.NET Archives - Tech Insights https://reactconf.org/category/dotnet/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Wed, 10 Jan 2024 05:29:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 .NET Archives - Tech Insights https://reactconf.org/category/dotnet/ 32 32 230003556 .NET 8 Release New Data Annotation in ASP.NET Core C# https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/ https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/#respond Wed, 10 Jan 2024 05:29:25 +0000 https://labpys.com/?p=2216 In this article, we will learn .NET 8 Release New Data Annotation in ASP.NET Core C#, along with explanations and code examples. Data Annotations in ASP.NET Core are attributes and …

The post .NET 8 Release New Data Annotation in ASP.NET Core C# appeared first on Tech Insights.

]]>
In this article, we will learn .NET 8 Release New Data Annotation in ASP.NET Core C#, along with explanations and code examples.

Data Annotations in ASP.NET Core are attributes and constraints that can be applied to an entity class or model properties to define validation rules.

  • Data Annotation attributes are used to control and validate input data either at the user interface level or at the database level.
  • Data annotations are a key feature of the .NET framework and can help make your code more efficient, easier to maintain, and more secure.

Required attribute

The Required attribute has been revised and has new parameters. In .NET 8 you can use DisallowAllDefaultValues property with the attribute so that the required attribute for the Guid member will work as expected.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        [Required(DisallowAllDefaultValues = true)]
        public Guid Id { get; set; }
    }
}

AllowedValues

AllowedValues is a new attribute that specifies which values are allowed for a string.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [AllowedValues("Computer","Eelectronics","Mechanical")]
        public  string DepartmentName { get; set; }
        
    }
}

BASE64String

The Base64string attribute ensures that the content is a complaint Base64 string.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Base64String]
    public string Address { get; set; }     
    }
}

Range

Specify the numeric range constraints for the value of a property.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Range(0, 100, MinimumIsExclusive = true, MaximumIsExclusive = true)]
    public int Age { get; set; }        
    }
}

Length

The Length attribute has been extended so that the maximum length can now also be specified.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [Length(8, 25)]
        public string Username { get; set; }
        
    }
}

DeniedValues

DeniedValues is a data annotation attribute in C# that specifies a list of values that are not allowed, it is the counterpart to allowedValues and prevents the specified values.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        [DeniedValues("Supervisor", "Operator")]
        public string UserRole { get; set; }
    }
}

See More: LINQ: Sort Multiple Columns using LINQ in C#

The post .NET 8 Release New Data Annotation in ASP.NET Core C# appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/feed/ 0 2216
LINQ: Sort Multiple Columns using LINQ in C# https://reactconf.org/linq-sorting-multiple-columns-using-linq-in-csharp/ https://reactconf.org/linq-sorting-multiple-columns-using-linq-in-csharp/#respond Wed, 22 Nov 2023 10:55:30 +0000 https://labpys.com/?p=2183 In this article, we will learn How to Sort multiple Columns using LINQ in C# using Order by , ThenBy, OrderbyDescending, and ThenbyDescending methods. Here’s an example of how to …

The post LINQ: Sort Multiple Columns using LINQ in C# appeared first on Tech Insights.

]]>
In this article, we will learn How to Sort multiple Columns using LINQ in C# using Order by , ThenBy, OrderbyDescending, and ThenbyDescending methods.

Here’s an example of how to Sort multiple Columns using LINQ in C#.

Create an Asp.NET Core MVC or Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Consider an example Employee class with properties like FirstName, LastName, City, and State. We’ll sort employees based on their FirstName and LastName.

Create a Model

namespace WEB_API_without_EF.Models
{
    public class Employees
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string JobTitle { get; set; }
        public string Address { get; set;}

        public string City { get; set; }

        public string state { get; set; }

    }
}

Create a Controller

namespace WEB_API_without_EF.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    { 
[HttpGet("GetOrderBy")]
        public IActionResult GetOrderBy()
        {
            List<Employees> employees = new List<Employees>
            {
                new Employees{FirstName="Anna", LastName="Bedecs", Company="Company A", City="Seattle",state="WA"},
                new Employees{FirstName="Antonio", LastName="Gratacos Solsona", Company="Company B", City="Boston",state="MA"},
                new Employees{FirstName="Thomas" ,LastName="Axen", Company="Company C", City="Seattle",state="WA"},
                new Employees{FirstName="Christina", LastName="Lee", Company="Company D", City="New York",state="NY"},
                new Employees{FirstName="Martin" ,LastName="O’Donnell", Company="Company E", City="Minneapolis",state="MN"},
                new Employees{FirstName="Francisco", LastName="Pérez-Olaeta", Company="Company F", City="Milwaukee",state="WI"},

            };

            //Order by Ascending Order

            var OrderbyEmployeeAsc = employees.
                        OrderBy(x => x.FirstName)
                        .ThenBy(x => x.LastName)
                        .ToList();
            // Descending Order

            var OrderbyEmployeeDesc = employees.
                        OrderBy(x => x.LastName)
                        .ThenByDescending(x => x.FirstName)
                        .ToList();

            

            return Ok(OrderbyEmployeeAsc);
        }
}
}

 Always utilize ThenBy() after OrderBy() because OrderBy() generates an IOrderedEnumerable object which then exposes the methods ThenBy() and ThenByDescending(). This means that we can order by multiple columns.

Output

Sorting Multiple Columns using LINQ  in C#

See More:

Sorting Multiple Columns using LINQ  in C#

The post LINQ: Sort Multiple Columns using LINQ in C# appeared first on Tech Insights.

]]>
https://reactconf.org/linq-sorting-multiple-columns-using-linq-in-csharp/feed/ 0 2183
Group by Multiple Columns in LINQ C# https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/ https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/#respond Wed, 22 Nov 2023 07:35:55 +0000 https://labpys.com/?p=2167 In this article, we will learn the Group y multiple Columns in LINQ C#. The ‘group by ‘method in LINQ to group data based on one or more columns. Here’s …

The post Group by Multiple Columns in LINQ C# appeared first on Tech Insights.

]]>
In this article, we will learn the Group y multiple Columns in LINQ C#. The ‘group by ‘method in LINQ to group data based on one or more columns.

Here’s an example of how to Group by multiple columns using LINQ in C#.

Create an Asp.NET Core MVC or Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Consider an example Employee class with properties like FirstName, LastName, City, and State. We’ll group employees based on their City and State.

Create a Model

namespace WEB_API_without_EF.Models
{
    public class Employees
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string JobTitle { get; set; }
        public string Address { get; set;}

        public string City { get; set; }

        public string state { get; set; }

    }
}

Create a Controller


namespace WEB_API_without_EF.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {

        [HttpGet("GetgroupBy")]
        public IActionResult GetgroupBy()
        {
            List<Employees> employees = new List<Employees>
            {
                new Employees{FirstName="Anna", LastName="Bedecs", Company="Company A", City="Seattle",state="WA"},
                new Employees{FirstName="Antonio", LastName="Gratacos Solsona", Company="Company B", City="Boston",state="MA"},
                new Employees{FirstName="Thomas" ,LastName="Axen", Company="Company C", City="Seattle",state="WA"},
                new Employees{FirstName="Christina", LastName="Lee", Company="Company D", City="New York",state="NY"},
                new Employees{FirstName="Martin" ,LastName="O’Donnell", Company="Company E", City="Minneapolis",state="MN"},
                new Employees{FirstName="Francisco", LastName="Pérez-Olaeta", Company="Company F", City="Milwaukee",state="WI"},

            };

            var groupemployee = from emp in employees
                                group emp by new { emp.City, emp.state } into empgroup
                                select new
                                {
                                   Name =$"City : {empgroup.Key.City} State : {empgroup.Key.state}",
                                   employees= empgroup.ToList(),
                                };
            
      

            return Ok(groupemployee);

        }
}
}

Output:

Group by Multiple Columns in LINQ C#

See More :

Upload Multiple Files in Angular with ASP.NET Core Web API

The post Group by Multiple Columns in LINQ C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/feed/ 0 2167
How to Upload Multiple Files in Angular with ASP.NET Core Web API https://reactconf.org/how-to-upload-multiple-files-in-angular-with-asp-net-core-web-api/ https://reactconf.org/how-to-upload-multiple-files-in-angular-with-asp-net-core-web-api/#respond Thu, 16 Nov 2023 06:05:55 +0000 https://labpys.com/?p=2141 In this article, we’ll learn How to upload multiple files in angular with ASP.NET Core Web API using the “POST” method with “FormData“. The Post () method of the angular …

The post How to Upload Multiple Files in Angular with ASP.NET Core Web API appeared first on Tech Insights.

]]>
In this article, we’ll learn How to upload multiple files in angular with ASP.NET Core Web API using the “POST” method with “FormData“. The Post () method of the angular  “HttpClient” object allows you to send data to a REST API, such as Web API which accepts HTTP requests.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Create a Controller

Create a controller named “uploadFilesController” in this create public method “upload“. as you can see below code sinnepet.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Upload_Multiple_Files.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
       
    public class uploadFilesController : ControllerBase
    {
        private IWebHostEnvironment _environment;

        public uploadFilesController(IWebHostEnvironment environment)
        {
            _environment = environment;
            
        }

        [HttpPost]
        [RequestSizeLimit(long.MaxValue)]
        public async Task<IActionResult> upload()
        {
            string uploadpath = _environment.WebRootPath;
            string dest_path = Path.Combine(uploadpath, "uploaded_doc");

            var fromFiles = Request.Form.Files;
            
            dynamic message="";
            if (!Directory.Exists(dest_path))
            {

                Directory.CreateDirectory(dest_path);
            }

            List<string> uploadedFile = new List<string>();

            foreach (var file in fromFiles)
            {
                string sourcefile = Path.GetFileName(file.FileName);
                using (FileStream filestream = new FileStream(Path.Combine(dest_path, sourcefile), FileMode.Create))
                {
                    file.CopyTo(filestream);
                    uploadedFile.Add(sourcefile);
                    message += string.Format("<b>{0}</b> Files Uploaded.<br/>", sourcefile);
                }

            }

            return Ok(message);
        }

    }
}

The next step is to create a new folder “wwwroot” folder inside the project root.

Avoid MultiPartBodyLength Error

To avoid the MultiPartBodyLength error, we are going to modify our configuration in the Program.cs class.

builder.Services.Configure<FormOptions>(f =>
{
    f.ValueLengthLimit = int.MaxValue;
    f.MultipartBodyLengthLimit = int.MaxValue;
    f.MemoryBufferThreshold = int.MaxValue;
});

Enable CORS Policy

With this CORS policy, we are grating access to all origin “AllowAnyOrigin”, allowing any request header “AllowAny Header”, and permitting any HTTP method “AllowAnyMethod”, read more

builder.Services.AddCors(option =>
{
    option.AddPolicy("corsPolicy", policy => {
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    
});
});

app.UseCors("corsPolicy");

Here’s a complete Program.cs Class

using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.Configure<FormOptions>(f =>
{
    f.ValueLengthLimit = int.MaxValue;
    f.MultipartBodyLengthLimit = int.MaxValue;
    f.MemoryBufferThreshold = int.MaxValue;
});

builder.Services.AddControllers();

builder.Services.AddCors(option =>
{
    option.AddPolicy("corsPolicy", policy => {
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    
});
});

var app = builder.Build();

// Configure the HTTP request pipeline.


app.UseCors("corsPolicy");

app.UseStaticFiles();
app.UseHttpsRedirection();


app.UseAuthorization();

app.MapControllers();

app.Run();

Create Client App using Angular

To create an Angular project first we need to install Node.js and angular

  • Download Node.js installer here https://nodejs.org/en/download/current

After installing angular using the command ‘npm install –g @angular/cli’, create a new angular project named “Upload_Multiple_Files” using the command ‘ng new \Upload_Multiple_Files‘. Next, navigate to the project directory using the command ‘cd ‘.

Create Component

First, we are going to do is to create a new Upload component in which we will handle all the upload-related logic.

ng g component file-upload --skip-tests

Then modify the file “file-upload.component.ts”.

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
 
@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {
 msg?: string;
 progressbar:number=0;

 @Output() public UploadCompleted = new EventEmitter();

 constructor(private http:HttpClient){}

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }

  uploadedFile = (files:any)=>{
    if(files.length===0){
      return;
    }

    let filecollection : File[] =files;
    const formData = new FormData();

    Array.from(filecollection).map((file,index)=>{
      return formData.append('file' + index, file, file.name)
    }); 

    this.http.post('https://localhost:7162/api/uploadfiles',formData, {reportProgress: true, observe:'events'})
      .subscribe({
        next:(event)=>{
          if(event.type === HttpEventType.UploadProgress)
          {  
          if(event?.loaded && event?.total)
            {
          this.progressbar = Math.round(100 * event.loaded / event.total)
            }
          }
          else if (event.type === HttpEventType.Response){
          this.msg = 'Upload successfully completed..!';
          this.UploadCompleted.emit(event.body);
        }
        },
        error: (err:HttpErrorResponse)=> console.log(err)
      });
  }
}

HttpClientModule

Add the “HttpClientModule” in app.module.ts file.

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],

Template File

Need to modify the “file-upload.component.html“.

<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3">
    <input type="file" #file placeholder="Select File" (change)="uploadedFile(file.files)" style="display: none;" multiple>
    <button type="button" class="btn btn-primary" (click)="file.click()">Upload Multiple File</button>
</div>
<div class="col-md-4">
    <span class="Upload" *ngIf="progressbar > 0 ">
      {{  progressbar }} %  Successfully Uploaded Files
    </span>
    <span class="Upload" *ngIf="msg">
        {{ msg }} 
        </span>

</div>
</div>

Finally, modify the “file-upload.component.css“.

.Upload{
    font-weight: bold;
    color:maroon;
    margin-left: 20px;
    line-height: 40px;
}

and add the select from the upload component in the app.component.html file.

<app-file-upload></app-file-upload>

Now Run the App.

Upload Multiple Files in Angular with ASP.NET Core Web API

The post How to Upload Multiple Files in Angular with ASP.NET Core Web API appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-upload-multiple-files-in-angular-with-asp-net-core-web-api/feed/ 0 2141
How to download multiple files in ASP.NET Core MVC https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/ https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/#respond Fri, 10 Nov 2023 11:03:11 +0000 https://labpys.com/?p=2121 This article explains how to download multiple files using ASP.NET Core MVC. First, create a table to store file information, such as filename and source path. Here is the following …

The post How to download multiple files in ASP.NET Core MVC appeared first on Tech Insights.

]]>
This article explains how to download multiple files using ASP.NET Core MVC. First, create a table to store file information, such as filename and source path.

Here is the following step-by-step guide to download multiple files in ASP.NET Core MVC:

Create an Asp.NET Core MVC Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Create a Model

namespace WebApplication_Download_Files.Models
{
    public class FileAssets
    {
        public Guid Id { get; set; }
        public string Filename { get; set; } = null;
        public string FileUrls { get; set; } = null;

        public FileAssets()
        {
            Id = Guid.NewGuid();
        }
    }
}

Configure Database Connection

Open the Program.cs file and add the following code snippet.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Configuration;
using WebApplication_Download_Files.Models;


var builder = WebApplication.CreateBuilder(args);

//Connection string
// "connectionstr": //"Server=localhost;Database=inventoryDb;Encrypt=False;Trusted_Connection=True;"

builder.Services.AddDbContext<AppDbContext>(opt=> opt.UseSqlServer(builder.Configuration.GetConnectionString("connectionstr")));
// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

Migration

Run the following command in the package manager console.

add-migration 'Init-create'
update-database

Create Controller

Open the HomeController.cs file. Create a new method named “downloadAll”

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.Text;
using WebApplication_Download_Files.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO.Compression;

namespace WebApplication_Download_Files.Controllers
{
    public class HomeController : Controller
    {
        
        private readonly AppDbContext _context;
        private readonly IWebHostEnvironment _env;

        public HomeController(AppDbContext context, IWebHostEnvironment env)
        {
           
            _context = context;
            _env = env;
         
        }

        public async Task<IActionResult> Index()
        {
            return _context.FileAssets != null ?
                        View(await _context.FileAssets.ToListAsync()) :
                        Problem("Entity set 'AppDbContext.FileAssets'  is null.");

        }

        public IActionResult downloadAll()
        {
            var ZipFile = $"docFile-{DateTime.Now.ToString("yyyy_MM-dd-HH_mm_ss")}.zip";

            using (var memorystream = new MemoryStream())
            {
                using(var archieve = new ZipArchive(memorystream,ZipArchiveMode.Create,true))
                {
                    _context.FileAssets.ToList().ForEach(files=>
                    {
                        var zipentry = archieve.CreateEntry(files.Filename);
                        var stringpath = Path.Combine(this._env.WebRootPath +  files.FileUrls);
                        byte[] bytes = System.IO.File.ReadAllBytes(stringpath);
                        using (var filems = new MemoryStream(bytes))
                            using(var openstream = zipentry.Open())
                        {
                            filems.CopyTo(openstream);
                        }

                    });
                }
                return File(memorystream.ToArray(), "application/zip", ZipFile);
            }
        }
    }
}

Create View

Open the Index.cshtml file and update the following code:

@model IEnumerable<WebApplication_Download_Files.Models.FileAssets>
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">File List to Download</h1>


    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Filename)
                </th>
                <th>
                    Action
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Filename)
                    </td>
                    
                    <td>
                        @Html.ActionLink("Download File","download",new{Filename = item.FileUrls  } )                        
                    </td>

                </tr>
            }
        </tbody>
    </table>
    <a asp-controller="Home" asp-action="downloadAll">Download All</a> 

</div>

output:

How to download multiple files in ASP.NET Core MVC

See Also:

Dynamic Middleware | Conditionally add middleware in ASP.NET Core

The post How to download multiple files in ASP.NET Core MVC appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/feed/ 0 2121
How to download files using ASP.NET Core MVC https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/ https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/#respond Thu, 09 Nov 2023 11:53:29 +0000 https://labpys.com/?p=2103 This article explores how to download files using ASP.NET Core MVC. To begin, we have to create a table for storing file information, such as file names, and a source …

The post How to download files using ASP.NET Core MVC appeared first on Tech Insights.

]]>
This article explores how to download files using ASP.NET Core MVC. To begin, we have to create a table for storing file information, such as file names, and a source path. Here’s a step-by-step guide on How to download files in ASP.NET Core MVC.

Create an Asp.NET Core MVC Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Open the HomeController.cs file. Create a new method named download:

        public IActionResult download(string Filename)
        {
            var stringpath = Path.Combine(this._env.WebRootPath + Filename);
            byte[] bytes = System.IO.File.ReadAllBytes(stringpath);
             
            return File(bytes, "application/octet-stream", Filename);
        }

ASP.NET Core provides four file-related response classes that implement the ActionResult interface.

  • FileContentResult:
  • FileStreamResult:
  • VirtualFileResult:
  • PhysicalFileResult

The FileResult class is an abstract base class for all file-related response classes in ASP.NET Core. The specific class you use to return a file to the browser depends on how to provide the file content and from where.

  • FileContentResult and  FileStreamResult can be used to return files from virtual paths within your web application.
  • PhysicalFileResult can be used to return a file from the absolute file path.

Open the View Index.cshtml file and add the following code.

@model IEnumerable<WebApplication_Download_Files.Models.FileAssets>
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">File List to Download</h1>


    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Filename)
                </th>
                <th>
                    Action
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Filename)
                    </td>
                    
                    <td>
                        @Html.ActionLink("Download File","download",new{Filename = item.FileUrls  } )                        
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

Output

How to download files using ASP.NET Core MVC

See Also:

Conditionally add middleware in ASP.NET Core

The post How to download files using ASP.NET Core MVC appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/feed/ 0 2103
Dynamic Middleware | Conditionally add middleware in ASP.NET Core https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/ https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/#respond Thu, 09 Nov 2023 06:05:19 +0000 https://labpys.com/?p=2083 This article explores configuring ASP.NET Core middleware Conditionally, in a way that allows you to have different middleware setups for different types of requests. For instance, in a project with …

The post Dynamic Middleware | Conditionally add middleware in ASP.NET Core appeared first on Tech Insights.

]]>
This article explores configuring ASP.NET Core middleware Conditionally, in a way that allows you to have different middleware setups for different types of requests. For instance, in a project with both MVC and Web API actions, you can implement distinct error-handling approaches for each request.

Create an Asp.NET Core MVC or Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .NET Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Create Middleware in Asp.Net Core

Visual Studio provides a template for creating standard middleware classes. To access this template, right-click on the project or folder where you want to create the middleware class and select Add>New Item, this will open the Add New Item dialog box. In the search bar located at the top right corner, type middleware to filter the available items. Select the middleware class item and provide a name for your class. Click the Add button to create the middleware class as shown below.

Conditionally add middleware in ASP.NET Core
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace middleware_App
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MiddlewareException
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public MiddlewareException(RequestDelegate next)
        {
            _next = next;
            
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            
            await  _next.Invoke(httpContext);                     

        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class ErrorExceptionExtensions
    {
        public static IApplicationBuilder UseErrorException(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MiddlewareException>();
        }
    }
}

Registering middleware with Use*

Adding it to the “Program.cs” file requires only a single line:

app.UseMiddlewareMVC();

Conditionally middleware with UseWhen

In some cases, you may want to apply most of your middleware to all requests. But you have specific conditions for certain requests. This can be easily achieved with “UseWhen” method, which also uses a predicate to determine if the middleware should run

app.UseWhen(
    context => context.Request.Path.StartsWithSegments("/api"),
    builder => builder.UseMiddleware<MiddlewareException>()
    );

The UseWhen method takes two parameters. The first parameter is a delegate of type Func<T,bool>, which returns a Boolean value indicating whether the middleware should be executed. If the delegate returns true, the middleware will be applied to the request, otherwise, it will be skipped.

See Also

Encode and Decode URLs in ASP.NET Core C#

The post Dynamic Middleware | Conditionally add middleware in ASP.NET Core appeared first on Tech Insights.

]]>
https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/feed/ 0 2083
.NET CORE | How to Encode and Decode URLs in ASP.NET Core C# https://reactconf.org/net-core-how-to-encode-and-decode-urls-in-asp-net-core-csharp/ https://reactconf.org/net-core-how-to-encode-and-decode-urls-in-asp-net-core-csharp/#respond Mon, 30 Oct 2023 06:42:31 +0000 https://labpys.com/?p=2024 What is URI Encoding It is the process of converting certain characters to a specific format to make them valid for use in a URI. This conversion is necessary before …

The post .NET CORE | How to Encode and Decode URLs in ASP.NET Core C# appeared first on Tech Insights.

]]>
What is URI Encoding

It is the process of converting certain characters to a specific format to make them valid for use in a URI. This conversion is necessary before transmitting these characters over the internet. In this article, we will learn How to Encode and Decode URLs in ASP.NET Core C#.

URLs can be categorized into reserved and unreserved characters. The reserved characters have special meanings, such as the ‘?’ character, which indicates the beginning of query parameters.

Encode and Decode URLs using the WebUtility Class in ASP.NET Core C#

The “WebUtility” class, which is available in the ‘System.Net’ namespace.

The “WebUtility.UrlEncode()” and “WebUtility.UrlDecode” methods will encode and decode the URI.

Encode URI

 var urlsWeb = "https://labpys.com/path/page?param=value";
            var encodedWeburls = WebUtility.UrlEncode(urlsWeb);
            Console.WriteLine($"Encode URL using Web Utility {encodedWeburls}");
 https%3A%2F%2Flabpys.com%2Fpath%2Fpage%3Fparam%3Dvalue

Decode URI

var encodedWeburls ="https%3A%2F%2Flabpys.com%2Fpath%2Fpage%3Fparam%3Dvalue";
var decodedurlsWeb = WebUtility.UrlDecode(encodedWeburls);
Console.WriteLine($"Decode URL using Web Utility {decodedurlsWeb}");
https://labpys.com/path/page?param=value

Encode and Decode URI using HttpUtility

To access the “HttpUtility” class include the “System.Web” namespace. The ‘HttpUtility.UrlEncode()’ and ‘HttpUtility.UrlDecode()’ method to encode and decode the URI, takes a single string parameter containing the URL to encode and decode. Here’s an example in C#:

Encode URI

   var urls = "https://labpys.com/path/page?param=value";
   var encodedurls = HttpUtility.UrlEncode(urls);
   Console.WriteLine($"Encode URL using HttpUtility  {encodedurls}");
   // output -  https%3a%2f%2flabpys.com%2fpath%2fpage%3fparam%3dvalue           

Decode URI

var decodedurlspath = HttpUtility.UrlDecode(encodedurls);
Console.WriteLine($"Decode URL using HttpUtility  {decodedurlspath}");
//output - https://labpys.com/path/page?param=value

Encode and Decode using Uri Class

Alternatively, we can use the Uri class to encode and decode URLs. The “Uri.EscapeDataString()’ and “Uri.UnescapeDataString()” methods encode and decode the URI.

             var urlsUri = "https://labpys.com/path/page?param=value";
            var encodedUriurls = Uri.EscapeDataString(urlsUri);
            Console.WriteLine($"Encode URL using Uri Class  {encodedUriurls}");
            //result - https%3A%2F%2Flabpys.com%2Fpath%2Fpage%3Fparam%3Dvalue

            var decodedurlsUri = Uri.UnescapeDataString(encodedUriurls);
            Console.WriteLine($"Decode URL using Uri Class {decodedurlsUri}");
            //result -https://labpys.com/path/page?param=value

More Articles:

How to Enable CORS in ASP.NET CORE WEB API

The post .NET CORE | How to Encode and Decode URLs in ASP.NET Core C# appeared first on Tech Insights.

]]>
https://reactconf.org/net-core-how-to-encode-and-decode-urls-in-asp-net-core-csharp/feed/ 0 2024
.NET CORS | How to Enable CORS in ASP.NET CORE WEB API https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/ https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/#respond Sat, 28 Oct 2023 07:37:36 +0000 https://labpys.com/?p=2018 What is CORS CORS stands for Cross-Origin Resource Sharing. It is an HTTP protocol that allows web applications to access resources hosted on different domains. In this article, we will …

The post .NET CORS | How to Enable CORS in ASP.NET CORE WEB API appeared first on Tech Insights.

]]>
What is CORS

CORS stands for Cross-Origin Resource Sharing. It is an HTTP protocol that allows web applications to access resources hosted on different domains. In this article, we will learn How to Enable CORS in ASP.NET Core Web API.

How to Enable CORS

Enabling CORS in ASP.NET Core Web API is quite easy, as the platform comes with built-in features to support that.

Enable CORS Policy with Specific Origin

You need to configure CORS in the Program.cs file, if you are using below .NET 6 then configure CORS in the startup.cs file.

Open the Program.cs file in your editor and modify it. Here is how to enable CORS in ASP.NET Core.

   Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                 });
            });

app.UseCors("CorsPolicy");

Above code example, we are using the WithOrigins method, which accepts a list of string URIs as parameters, and allows you to specify multiple origins for a single CORS Policy.

Enable CORS Policy with any Origin

With this CORS policy, we are grating access to all origins “AllowAnyOrigin”, allowing any request header “AllowAnyHeader”, and permitting any HTTP method “AllowAnyMethod”

 Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyOrigin().
                    AllowAnyHeader().
                    AllowAnyMethod(); 
                 });
            });

app.UseCors("CorsPolicy");

CORS Policy Options

Here are the CORS policy options you can use to configure your ASP.NET Core WEB API:

  1. AllowAnyOrigin: To accept requests from any domain
  2. WithOrigins: To allow requests only from specific domains.
  3. WithMethods: to specify which HTTP methods are allowed in the request.
  4. AllowAnyMethod: To allow any HTTP method (GET, POST, PUT, etc.) in the request.
  5. AllowAnyHeader: To accept any HTTP request header.
  6. WithHeaders: To specify which HTTP headers are allowed in the request.
  7. WithExposedHeaders: To specify which headers are safe to expose to the API of a CORS API specification.
  8. AllowCredentials: To allow requests with credentials.

Conclusion

In this article, we have shown you how to enable CORS(Cross-Origin Resource Sharing) in an ASP.NET Core Web API. CORS is essential for allowing web applications hosted in different domains to access your API securely.

See More Articles:

Difference between IEnumerable and IQueryable in C#

The post .NET CORS | How to Enable CORS in ASP.NET CORE WEB API appeared first on Tech Insights.

]]>
https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/feed/ 0 2018
ASP.NET Core | How to Call Stored Procedure in Web API without Entity Framework https://reactconf.org/asp-net-core-how-to-call-stored-procedure-in-web-api-without-entity-framework/ https://reactconf.org/asp-net-core-how-to-call-stored-procedure-in-web-api-without-entity-framework/#respond Tue, 26 Sep 2023 07:32:06 +0000 https://labpys.com/?p=1862 In the .NET Framework, there are various methods to connect the database without using Entity Framework. In this tutorial, we will learn How to Call Stored Procedures in WEB API …

The post ASP.NET Core | How to Call Stored Procedure in Web API without Entity Framework appeared first on Tech Insights.

]]>
In the .NET Framework, there are various methods to connect the database without using Entity Framework. In this tutorial, we will learn How to Call Stored Procedures in WEB API without Entity Framework using ASP.NET Core Web API.

Creating ASP.NET Core Web API without using Entity Framework, is an alternative data access to optimize API for speed and scalability.

Call Stored Procedure in WEB API without Entity Framework

In this tutorial, we will explore two different methods, ADO.Net and Dapper for calling stored procedures.

Create Asp.Net Core Web API

  • Open Visual Studio or VS Code
  • Click on “Create a new Project”
  • Select “ASP.NET Core Web  API”
  • Click Next”
  • Enter a project name and choose a location.
  • Select target framework
  • Click Create

Install the NuGet Package

  • Dapper
  • Microsoft.Data.SqlClient

Database Connection String  

Configure the Database Connection String in the appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "connectionstr": "Server=localhost;Database=Northwind;Encrypt=False;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}

Create Models

Create a model class named Employees.cs

namespace WEB_API_without_EF.Models
{
    public class Employees
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string JobTitle { get; set; }
        public string Address { get; set;}
 
    }
}

Create the Services

Create the class named AppDbcontext.cs.

using System.Data;
using Microsoft.Data.SqlClient;
using Dapper;

namespace WEB_API_without_EF.Data
{
    public class AppDbContext
    {
        private readonly IConfiguration _configuration;
        public AppDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IDbConnection Createconnection()
        {

            return new SqlConnection(_configuration.GetConnectionString("connectionstr"));

        }

        public SqlConnection sqlconnection()
        {
            SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("connectionstr"));
            return connection;
        }
 
        public async Task Init()
        {
            var conn = Createconnection();

            await _initcustomer();

            async Task _initcustomer()
            {
                var sqlstr = "CREATE TABLE IF NOT EXISTS Employees(ID INTEGER NOT NULL PRIMARY KEY,FirstName TEXT,LastName TEXT,Address TEXT,Email TEXT,Company TEXT);";

                await conn.ExecuteAsync(sqlstr);

            }
        }

    }
}

Create Controller

In the controller, you can define API endpoints.

using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using WEB_API_without_EF.Data;
using WEB_API_without_EF.Models;

namespace WEB_API_without_EF.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly AppDbContext _context;

        public EmployeeController(AppDbContext context)
        {
            _context = context;
        }

        // Using Dapper

        [HttpGet("GetAllusingDapper")]
        public async Task<IEnumerable<Employees>> GetAlldapper()
        {
            using var connection = _context.Createconnection();
            var sqlstr = "Exec GetEmployee";

            return await connection.QueryAsync<Employees>(sqlstr);

        }

        // Using ADO.Net
        [HttpGet("GetAllusingAdo")]
        public  List<Employees> GetAllAdo()
        {
            using var connection = _context.sqlconnection();
            var sqlQ = "Exec GetEmployee";

            List<Employees> employees = new List<Employees>();            

           using (SqlCommand cmd = new SqlCommand(sqlQ, connection))
            {
                connection.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while(sdr.Read())
                    {
                        employees.Add(new Employees
                        {
                            ID = int.Parse(sdr["Id"].ToString()),
                            FirstName = sdr["FirstName"].ToString(),
                            LastName = sdr["LastName"].ToString(),
                            Email = sdr["Email"].ToString(),
                            Company = sdr["Company"].ToString(),
                            Address = sdr["Address"].ToString(),
                            JobTitle = sdr["JobTitle"].ToString(),
                        });
                    }
                }
                connection.Close();
                    
                }


            return employees;
        }


    }
}

Configure Program.cs Class

using WEB_API_without_EF.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddSingleton<AppDbContext>();
builder.Services.AddControllers();



var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Create Stored Procedure in SQL Server

USE [Northwind]
GO
/****** Object:  StoredProcedure [dbo].[GetEmployee]    Script Date: 9/26/2023 1:09:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetEmployee]
	 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT  * from Employees;
END

Test Web API

Using the tool Postman for testing API Endpoints.

ADO.Net
Dapper

See More: How to Implement JWT Authentication in Asp.Net Core Web API

The post ASP.NET Core | How to Call Stored Procedure in Web API without Entity Framework appeared first on Tech Insights.

]]>
https://reactconf.org/asp-net-core-how-to-call-stored-procedure-in-web-api-without-entity-framework/feed/ 0 1862