1670416800
In this ASP.NET tutorial, we will learn about How to handle CSV files in ASP.NET Core Web API. Handling CSV files can be essential for developers in applications using ASP.NET Core Web APIs. There are many approaches to handling CSV, and CSVHelper is a handy NuGet package for doing so easily. This article will discuss how to handle CSV files using the CSVHelper library in an ASP.NET Core Web API.
CSVHelper is an open-source .NET library for reading and writing CSV files. It is speedy, flexible, and easy to use. We can read and write CSV files using the model class. Also, some configurations can map the model class with the headers of the CSV files, if required.
First, create an ASP.NET Core Web API project using Visual Studio 2022. To do so, open Visual Studio and select a new project with an ASP.NET Core Web API template, as in the following figure.
Now, select the .NET 6 framework for this project, like in the next figure. Then, create the project and run it to check if everything is working.
Then, to install the CSVHelper package in our project, click right on the project and select the Manage NuGet Packages… option, as shown in the figure.
Then, navigate to the Browse tab in the NuGet section, search for the CSVHelper version 28.0.1 package, and install it, like in the following figure.
Now, create a model class named Employee. This class is used to read and write CSV files.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public string JobPosition { get; set; }
}
Note: We have created the Employee model class only for demonstration purposes. You can use any model class you need for your project.
Now, we create a service to read CSV files using the CSVHelper NuGet package. For this, create a folder named Services in the root directory. Then, create an interface named ICSVService, similar to the next sample.
public interface ICSVService
{
public IEnumerable<T> ReadCSV<T>(Stream file);
}
Create a class named CSVService, inherited from ICSVService.
public class CSVService : ICSVService
{
public IEnumerable<T> ReadCSV<T>(Stream file)
{
var reader = new StreamReader(file);
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csv.GetRecords<T>();
return records;
}
}
We have used a method-level generic to deal with the model class. We can use this method with any model class to read CSV files. We have also passed the file stream as a parameter to the ReadCSV method. The StreamReader reads the text and characters from the file stream. Later, we used CsvReader to transfer the content read from StreamReader into the memory. Then, the GetRecords method returned the data of CSV files. We don’t need any configurations if our class property names match the headers of CSV files.
After all this, register the CSV service in the Program.cs, as shown in the next code.
builder.Services.AddScoped<ICSVService, CSVService>();
Next, create a controller class named EmployeeController inside the Controllers folder. Then, create the HttpPost request to read the CSV file using the ICSVService.
[ApiController]
[Route("[controller]")]
public class EmployeeController : Controller
{
private readonly ICSVService _csvService;
public EmployeeController(ICSVService csvService)
{
_csvService = csvService;
}
[HttpPost("read-employees-csv")]
public async Task<IActionResult> GetEmployeeCSV([FromForm] IFormFileCollection file)
{
var employees = _csvService.ReadCSV<Employee>(file[0].OpenReadStream());
return Ok(employees);
}
}
We injected the ICSVService to use the read operation for CSV files. Also, EmployeeController uses the ApiController attribute to implement the Web API controller in ASP.NET Core. Then, we used the ReadCSV method of the CSVService to get the data of the CSV file after reading it.
First, let’s run the application. The following is the screenshot of the CSV file we use to read the data.
Then, run the read-employees-csv endpoint to read the CSV file like in the following figure.
Here we have attached the CSV file we use to run the read.
We received a response after running the API successfully.
We use CSVService to create a CSV write method using the CSVHelper. For this, add an abstract method named WriteCSV<T> in the ICSVService interface.
public interface ICSVService
{
public IEnumerable<T> ReadCSV<T>(Stream file);
void WriteCSV<T>(List<T> records);
}
After that, implement the WriteCSV method in the CSVService class like in the following code.
public class CSVService : ICSVService
{
public IEnumerable<T> ReadCSV<T>(Stream file)
{
var reader = new StreamReader(file);
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csv.GetRecords<T>();
return records;
}
public void WriteCSV<T>(List<T> records)
{
using (var writer = new StreamWriter("D:\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
}
}
In the WriteCSV<T> method, the StreamWriter is used to create and write files in the path specified in the parameter. The CsvWriter is used to create the actual CSV files using the StreamWriter instance created. The WriteRecords method writes all the data into the files.
Now, use EmployeeController to create a HttpPost request to create and write the CSV file.
[ApiController]
[Route("[controller]")]
public class EmployeeController : Controller
{
private readonly ICSVService _csvService;
public EmployeeController(ICSVService csvService)
{
_csvService = csvService;
}
[HttpPost("write-employee-csv")]
public async Task<IActionResult> WriteEmployeeCSV([FromBody] List<Employee> employees)
{
_csvService.WriteCSV<Employee>(employees);
return Ok();
}
[HttpPost("read-employees-csv")]
public async Task<IActionResult> GetEmployeeCSV([FromForm] IFormFileCollection file)
{
var employees = _csvService.ReadCSV<Employee>(file[0].OpenReadStream());
return Ok(employees);
}
}
We implemented the new HttpPost request to write the CSV files using the WriteCSV<Employee> method of CSVService.
Let’s run the Web API application. Then, we run the write-employee-csv endpoint to test the service.
We used Swagger to run and test the API to write the CSV. We passed a list with two employee objects.
And so, we have successfully created a CSV file in the directory path. The employee data is in the CSV file, like in the next figure.
This article discussed handling CSV files using the CSVHelper package with an ASP. NET Core Web API application. This included performing read and write operations in the CSV file using the CSVHelper package.
Original article sourced at: https://www.syncfusion.com
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1602564619
User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.
Sub-topics discussed :
ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.
ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.
The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.
First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.
Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.
#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core
1583378723
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1583377668
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1602564706
In this article, you will learn how to use or integrate WordPress in ASP.NET and Running WordPress on ASP.NET Core, without PHP, or any source files on the server. The following demonstration will show you how to add WordPress as a frontend to an existing ASP.NET Core application step by step.
WordPress is a free, simplest, and most popular open-source content management system to create your own website or blog which is written in PHP and paired up with MySQL. WordPress on .Net Core is possible with peachpie, which is a compiler built on top of the Roslyn platform, it’s a set of runtime and base class libraries and everything that allows compiling a PHP project, a group of PHP files into a regular .net project.
Peachpie allows for seamless both-way interoperability between PHP and .NET applications. In simpler terms, this means that one can have some parts of an application written in PHP, while other modules are written in .NET and everything will work together as one application. Here is the original Repository of the WordPress SDK by PeachPie.
Here are the following steps to run WordPress with ASP.Net Core:-
Step1: Open your Visual Studio IDE and Create a new project – > ASP.NET Core Web Application
Step 2: Select Web Application: A project template for creating an ASP.Net Core application with example ASP.Net Razor Pages Content.
#.net core #asp.net #wordpress asp.net core #wordpress on asp.net core #wordpress with asp.net core