c# – When Receiving/Returning data in controller action – DateTime conversion between UTC and Epoch in Asp.net core WebAPI

I was wondering what would be a better approach designing a system which deals with UTC DateTime in the service and Database layer but needed to send and receive the DateTime in Epoch format from remote agents.

Consider the following Class (model):

public class UserProfile
{
    (DataType(DataType.EmailAddress))
    public string Email { get; set; }

    public DateTime SomeDate { get; set; }
}

Now if if the APIs needs the value of the SomeDate to be in Epoch format (like Dotnet long type instead of DateTime but the system needs to have the data in UTC DateTime format to process and store in the service codes.

Considering there would be many REST APIs and different models, what would be a global solution to handle the issue. Can this be solved with auto mapper or action filter or something like that?

c# – Asp.Net overall design pattern integrating REST, dependency injection, and Hosted Services (See full project at Github)

I’m new to C#, and want to conform as much as possible to good design patterns. This code is the beginning of a Microservice, running as Asp.Net. It is based on a Microsoft tutorial doing similar work.

It has three functional components currently:

  1. Converts a CSV file to JSON, for return via REST
  2. A REST controller to test the conversion of the CSV to JSON return
  3. A background service which monitors a directory looking for changed files. The file attributes (Path, Date, Checksum) are stored in a MongoDB database via a Repository.

Opinions/Recommendations regarding the design patterns welcomed.

The full code can be found at: https://github.com/BioComSoftware/unite-radimaging-source-n2m2.git

BONUS: Notice in FileSearchHostedService.cs, I instantiate the Repository objects explicitly. I think it would be more appropriate to have them as Dependency Injection – but I couldn’t get it to work. Notice the commented-out lines that would have done this. My understanding is; I would need to do this with IScopedProcessingService – but I have no idea how to do this with this specific code.

Structure

(Startup.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime.
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {

            services.AddControllers();

            services.AddScoped<IFoundFileContext, FoundFileContext>();
            services.AddScoped<IFoundFileRepository, FoundFileRepository>();
        }

        // This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseExceptionHandler("/error");
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { 
                endpoints.MapControllers(); 
            });
        }
    }
}

(FoundFileRepository.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Entities;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2.Repositories {
   public class FoundFileRepository : IFoundFileRepository {
       private readonly IFoundFileContext _context;
       public FoundFileRepository(IFoundFileContext context) {
           _context = context ?? throw new ArgumentNullException(nameof(context));
       }

       public async Task<IEnumerable<FoundFile>> GetFiles() {
       return await _context
           .FoundFiles
           .Find(p => true)
           .ToListAsync();
       }

       public async Task<FoundFile> GetFile(string id) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Id == id)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByPath(string path) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Path == path)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByChecksum(string checksum) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Checksum == checksum)
                          .FirstOrDefaultAsync();
       }

       //public async Task<IEnumerable<FoundFile>> GetFileByMtime(string mtime) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<DateTime>(p => p.Mtime, mtime);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       //public async Task<IEnumerable<FoundFile>> GetFileBySize(long size) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<long>(p => p.Size, size);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       public async Task CreateFile(FoundFile foundFile) {
           await _context.FoundFiles.InsertOneAsync(foundFile);
       }

       public async Task<bool> UpdateFile(FoundFile foundFile) {
           var updateResult = await _context.FoundFiles.ReplaceOneAsync(
               filter: g => g.Path == foundFile.Path, replacement: foundFile);
           return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0;
       }

       public async Task<bool> DeleteFile(string path) {
           FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.Eq(p => p.Path, path);

           DeleteResult deleteResult = await _context
                                               .FoundFiles
                                               .DeleteOneAsync(filter);

           return deleteResult.IsAcknowledged
               && deleteResult.DeletedCount > 0;
       }
   }
}

(FileSearchHostedService.cs)

using unite.radimaging.source.n2m2.Repositories;
using unite.radimaging.source.n2m2.Entities;
using unite.radimaging.source.n2m2.Data;
using Serilog;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace unite.radimaging.source.n2m2.HostedServices {
    public class FileSearchHostedService : BackgroundService {
        private readonly IConfiguration _configuration;
        //private IFoundFileRepository _repository;

        public FileSearchHostedService(
            //IFoundFileRepository repository,
            IConfiguration configuration
            ) {
            //_repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken) {
            Log.Information("FileSearchHostedService: File searching started.");

            cancellationToken.Register(() => Log.Information("Processing service stopped"));

            //string checksum;
            string _current_path;
            FileInfo _current_file;
            FoundFile _foundFile;
            FoundFile _existingFile;
            FoundFile _addFoundFile;
            FoundFileContext FoundfileContext = new FoundFileContext(_configuration); // Normal instantiation, in leiu of injection
            FoundFileRepository _repository = new FoundFileRepository(FoundfileContext);  // Normal instantiation, in leiu of injection

            while (!cancellationToken.IsCancellationRequested) {
                Log.Information("Searching files...");
                string dir = _configuration.GetValue<string>("FileSearchSettings:SearchDir");
                string() files = Directory.GetFiles(dir);
                foreach (string filename in files) {
                    Log.Debug($"Parsing '{filename}'");

                    _current_file     = new FileInfo(filename);
                    _current_path = Path.GetFullPath(Path.Combine(_current_file.Directory.ToString(), _current_file.Name));

                    _foundFile = new FoundFile() {
                        Path = _current_path,
                        Size = _current_file.Length,
                        Mtime = _current_file.LastWriteTime,
                        Checksum = FileChecksum.getChecksum(filename)
                    };
                    Console.WriteLine("==========================");
                    _existingFile = await _repository.GetFileByPath (_current_path);
                    Console.WriteLine("past _repository.GetFileByPath");

                    try {
                        Console.WriteLine($"{_existingFile.Path} exists!!!");
                        Console.WriteLine($"     _existingFile.Checksum: {_existingFile.Checksum}");
                        Console.WriteLine($"     _existingFile.Length = {_existingFile.Size}");
                        Console.WriteLine($"     _existingFile.LastWriteTime = ({_existingFile.Mtime}");
                    }
                    catch {
                        Console.WriteLine($"Creating MongoDB for file {_foundFile.Path} ");
                        _addFoundFile = new FoundFile() {
                            Path = _foundFile.Path,
                            Size = _foundFile.Size,
                            Mtime = _foundFile.Mtime,
                            Checksum = _foundFile.Checksum
                        };
                        await _repository.CreateFile(_addFoundFile);
                    }
                }

                await Task.Delay(
                    _configuration.GetValue<int>("FileSearchSettings:Delay"),
                    cancellationToken
                    );
            }
        }
    }
}

c# – …an error occurred during the pre-login handshake… asp.net MVC core

BandaCRUD.cs

using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace BandaAPI.Models
{
public class BandaCRUD //127.0.0.1
{//”Server=localhost,3306;uid=root;pwd=;database=myband; Trusted_Connection=True;MultipleActiveResultSets=true;Persist Security Info=False”;
//”SqlConnection”: “Server=localhost,3306;uid=root;pwd=;database=myband;Trusted_Connection=True;MultipleActiveResultSets=true;Persist Security Info=True;”
string connectionString = “Server=localhost,3306;uid=root;pwd=;database=myband”;
public IEnumerable GetAllBandas()
{
List bandaaList = new List();

        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("GetAllBandas", con);
            cmd.CommandType = CommandType.StoredProcedure;
         //   con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Banda bandaa = new Banda();
                bandaa.Id = Convert.ToInt32(dr("Id").ToString());
                bandaa.Name = dr("Name").ToString();
                bandaa.MacAddress = dr("MacAddress").ToString();
                bandaa.AuthKey = dr("AuthKey").ToString();

                bandaaList.Add(bandaa);
            }
            con.Close();
        }
        return bandaaList;
    }



    // To Insert Banda

    public void AddBanda(Banda bandaa)
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
                    SqlCommand cmd = new SqlCommand("InsertBandas", con);
                    cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@Name", bandaa.Name);
            cmd.Parameters.AddWithValue("@MacAddress", bandaa.MacAddress);
            cmd.Parameters.AddWithValue("@AuthKey", bandaa.AuthKey);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    //To Update Banda

    public void UpdateBanda(Banda bandaa)
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand("UpdateBandas", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@NId", bandaa.Id);
            cmd.Parameters.AddWithValue("@Name", bandaa.Name);
            cmd.Parameters.AddWithValue("@MacAddress", bandaa.MacAddress);
            cmd.Parameters.AddWithValue("@AuthKey", bandaa.AuthKey);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    //To Delete Banda

    public void DeleteBanda(int? Id)
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand("DeleteBandas", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@Id", Id);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
//Get Bandas por Id

public Banda GetBandasById(int? Id)
{
    Banda bandaa = new Banda();

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("GetBandasById", con);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Id", Id);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {

            bandaa.Id = Convert.ToInt32(dr("Id").ToString());
            bandaa.Name = dr("Name").ToString();
            bandaa.MacAddress = dr("MacAddress").ToString();
            bandaa.AuthKey = dr("AuthKey").ToString();

        }
        con.Close();
    }
    return bandaa;
}

}
}
Banda.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BandaAPI.Models
{
public class Banda
{
public int Id { get; set; }
(Required)
public string Name { get; set; }
(Required)
public string MacAddress { get; set; }
(Required)
public string AuthKey { get; set; }

}

}
Startup.cs

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using BandaAPI.Data;

namespace BandaAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddDbContext<BandaAPIContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("connectionString")));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

}
BandaController.cs

using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BandaAPI.Models;

namespace BandaAPI.Controllers
{
public class BandaController : Controller
{
BandaCRUD bandacrud = new BandaCRUD();
public IActionResult Index()
{
List bandaList = new List();
bandaList = bandacrud.GetAllBandas().ToList();

        return View(bandaList);
    }
    (HttpGet)
    public IActionResult Create()
    {
        return View();
    }
    (HttpPost)
    (ValidateAntiForgeryToken)
    public IActionResult Create((Bind) Banda objbanda)
    {
        if (ModelState.IsValid)
        {
            bandacrud.AddBanda(objbanda);
            return RedirectToAction("Index");
        }
        return View(objbanda);
    }
    public IActionResult Edit(int? Id)
    {
        if (Id == null)
        {
            return NotFound();
        }
        Banda banda = bandacrud.GetBandasById(Id);
        if (banda == null)
        {
            return NotFound();
        }
        return View(banda);
    }
    (HttpPost)
    (ValidateAntiForgeryToken)
    public IActionResult Edit(int? Id,(Bind) Banda objbanda)
    {
        if (Id == null)
        {
            return NotFound();
        }
       if (ModelState.IsValid)
        {
           bandacrud.UpdateBanda(objbanda);
            return RedirectToAction("Index");
        }
        return View(bandacrud);
    }
    (HttpGet)
    public IActionResult Details(int? Id)
    {
        if(Id == null)
        {
            return NotFound();
        }
        Banda banda = bandacrud.GetBandasById(Id);
        if (banda == null)
        {
            return NotFound();
        }
        return View(banda);
    }
    public IActionResult Delete(int? Id)
    {
        if (Id == null)
        {
            return NotFound();
        }
        Banda banda = bandacrud.GetBandasById(Id);
        if (banda == null)
        {
            return NotFound();
        }
        return View(banda);
    }
    (HttpPost,ActionName("Delete"))
    (ValidateAntiForgeryToken)
    public IActionResult DeleteBanda(int? Id)
    {
        bandacrud.DeleteBanda(Id);
        return RedirectToAction("Index");
    }
}

}

How to render dynamically created HTML string into razor view in Asp.NET Core

I have written html helper method as below

 public static class CustomHtmlHelper
{
    public static HtmlString SetMenuRespectiveWithRoles(this IHtmlHelper html, HttpContext context)
    {
        StringBuilder menu = new StringBuilder();
        string menuLink = string.Format("<a asp-area='{0}' asp-controller='{1}' asp-action='{2}'>{3}</a></li>", "AreaName", "ControllerName", "ActionName", "Menu Name");
        return new HtmlString(menu.ToString());
    }
}

And calling it from layout as –

 @Html.SetMenuRespectiveWithRoles(Context)

It renders on browser as –

<a asp-area="AreaName" asp-controller="ControllerName" asp-action="ActionName">MenuName</a>

I was expecting that it will render as

<a href="AreaName/ControllerName/ActionName">MenuName</a>

I don’t want to create html tag using TagHelpers class.

Can you please guide how can we render dynamically created string in .net core razor page?

asp.net core – Session Scoped Dependency Injection vs Caching in Data Access Layer

The issue at hand is that I don’t want to repeatedly hit the DB to look up user information for the logged in user over the course of the many requests made within a single session.

My first inclination is to use Session Scoped Dependency Injection, however this isn’t possible with out of the box DI features provided by Microsoft. I could install Autofac and that seems like a perfectly reasonable solution to me, however I seem to recall reading why Microsoft didn’t include the ability to do this because they felt it was a bad practice… but I don’t recall what their reasons were at the moment.

Then it occurred to me that the way people at Microsoft would probably handle this is through the fact that Entity Framework would just cache the results. However, I’m not using EF and the solution I’m using does not provide caching though I could easily add some caching to it.

So I’m wondering if I should 1) Install Autofac or 2) Add caching features to my data access layer.

Are there any serious reasons I should avoid 1) (i.e. not avoid installing Autofac generally, but doing it for the purpose of using Session Scoped DI, obviously)? Because I think that’s what I will probably end up doing unless I can find a substantial reason not to.

sql server – Mandar a select2 ubicado en un modal un valor a editar ASP.Net mvc

espero esten bien y saber si alguien me puede orientar en como hacer lo siguiente, lo que pasa es que tengo un modal de registro de datos, en el cual tengo un select2 que estoy cargando mediante ajax de la siguiente manera:

 $("#Departamento").select2({
        dropdownParent: $('#modalEmpleado'),
        ajax: {
            url: 'https://' + location.host + '/Empleado/GetDepartamentosSelect2',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    name: params.term
                };
            },
            processResults: function (data, params) {
                Departamentos = data.listaSelect2;
                params.page = params.page || 1;
                return {
                    results: data.listaSelect2,
                    pagination: {
                        more: (params.page * 2) < data.count_filtered
                    }
                }                 
            },
        }
    });

En el controlador resivo la peticion de esta manera:

 public async Task<JsonResult> GetDepartamentosSelect2(string name)
    {
        List<spr_GetDepartamentos> getListaDepartamentos = new List<spr_GetDepartamentos>();
        using (var db = new AppDbContext())
        {
            getListaDepartamentos = await db.Set<spr_GetDepartamentos>().SqlQuery
                                                ("EXEC spr_GetDepartamentos").ToListAsync();

            var listaSelect2 = getListaDepartamentos.Select(x => new
            { id = x.Id, text = x.Nombre }).ToList();

            if (!(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name)))
            {
                listaSelect2 = listaSelect2.Where(x => x.text.ToLower().StartsWith(name.ToLower())).ToList();
            }
            var jsonResult = Json(new { listaSelect2 }, "application/json",
            System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }
    }

Los datos los carga correctamente, el problema que noto, es que no me llena automaticamente en la etiqueta select los valores en el option, para asi despues al momento de querer editar algun elemento que esta en el select2 poder mandarlo llamar asi: **$('#Departamento').val(n).trigger('change');** y que me muestre en el select2 el dato que este en el val(n), asi es como tengo en el html la etiqueta

<div class="form-group">
                        <div class="row">
                            <div class="col-12 col-sm-12">
                                <label>Departamento</label>
                                <select class="Departamento" id="Departamento" name="Departamento"></select>
                            </div>
                        </div>
                    </div>

development – Unable to use “OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext” inside ASP.NET core (.NET 5)

I have the following CSOM code inside my ASP.NET CORE (.NET 5.0):-

var siteUrl = config.GetSection("SP").GetSection("SiteURL").Value;           
string clientId = "****";
string clientSecret = "***";

     using (ClientContext context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret))

        {

but i am getting this error:-

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'OfficeDevPnP.Core.Utilities.TokenHelper' threw an exception.
  Source=OfficeDevPnP.Core
  StackTrace:
   at OfficeDevPnP.Core.Utilities.TokenHelper.set_Realm(String value)
   at OfficeDevPnP.Core.AuthenticationManager.EnsureToken(String siteUrl, String realm, String appId, String appSecret, String acsHostUrl, String globalEndPointPrefix)
   at OfficeDevPnP.Core.AuthenticationManager.GetAppOnlyAuthenticatedContext(String siteUrl, String realm, String appId, String appSecret, String acsHostUrl, String globalEndPointPrefix)
   at OfficeDevPnP.Core.AuthenticationManager.GetAppOnlyAuthenticatedContext(String siteUrl, String appId, String appSecret)
   at ServiceDeskSharePointIntegration.Program.Main(String() args) in C:Users****sourcereposServiceDeskSharePointIntegrationServiceDeskSharePointIntegrationProgram.cs:line 47

Inner Exception 1:
TypeLoadException: Could not load type 'System.Web.Configuration.WebConfigurationManager' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

when i hover over the related package i got this error:-

enter image description here

asp.net – Erro ao adicionar controlador mvc usando o entity framework

Estou tentando criar uma aplicação MVC usando Entity Framework Core, e o Asp.Net Core MVC 5, usando o MySql através do Pomelo.EntityFrameworkCore.MySql, a classe de domínio é definida como:

public class Aluno
{
    (Key)
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    (DisplayFormat(DataFormatString ="{0:dd/MM/yyyy", ApplyFormatInEditMode = true))
    public DateTime DataNascimento { get; set; }
}

Meu DbContext é definido como:

 public class EscolaDbContexto: DbContext
{
    

    public EscolaDbContexto(DbContextOptions options):base(options)
    {
        

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        List<Aluno> seed = new List<Aluno>()
        {
            new Aluno(){Nome = "Sebastião", DataNascimento = Convert.ToDateTime("31/07/1984")},
            new Aluno(){Nome = "José", DataNascimento = Convert.ToDateTime("01/03/1985") },
            new Aluno(){Nome = "Pedro", DataNascimento = Convert.ToDateTime("01/07/1987") }


        };
        modelBuilder.Entity<Aluno>().HasData(seed);
    }
    public DbSet<Aluno> Albuns { get; set; }
    
}

E meu appsetings.json é definido como:


"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"EscolaDbContext": "server=127.0.0.1;port=3306;database=escolaDb;uid=root;password=1234"
},
"AllowedHosts": "*"

Alem de configurar no Startup.cs da sequinte gorma


public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext(options => options
.UseMySql(Configuration.GetConnectionString("EscolaDbContext")));
}

No entanto quando tento criar um controller usando o gerador de código “Controlador MVC com exibições, usando o Entity Framework, selecionando a classe Aluno, como domínio e EscolaDbContext como contexto de dados, aparece o seguinte erro:

inserir a descrição da imagem aqui

O que eu estou fazendo de errado?

sql server – Error al convertir string a Datetime en ASP.NET Core

estoy tratando de convertir un string a formato fecha en .net Core pero me da error al convertirlo , estoy implementando el Convert.ToDateTime(string) en ambos campos , uno en mi variable de entrada y otro en mi atributo de tidad ya que también es un string . Lo que quiero es poder convertirlo en datetime para poder hacer un filtro de fecha desde – hasta y poder listar las fecha desde ese rango

este es mi código

public List<Stock_Cliente> visualizarMov(StockClienteFil stk)
        {
            DateTime fechaDesde = Convert.ToDateTime(stk.fec_mov_des);
            DateTime fechaHasta = Convert.ToDateTime(stk.fec_mov_has);

            var visualizarMov = _quimpacContex.Stock_Cliente.Where(x => x.stk_cli_des_alm.Contains(stk.des_alm) && x.stk_cli_des_mat.Contains(stk.des_mat)
             && x.stk_cli_num_lot.Contains(stk.num_lot) && x.stk_cli_ser_pre.Contains(stk.ser_pre) && x.stk_cli_buq.Contains(stk.cli_buq)
             && Convert.ToDateTime(x.stk_cli_fec_mov) >= fechaDesde && Convert.ToDateTime(x.stk_cli_fec_mov) >= fechaHasta).ToList();
           
            return visualizarMov;
        }

este es mi clase Stock_Cliente

public class Stock_Cliente
    {
        (Key)
        public int stk_cli_cod { get; set; }
        public string stk_cli_cod_cen { get; set; }
        public string stk_cli_des_cen { get; set; }
        public string stk_cli_cod_cli { get; set; }
        public string stk_cli_des_cli { get; set; }
        public string stk_cli_cod_alm { get; set; }
        public string stk_cli_des_alm { get; set; }
        public string stk_cli_num_mat { get; set; }
        public string stk_cli_des_mat { get; set; }
        public string stk_cli_uni_med { get; set; }
        public string stk_cli_num_lot { get; set; }
        public string stk_cli_fec_mov { get; set; }
        public string stk_cli_ser_pre { get; set; }
        public decimal stk_cli_can { get; set; }
        public string stk_cli_buq { get; set; }
        public string stk_cli_fec_lle { get; set; }
        public string stk_cli_hor_lle { get; set; }
        public string stk_cli_fec_sal { get; set; }
        public string stk_cli_hor_sal { get; set; }
        public string stk_cli_est { get; set; }
        public DateTime? stk_cli_fec_cre { get; set; }
        public string? stk_cli_usu_cre_sap { get; set; }
        public DateTime? stk_cli_fec_mod { get; set; }
        public string? stk_cli_usu_mod_sap { get; set; }
    }

este es el json que le envío

{
    "des_alm":"Tanque TKG13",
    "des_mat":"ACEITE",
    "num_lot":"CN-S",
    "ser_pre":"Despacho",
    "cli_buq":"PAB4168",
    "fec_mov_des":"20/12/2019",
    "fec_mov_has":"25/03/2019"
}

esta es mi tabla en mi bd
introducir la descripción de la imagen aquí

este es el error que me genera

System.InvalidOperationException: 'The LINQ expression 'DbSet<Stock_Cliente>()
    .Where(s => s.stk_cli_des_alm.Contains(__stk_des_alm_0) && s.stk_cli_des_mat.Contains(__stk_des_mat_1) && s.stk_cli_num_lot.Contains(__stk_num_lot_2) && s.stk_cli_ser_pre.Contains(__stk_ser_pre_3) && s.stk_cli_buq.Contains(__stk_cli_buq_4) && Convert.ToDateTime(s.stk_cli_fec_mov) >= __fechaDesde_5 && Convert.ToDateTime(s.stk_cli_fec_mov) >= __fechaHasta_6)' could not be translated. Additional information: Translation of method 'System.Convert.ToDateTime' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information.
Translation of method 'System.Convert.ToDateTime' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

.net – Access ASP.NET Core HttpContext.Session in Custom RequestCultureProvider

In our ASP.NET Core web app, I need to be able to access HttpContext.Session within a Custom RequestCultureProvider I’ve written. There is alot of background here… To be brief, I’ll just mention that the business requirement is that I’m trying to meet, is to be able to display data in at least two different cultures, in our web app. A user may navigate to one page, where it should display in fr-FR and navigate to another page where it should display in zh-CN.

I have all of this working, when it comes to the “Response” from the server. By using an ActionFilter on a per-Action basis I can set the current thread’s culture to whatever I want. We look up the various cultures from a database and store them in Session and then n the ActionFilter, based on an argument I pass to the ActionFilter method… I can even load ViewComponents via Controller Actions in the various cultures and have each view component display with a different culture setting. Given this, you can see why I can’t store session in a Cookie or use the Querystring.

But the PROBLEM comes into play with “Requests” to the server, like when I edit Form data in a view and Submit/post the data back to an Action.
When I do that, my Dates are sent back in as NULL. BTW, I do Model binding and I have my dates marked with this attributes in my ViewModels:

    (DataType(DataType.Date))
    (DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}"))

According to the well written article below, the order in which the Request culture is looked up, is:

https://www.jerriepelser.com/blog/how-aspnet5-determines-culture-info-for-localization/

  1. From the query string
  2. From a cookie
  3. From the Accept-Language HTTP header
  4. From the DefaultRequestCulture property of the RequestLocalizationOptions class
  5. From the thread culture

I can certainly verify the above. If I use a cookie, it works. If I add French fr-FR as the first language in Chrome Settings, it works. If I change my default request culture in my Startup localization to fr-FR, it works…
For example, in the web page a Kendo DatePicker (or even an tag) will contain a French date like “14-août-2019”, yet when I post it back to an Action, it is NULL unless I’ve set the querystring, cookie, Accept-Language or DefaultRequestCulture to fr-FR.

One odd thing is that #5 says it should use the current Thread Culture, and in my Action that I post Form data to I check the current thread’s culture, and it is indeed fr-FR, so I don’t know why my french dates are not being recognized…

So what I tried to get around this was to clear out all of those default providers and write a custom provider.
In Startup.ConfigureServices, I now do this:

        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new()
            {
                new CultureInfo("en-US"),
                new CultureInfo("fr-FR"),
                new CultureInfo("zh-CN"),
                new CultureInfo("en-IE"),
            };

            var defaultCultureSettingOverride = this.Configuration.GetSection("appsettings").GetValue<string>("DefaultCultureOverride");
            defaultCultureSettingOverride = defaultCultureSettingOverride == null ? "en-US" : defaultCultureSettingOverride;

            options.DefaultRequestCulture = new RequestCulture(defaultCultureSettingOverride);
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            options.RequestCultureProviders.Clear();
            options.RequestCultureProviders.Insert(0, new MyCustomRequestCultureProvider()
            {
                Options = options,
            });
        });

And that works too, as long as my MyCustomRequestCultureProvider returns the correct culture!

My problem now is: I NEED to be able to access Session state in my custom RequestCultureProvider. But the HttpContext sent into DetermineProviderCultureResult has a null Session. Why? Is it the wrong place in the pipeline?

And when I call options.RequestCultureProviders.Insert(0, , new MyCustomRequestCultureProvider() in ConfigureServices, I don’t have access yet (as far as I can tell) to the HttpContextAccessor.
If I pass new MyCustomRequestCultureProvider(new HttpContextAccessor()), that does me no good…
And while I have access to IHttpContextAccessor accessor as a parameter passed into Startup.Configure, I can’t do the same thing with Startup.ConfigureServices. If I add (IHttpContextAccessor accessor) as an additional parameter to ConfigureServices, .NET Core errors when I run it, telling me that method can only access an IServicesCollection parameter.

I’m at a dead end…