c# – .net core console app suggestions

I have a .net core console app that gets some data from an external API and inserts it into a SQL database table. It is working as expected but I wonder if you guys have any suggestions to make it more maintainable, testable, robust, and dynamic. By the way, I will add logging when getting data from API, inserting it into the database and when gets exceptions.

Here is the code:

class Program
    {
        static async Task Main(string() args)
        {
                           
            var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {
                    //Setting up API Client
                    services.AddHttpClient("OrdersClient", client =>
                    {
                        client.BaseAddress =
                            new Uri("https://test/282675/orders?status=Created");

                        client.DefaultRequestHeaders.Add("Accept", "application/json");
                    });

                    services.AddSingleton<IHostedService, BusinessService>();

                    //Setting up app settings configuration
                    var config = LoadConfiguration();    
                    services.AddSingleton(config);
                });

            await builder.RunConsoleAsync();
       
        public static IConfiguration LoadConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            return builder.Build();
        }
    }

public class BusinessService : IHostedService
    {
        private IHttpClientFactory _httpClientFactory;
        private readonly IHostApplicationLifetime _applicationLifetime;
        private IConfiguration _configuration;
        public BusinessService(IHttpClientFactory httpClientFactory, IHostApplicationLifetime applicationLifetime, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _applicationLifetime = applicationLifetime;
            _configuration = configuration;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await MakeRequestsToRemoteService();
            //Stop Application
            _applicationLifetime.StopApplication();
        }

        public async Task MakeRequestsToRemoteService()
        {
            HttpClient httpClient = _httpClientFactory.CreateClient("OrdersClient");

            var authenticationBytes = Encoding.ASCII.GetBytes("test:1234");

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(authenticationBytes));
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await httpClient.GetAsync("https://test/282675/orders?startDate=1612126800000");
            Console.WriteLine(DateTime.Now);

            if (response.IsSuccessStatusCode)
            {
                Root orders = await response.Content.ReadAsAsync<Root>();

                if (orders.Content.Count > 0)
                {
                    foreach (var content in orders.Content)
                    {
                        Console.Write(content.CustomerId + " " + content.CustomerFirstName + " " + content.CustomerLastName + " " + content.CustomerEmail +" " + content.TotalPrice + " "+ content.InvoiceAddress.Phone + " " + content.Lines(0).ProductCode + " " +content.Lines(0).ProductName );
                        InsertData(content);
                    }
                }

            }
            
            
        }

        public void InsertData(Content content)
        {
           
            
            string connString = _configuration("ConnectionStrings:Development");
            using (SqlConnection sqlConnection = new SqlConnection(connString))
            {
                sqlConnection.Open();

                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = sqlConnection;
                    string sql = @"insert into Orders (id, customerId, firstName, lastName, phone, productCode, productName, price, orderDate, status) values (@id, @customerId, @firstName, @lastName, @phone, @productCode, @productName, @price, @orderDate, @status)";
                    command.CommandText = sql;
                    command.Parameters.Clear();
                    
                    try
                    {
                        command.Parameters.Add("id", SqlDbType.BigInt).Value = content.Id;
                        command.Parameters.Add("customerId", SqlDbType.Int).Value = content.CustomerId;
                        command.Parameters.Add("firstName", SqlDbType.VarChar).Value = content.CustomerFirstName;
                        command.Parameters.Add("lastName", SqlDbType.VarChar).Value = content.CustomerLastName;
                        command.Parameters.Add("phone", SqlDbType.VarChar).Value = content.InvoiceAddress.Phone;
                        command.Parameters.Add("productCode", SqlDbType.Int).Value = content.Lines(0).ProductCode;
                        command.Parameters.Add("productName", SqlDbType.VarChar).Value = content.Lines(0).ProductName;
                        command.Parameters.Add("price", SqlDbType.Float).Value = content.TotalPrice;
                        command.Parameters.Add("orderDate", SqlDbType.BigInt).Value = content.OrderDate;
                        command.Parameters.Add("status", SqlDbType.TinyInt).Value = 1; //Retrieved

                        command.ExecuteNonQuery();
                    }
                    catch (SqlException exception)
                    {
                        if (exception.Number == 2627) // Cannot insert duplicate key row in object error
                        {
                            Console.WriteLine("Duplicates...");
                        }
                        else
                            throw; // Throw exception if this exception is unexpected
                    }
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }

c# – Blocked by CORS policy Angular 10 and .net core

I’m facing a problem related to CORS with .net CORE 3.1, i’m trying to reach api with an Angular 10 front end and i’m getting this message in the console :Access to XMLHttpRequest at ‘http://localhost:23645/api/MyController/GetAllSimulationByUser’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

this the code of my front request :

export class AppService {

  header: HttpHeaders;
  url: string;
  constructor(private Http: HttpClient) {
    this.header = new HttpHeaders({
      'Access-Control-Allow-Origin': '*' ,
      'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
      'content-type': 'application/json'
  });
getAllSimulation() {
    return this.Http.get(this.url + '/MyController/GetAllSimulationByUser', {headers:this.header});
  }

this is what i added in startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
services.AddCors(opt => opt.AddPolicy("CorsPolicy", c =>
                {
                    c.WithOrigins("http://localhost:4200")
                       .AllowAnyHeader()
                       .AllowAnyMethod();
                }));
}

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            try
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseRouting();
                app.UseCors("CorsPolicy");
}
}

in a launchSettings.json i set this :

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:23645",
      "sslPort": 0
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyAPI": {
      "commandName": "Project",
      "launchBrowser": false,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }
  }
}

and finally i decorated my controller and my method like this :

 (EnableCors("CorsPolicy"))
   
    (Route("api/(controller)"))
    (ApiController)
    public class MyController : ControllerBase
    {
       (EnableCors("CorsPolicy"))
        (HttpGet)
        (Route("GetAllSimulationByUser"))
        public IEnumerable<Type> GetAllSimulationByUser()
        {
           //my code
                
        }
    }

Can anyone have an answer to this question? thanks

c# – Web Components/Redux with .NET Core MVC viable?

I’m currenty building several new themes using NopCommerce, a .NET e-commerce platform using the MVC architecture.

NopCommerce exposes a lot of services to you for communicating with the db, and is itself built with the Entity Framework code first approach.

Overall, I think NopCommerce is pretty well-rounded, the platform is pretty extensive and very easy to get up and running, decent developer experience and whatnot. The only thing I am missing from the platform is a built-in way of creating asynchronous views.

The NopCommerce team currently uses a lot of jQuery for updating some certain DOM-elements, such as a cart drawer, cart quantity indicator, toasters and some other things. I would prefer to exclude jQuery from the project completely, as I don’t feel new developers at work should have to learn jQuery in 2021.

We have discussed using some sort of front end framework for asynchronous UI components for some time now, but are hesitant to include React or Angular due to 1) the bundle size and 2) the need for our developers to also learn these frameworks. Preact was an option but painpoint 2 was still being hit. We also don’t want to do everything “vanilla”, but if we would, one concern was how long time it would take to craft such an implementation compared to the benefits it would give.

We came across Web Components and noticed that the support is pretty good now, and there is an official polyfill for the V1 spec. It also results in pretty neat looking DOM-structure, and is very lightweight (<1kb), and also has the webcomponent-redux npm package available for dead-simple redux-bindings!

Initially, it looks promising, but again, questions are raised.. Is the time to make this work worth it? It probably wouldn’t take very long to make one async components in this manner, but since you can make web components in so many ways (https://webcomponents.dev/blog/all-the-ways-to-make-a-web-component/), I’m very unsure what a good approach would be for our specific case.

As an example: Basically, we are going to take the existing (synchronous) “GetProductsByFilters” endpoint, and rewrite it to return JSON instead, which our Web Component would then request when filters are changed by a customer, then rendering the new product grid asynchronously instead of rerendering the page.

If anyone has any experience with .NET Core and Web Components, and with redux in particular (or a self-built implementation?), I would appreciate any input you have!

Bonus: Also interested in thoughts about a monorepo for said Web Components!

All the best

asp.net – Definir un formato para un atributo datetime en un modelo usando .NET

tengo el siguiente modelo:

using System;
using System.ComponentModel.DataAnnotations;

namespace BAT.Models
{
    public class Base
    {
        (Key)
        public int Id { get; set; }

        (DataType(DataType.Date))
        public DateTime FechaCreacion { get; set; }
    }
}

Mi idea es definir un formato para que en la vista se muestre automáticamente el formato que defina en el modelo. Actualmente en la vista se me muestran las fechas con el formato mes/día/año horas/minutos/segundos, pero yo quiero el formato horas/minutos/segundos día/mes/año. Ya sé que podría usar la función ToString() y darle el parámetro adecuado, pero eso me implica aplicar la función para cada parte donde se muestra la fecha.

¡Gracias de antemano!

.net – Resultados são diferentes no VB e no C#

Estou tentando utilizar uma formula que me da o resultado esperado em C#, ao traduzir o código pra VB.NET o resultado é completamente diferente.
Tenho quase certeza de que fiz a tradução corretamente. Será que esqueci de algo?

Formula em C#:

double x = 199025 / (double)(1 << 19) * 360.0 - 180;
// Resultado: -43.3403778076172

Link pra testar online: https://onlinegdb.com/uUuQD8kMG

Formula em VB.NET:

Dim x as Double = 199025 / CType((1 << 19) * 360.0 - 180, Double)
// Resultado: 0.00105447339908394

Link pra testar online: https://onlinegdb.com/02c5RaQTP

Application won’t recognise net framework 4.8.0 but I’ve already got it installed?

I have and application I’ve downloaded.
I try to start it and a net framework error comes up saying it needs net framework version 4.8.0 to work.
I downloaded the version and it says it’s already installed.
Can anyone help me?
The application won’t start up even though I have the software and I’m getting a little frustrated 😐

c# – Aplicação .NET online + Offline

É o seguinte, há hoje alguma forma ou ferramenta que permita gravar os dados em um banco offline caso a internet do cliente caia? Vou explicar melhor, a minha aplicação é Web, feita em .Net, roda totalmente do Browser e a princípio, vai gravar tudo no banco online, mas e se a conexão do cliente cair? Eu precisaria que esses dados fossem gravados na máquina do cliente localmente, para quando a conexão voltasse, todos essa informação armazenada localmente fosse lançada no banco de dados online. O que vocês acham?

Obrigado.

.net – Generate word reports from api or database

Suppose we have a web (asp.net core 5) application that

  • saves some data in (sql server) database;
  • exposes an API to obtain some sets of the data in json format;

We would like to generate reports from the available data.
The reports should be downloaded by users and eventually edited (“download report as MS Word” would be a solution)

I saw the “standard” approach would be to use the “Open XML SDK by Microsoft” to directly generate the Word document from database/asp.net core business objects.

  • did you faced such situation?
  • what would you recommend as report generating tool in such cases?

Publish Guest Post On Squareblogs. net Do-Follow and Permanent Backlinks for $1

Publish Guest Post On Squareblogs. net Do-Follow and Permanent Backlinks

Hello Everyone

Please if you need Sample Contact Us any time.

My requirements:

  1. your Website URL (1 URL each 1 Post )
  2. your Keyword ( 1 Keyword each Post )
  3. your Article ( if you don’t have an Article you can buy it Article in my Extras Below)

Squareblogs.net GOOGLE Metrics:

★ Domain Authority (DA): 59

★ Page Authority (PA): 70

★ Check Indexed Pages: Click Here

FAQ:

Q: Are all the Links are Dofollow?

A: yes,100% Dofollow

Q: Is All the links are permanent?

A: Yes

Q: How many Link allowed Per Post?

A: We will allow only 1-2 link to each article

Q: Do you accept all niches?
A: No, we won’t accept all, No adult, Sexual, Gambling, Casino, or any type of illegal links


Q: How many keywords allowed in this order

A: We will allow 2 keywords maximum.

Please If you have any Question don’t hesitate to contact me

Thanks

.(tagsToTranslate)Guest(t)Post(t)Squareblogs(t)Do-Follow(t)DOFOLLOW(t)Backlinks(t)guestblog

asp.net core – .net 5 identity for different types of users

Hello awesome peeps I was working on a project on .net 5 and the system have 2 users with their own admin panel on is for staff and one is for customers, the staff admins can create other staff and assign them roles and permission so doest the customers they can assign their employees any roles and permission. I am using .net Identity and what is the best way to do this? should I add the users in a one table AspNetUsers table and differ them through their roles or is there any way that I can create staff and customer and do all the identity features and stuff on two different user tables? I am a newbie and am a little confused any help is appreciated!