ASP.NET CORE server side processing to acces to the files stored in FILE TABLE ?

sblb 1,166 Reputation points
2022-05-31T13:16:42.73+00:00

Hi,
first I want to create an ASP.NET core application linked to the FILE TABLE to open the files directly in my interface
After several attempts I was able to implement in my interface the links of my files to be able to consult them.
In the FILE TABLE I have 60000 files so the access to the file and directory of the FILE TABLE was not relevant.

I took the option to work server side processing to improve the performance.

I've created an class FileTable and the controller FileController

Questions :
_ Can I do a first migration to create a FILE TABLE?
_ If no, Should I create a class with the [NoMapped] attribute?
_ Can I use jquery Datatable with File Table?
_ How to use a controller to put the path of the files from the controller I put below?

I know these are not expert questions but I really need help on this.
thank you in advance

You will find below the class that I will need.

public class FileTable
     {
         public int Id { get; set; }
         public string Name { get; set; }
         public string Description { get; set; }
         public DateTime CreatedTimestamp { get; set; }
         public DateTime UpdatedTimestamp { get; set; }
         public string ContentType { get; set; }
     }


[Route("api/[controller]")]
     [ApiController]
     public class FileController : Controller
     {
         private readonly ApplicationDbContext context;
         public FileController(ApplicationDbContext context)
         {
             this.context = context;
         }

         [HttpPost]
         public IActionResult GetCustomers()
         {
             try
             {
                 var draw = Request.Form["draw"].FirstOrDefault();
                 var start = Request.Form["start"].FirstOrDefault();
                 var length = Request.Form["length"].FirstOrDefault();
                 var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
                 var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
                 var searchValue = Request.Form["search[value]"].FirstOrDefault();
                 int pageSize = length != null ? Convert.ToInt32(length) : 0;
                 int skip = start != null ? Convert.ToInt32(start) : 0;
                 int recordsTotal = 0;
                 var customerData = (from tempcustomer in context.FileDescriptions select tempcustomer);
                 if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
                 {
                     customerData = customerData.OrderBy(sortColumn + " " + sortColumnDirection);
                 }
                 if (!string.IsNullOrEmpty(searchValue))
                 {
                     customerData = customerData.Where(m => m.Name.Contains(searchValue)
                                                 || m.Description.Contains(searchValue)
                                                 || m.ContentType.Contains(searchValue));

                 }
                 recordsTotal = customerData.Count();
                 var data = customerData.Skip(skip).Take(pageSize).ToList();
                 var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
                 return Ok(jsonData);
             }
             catch (Exception ex)
             {
                 throw;
             }
         }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,274 questions
0 comments No comments
{count} votes

24 answers

Sort by: Most helpful
  1. sblb 1,166 Reputation points
    2022-06-01T16:34:20.473+00:00

    I confirm you I have a code that works quite well but as you know the display performance is not good because I work client side. ( Thanks for your help)
    I guess you understood I want to work server side.

    If you want to query the actual file table then use entity framework's raw query option

    I should be able to put in GetCustomer method var FileName= context.FileDescription.FromSqlRaw("EXECUTE dbo.wSerie" .ToList(); but is not good way!


  2. Vikas Lalwani 6 Reputation points
    2022-06-02T07:40:21.5+00:00

    I suppose you have referenced this article,

    https://qawithexperts.com/article/asp-net/jquery-datatable-server-side-processing-in-aspnet-core/417

    as code looks similar to what you have written in controller.

    I will suggest to you first connect your database by using Microsoft.EntityFrameworkCore.SqlServer Nuget package and also install Microsoft.AspNetCore.Mvc.NewtonsoftJson.

    Also configure DbContext properly, you don't need to run raw queries, better handle everything using Linq or lambda.

    performance is dependent on this part of code

    var data = customerData.Skip(skip).Take(pageSize).ToList();

    As we will only fetch required rows (like 10 rows only from database), based on currently viewed page.


  3. Armin Duraković 1 Reputation point
    2022-06-02T09:05:24.827+00:00

    Chech did you you included the file contents in the filetable query.

    Best regards

    0 comments No comments

  4. sblb 1,166 Reputation points
    2022-06-02T09:53:23.71+00:00

    @ AgaveJoe

    The first intention that I have is to put some elements from the file table (Name, Type, Date...) in FileDescription class to render it and have acces to the file.
    I don't use the procedure.
    This elements must put in GetCustomers method.
    1 - I need to recover the access path, I think to do that

         FileDescription results = _context.Set<FileDescription>().FromSqlRaw("SELECT FileTableRootPath() as Name").FirstOrDefaultAsync();
    

    2 - Put the element of file table in class FileDescription

    string[] FileName = context.FileDescriptions.FromSqlRaw("SELECT*FROM dbo.wSerie").ToList();
    

    The FileDescription has defined as below:

      public class FileDescription
        {
            [NotMapped]
             public string Name { get; set; } = string.Empty;
             public string Description { get; set; }
             public DateTime CreatedTimestamp { get; set; }
             public DateTime UpdatedTimestamp { get; set; }
             public string ContentType { get; set; }
        }
    

    I defined the ApplicationDbContext

     public class ApplicationDbContext : DbContext
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
            {
            }
            public DbSet<FileDescription> FileDescriptions { get; set; }
    
              protected override void OnModelCreating(ModelBuilder modelBuilder)
             {
                 modelBuilder.Entity<FileDescription>().HasNoKey().ToTable("FileDescription", t => t.ExcludeFromMigrations());
                 base.OnModelCreating(modelBuilder);
    
              }
        }
    

    Connextion
    "ConnectionStrings": {
    "DefaultConnection": "Data Source=servername;Initial Catalog=wSERIE;Trusted_Connection=True"
    }

    FileController

     [Route("api/[controller]")]
        [ApiController]
        public class FileController : Controller
        {
            private readonly ApplicationDbContext context;
            public FileController(ApplicationDbContext context)
               {
                   this.context = context;
               }
    
    
    
            [HttpPost]
            public IActionResult GetCustomers()
            {          
                try
                {
                    var draw = Request.Form["draw"].FirstOrDefault();
                    var start = Request.Form["start"].FirstOrDefault();
                    var length = Request.Form["length"].FirstOrDefault();
                    var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
                    var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
                    var searchValue = Request.Form["search[value]"].FirstOrDefault();
                    int pageSize = length != null ? Convert.ToInt32(length) : 0;
                    int skip = start != null ? Convert.ToInt32(start) : 0;
                    int recordsTotal = 0;
                    var customerData = (from tempcustomer in context.FileDescriptions select tempcustomer);
                    if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
                    {
                        customerData = customerData.OrderBy(sortColumn + " " + sortColumnDirection);
                    }
                    if (!string.IsNullOrEmpty(searchValue))
                    {
                        customerData = customerData.Where(m => m.Name.Contains(searchValue));
                                                   // || m.Description.Contains(searchValue)
                                                 //   || m.ContentType.Contains(searchValue));
    
                    }
                    recordsTotal = customerData.Count();
                    var data = customerData.Skip(skip).Take(pageSize).ToList();
                    var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
                    return Ok(jsonData);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
    

    The customerDatatable

    $(document).ready(function () {
        $('#customerDatatable').dataTable({
    
            "processing": true,
            "serverSide": true,
            "filter": true,
            "ajax": {
                "url": "/api/file",
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [{
                "targets": [0],
                "visible": false,
                "searchable": false
            }],
            "columns": [
              //  { "data": "id", "name": "Id", "autoWidth": true },
                { "data": "name", "name": "Name", "autoWidth": true },
                { "data": "description", "name": "Description", "autoWidth": true },
                { "data": "createdTimestamp", "name": "CreatedTimestamp", "autoWidth": true },
                { "data": "updatedTimestamp", "name": "UpdatedTimestamp", "autoWidth": true },
               { "data": "contentType", "name": "ContentType", "autoWidth": true },
    
            ]
    
        });
    });
    

  5. AgaveJoe 26,136 Reputation points
    2022-06-02T13:30:58.907+00:00

    In your FileTableRoot class, why do you put only one element?

    In the original design, the FileTableRoot class holds the file table root directory which a string. It's not clear why you changed the code.

    In my side I want to have several informations eg date, content type..

    You want to return the FileDescription, right? It seems like you changed this line...

    modelBuilder.Entity<FileTableRoot>().HasNoKey().ToTable("FileTableRoot", t => t.ExcludeFromMigrations());  
    

    to this line.

    modelBuilder.Entity<FileDescription>().HasNoKey().ToTable("FileDescription", t => t.ExcludeFromMigrations());  
    

    Rather than changing FileTableRoot to FileDescription in the DbContext, just add the FileDescription to the context.

    The DbContext should have the following pattern.

    public partial class ArchiveDbContext : DbContext  
    {  
        public ArchiveDbContext(DbContextOptions<ArchiveDbContext> options)  
            : base(options)  
        {  
        }  
      
        public DbSet<FileDescription>? FileDescriptions { get; set; }  
      
        protected override void OnModelCreating(ModelBuilder modelBuilder)  
        {  
            modelBuilder.Entity<FileTableRoot>().HasNoKey().ToTable("FileTableRoot", t => t.ExcludeFromMigrations());  
            modelBuilder.Entity<FileDescription>().HasKey(m => m.Id);  
            base.OnModelCreating(modelBuilder);  
        }  
    }  
    

    Next, add a migration and update the database. For example...

    add-migration NameOfTheMigration  
    update-database  
    

    Of course, this assumes you've added the required NuGet packages. See the official docs which covers code first migrations.

    Migrations Overview