Sunday, 6 August 2023

Convert Excel To DataTable,Bulk Insert, Display Imported data,Export to PDF In ASP.NET Core

 In this article, we will talk about how you can convert excel to DataTable using the EPPlus package in the Asp.Net Core MVC application.

C#, ASP.NET, .NET, SQL-Server, convert, ASP.NET-Core, .NET-Core






Introduction



This is the easiest and quick way to make a simple application for importing bulk data from Excel Sheet and insert the all data in one command into MSSQL server database using BulkCopy with Column Mapping. After importing display the all imported data into Html /mvc razor view page. And easy way to export the Grid/Html table data into pdf.
 Using the code
//
Install-Package Microsoft.Data.SqlClient --version 5.1.1
Install-Package System.Data.OleDb --version 7.0.0
Install-Package EPPlus --version 6.2.7
Install-Package itext7.pdfhtml -Version 4.0.4
//


Step1:
Create a new asp.net core project ExcelToDataTable in Visual Studio.
Add the above packages.
Create a model view class FileUploadModel
//
using System.ComponentModel.DataAnnotations;

namespace ExcelToDataTable.Models
{

    public class FileUploadModel
    {
        [Required(ErrorMessage = "Please select file")]
        public IFormFile File { get; set; }
    }
}

Step2:

Put connectionStrings in appsettings.json . One is for MSSQL Server database connection.
Anothr is for Excel OleDb connection. 
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "constr": "Data Source=.;Initial Catalog=AssetManagement;
                    user id=sa;password=sapassword;MultipleActiveResultSets=True;
                   App=EntityFramework;Encrypt=false",
    "ExcelConString": "Provider=Microsoft.ACE.OLEDB.12.0;
         Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"
  }   
}

Step3:
Create a Databse AssetManagement in MS SQl Server. And Create a database table Assets.
USE [AssetManagement]
GO

/****** Object:  Table [dbo].[Assets]    Script Date: 7/24/2023 12:16:02 PM ******/
SET ANSI_NULLS ON

GO
SET QUOTED_IDENTIFIER ON

GO
CREATE TABLE [dbo].[Assets](
    [Id] [int] IDENTITY(1,1) NOT NULL ,
    [ItemName] [nvarchar](50) NULL,
    [Price] [nvarchar](50) NULL,
    [Quntity] [nvarchar](50) NULL, 
    [IsAvailable] [bit] NULL,
 CONSTRAINT [PK_Assets] PRIMARY KEY CLUSTERED 
(  [Id] ASC)WITH (PAD_INDEX = OFF, 
STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON,
 ALLOW_PAGE_LOCKS = ON, 
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[Assets] ADD  CONSTRAINT [DF_Assets_IsAvailable]  DEFAULT ((1))
 FOR [IsAvailable]
GO
//


Step4:
Create a Controller   ExcelToDataTableController.
Add required namespaecs like the below code.
Actions:
      i)Index
     ii) Convert
             a) import from excel
             b) bulkCopy to mssql datatabase  table (make sure database table name, column names                                                                                     are  same as excel columns)
    iii) Display
    iv) Export
//
using ExcelToDataTable.Models;
using Microsoft.AspNetCore.Mvc; 
using System.Data;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using OfficeOpenXml;
using System.Text;
using iText.Html2pdf;
using iText.IO.Source;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
namespace ExcelToDataTable.Controllers
{
    public class ExcelToDataTableController : Controller
    {
        private IConfiguration Configuration;
        public ExcelToDataTableController( IConfiguration _configuration)
        {
            Configuration = _configuration;
        }
        public IActionResult Index()
        {
            FileUploadModel model = new FileUploadModel();
            return View(model);
        }
        [HttpPost]
        public IActionResult Convert(FileUploadModel model)
        {
            DataTable table = new DataTable();
            try
            {
                if (model.File != null)
                {
              //if you want to read data from a excel file use this 
             //using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
                    using (var stream = model.File.OpenReadStream())
                    {
                        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                        ExcelPackage package = new ExcelPackage();
                        package.Load(stream);
                        if (package.Workbook.Worksheets.Count > 0)
                        {
                            using (ExcelWorksheet workSheet = 
                            package.Workbook.Worksheets.First())
                            {
                                int noOfCol = workSheet.Dimension.End.Column;
                                int noOfRow = workSheet.Dimension.End.Row;
                                int rowIndex = 2;
                             for (int c = 1; c <= noOfCol; c++)
                             {
           table.Columns.Add(workSheet.Cells[rowIndex, c].Text.Replace(" ","").Trim());
                             }
                                rowIndex = 3;
                                for (int r = rowIndex; r <= noOfRow; r++)
                                {
                                    DataRow dr = table.NewRow();
                                    for (int c = 1; c <= noOfCol; c++)
                                    {
                                        dr[c - 1] = workSheet.Cells[r, c].Value;
                                    }
                                    if (!string.IsNullOrEmpty(dr[0].ToString()))
                                    {
                                        table.Rows.Add(dr);
                                    }
                                }
                                //Read the connection string for the Excel file.
                                string conString = 
                               this.Configuration.GetConnectionString("ExcelConString");
                        //Insert the Data read from the Excel file to Database Table.
                          conString = this.Configuration.GetConnectionString("constr");
                                using (SqlConnection con = new SqlConnection(conString))
                                {
                                    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                                    {
                                        //Set the database table name.
                                        sqlBulkCopy.DestinationTableName = "dbo.Assets";
           //[OPTIONAL]: Map the Excel columns with that of the database table.
                             sqlBulkCopy.ColumnMappings.Add("ItemName", "ItemName");
                             sqlBulkCopy.ColumnMappings.Add("Price", "Price");
                            sqlBulkCopy.ColumnMappings.Add("Quntity", "Quntity"); 
                                          con.Open();
                                        sqlBulkCopy.WriteToServer(table);
                                        con.Close();
                                    }
                                }
             ViewBag.SuccessMessage = "Excel Successfully Converted to Data Table";                             
                            }
                        }
                        else
                            ViewBag.ErrorMessage = "No Work Sheet available in Excel File";
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
            }
            if(table.Rows.Count > 0)
            {
                return View("Display", table);
            }
            else
            return View("Index");
        }
        public IActionResult Display(DataTable dt)
        {   
           return View(dt);
        }

        [HttpPost]
        public FileResult Export(string GridHtml)
        {
            using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(GridHtml)))
   {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                PdfWriter writer = new PdfWriter(byteArrayOutputStream);
                PdfDocument pdfDocument = new PdfDocument(writer);
                pdfDocument.SetDefaultPageSize(PageSize.LEDGER);
                HtmlConverter.ConvertToPdf(stream, pdfDocument);
                pdfDocument.Close();
                return File(byteArrayOutputStream.ToArray(), "application/pdf", "Grid.pdf");
            }
        }
    }
}

//
Step5:
Create a view Index Under Views>ExcelToDatatable folder.
 //
@model FileUploadModel
@{
    ViewData["Title"] = "Convert Excel To DataTable";
}
<form asp-action="Convert"
asp-controller="ExcelToDataTable" method="post" enctype="multipart/form-data">
    <div class="row mt-2">
        @if (ViewBag.SuccessMessage != null)
        {
            <div class="alert alert-success">
                @ViewBag.SuccessMessage
            </div>
        }
        @if (ViewBag.ErrorMessage != null)
        {
            <div class="alert alert-danger">
                @ViewBag.ErrorMessage
            </div>
        }
    </div>
    <div class="row mt-2">
        <div class="col-6">
            <label class="col-form-label">Select File</label>
            <input asp-for="File" class="form-control" />
            <span asp-validation-for="File" class="text-danger"></span>
        </div>
    </div>
    <div class="row mt-2">
        <div class="col-6">
            <button type="submit" class="btn btn-success">Upload File</button>
        </div>
    </div>
</form>

Step 6:
Create a view Display Under Views>ExcelToDatatable folder.
//
@using System.Data
@model DataTable
@{
    ViewData["Title"] = "Display";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Display</h1>
<form method="post" asp-action="Export" asp-controller="ExcelToDataTable">
    <input type="hidden" name="GridHtml" />
    <input type="submit" id="btnSubmit" class="btn btn-info" value="Export To PDF" />
</form>
<br />
<div id="Grid">
    <table class="table table-responsive table-bordered table-striped" 
cellpadding="5" cellspacing="0" 
style="border: 1px solid #ccc; font-family: Arial; font-size: 10pt;">
    <tr>
        <th style="background-color: #B8DBFD;border: 1px solid #ccc">ItemName</th>
        <th style="background-color: #B8DBFD;border: 1px solid #ccc">Price</th>
        <th style="background-color: #B8DBFD;border: 1px solid #ccc">Quantity</th> 
    </tr>
    @foreach (DataRow row in Model.Rows)
    {
        <tr>
                <td style="border: 1px solid #ccc">@row["ItemName"]</td>
                <td style="border: 1px solid #ccc">@row["Price"]</td>
                <td style="border: 1px solid #ccc">@row["Quantity"]</td> 
        </tr>
    }
</table>
</div> 
<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSubmit").click(function () {
            $("input[name='GridHtml']").val($("#Grid").html());
        });
    });
</script>
//
Step 7:
Run the application Ctrl+F5



You can use this example in any .Net project, not only MVC. Reading data from excel and converting it into DataTable will remain the same in all .Net projects. I hope you find this article helpful. If you have any doubts, you can ask them in the comments.


You can download the source code of this project from my GitHub Account.





  


Tuesday, 11 July 2023

Accelerate Your Business with Expert ASP.NET MVC Application Development Services

Introduction: In today's digitally-driven world, businesses need a strong online presence to stay competitive. If you're looking to enhance your brand's visibility, engage customers, and streamline your operations, a powerful ASP.NET MVC application can be a game-changer. In this blog post, we'll delve into the benefits of ASP.NET MVC development and showcase how Mozammal, a seasoned web development expert, can help you unlock the full potential of this technology through their exceptional services on Fiverr.
đŸŽ¯ #ASPNET #MVC #WebDevelopment #FiverrGig 🚀 1. Harness the Power of ASP.NET MVC: ASP.NET MVC is a versatile and robust framework that empowers businesses to build scalable, secure, and high-performing web applications. It allows for clean separation of concerns, making maintenance and testing a breeze. By leveraging ASP.NET MVC, you can develop dynamic, feature-rich web applications tailored to your specific business needs. 2. Meet Mozammal: Your Expert ASP.NET MVC Developer: When it comes to ASP.NET MVC application development, Mozammal is a trusted professional who excels in creating innovative and custom solutions. With a proven track record and extensive experience, Mozammal possesses the skills and expertise needed to transform your vision into a reality. Their Fiverr Gig offers a range of services to meet your unique requirements, delivering top-notch results that propel your business forward. 👨‍đŸ’ģ Expert Developer | Custom ASP.NET MVC Solutions | Fiverr Seller | Satisfaction Guaranteed 👍
3. Customized Solutions for Your Business: Mozammal understands that every business has distinct needs. Whether you require an e-commerce platform, a customer relationship management system, or a content management solution, Mozammal's ASP.NET MVC application development services can be tailored to meet your specific goals. By collaborating closely with you, they ensure that the end product aligns perfectly with your vision and drives tangible results. 4. Unleash Innovation with Cutting-Edge Features: Mozammal stays up to date with the latest trends and technologies in the web development landscape. By leveraging their expertise in ASP.NET MVC, they can incorporate cutting-edge features into your web application. From real-time updates using SignalR to seamless integration with social media platforms, Mozammal has the know-how to make your application stand out from the competition and keep your users engaged. 💡 Innovative Features | Real-Time Updates with SignalR | Social Media Integration 🌟 5. Seamless User Experience and Responsive Design: In today's mobile-dominated world, user experience is paramount. Mozammal's proficiency in creating intuitive user interfaces and implementing responsive design ensures that your application looks and performs flawlessly across all devices. By optimizing the user experience, Mozammal helps you engage and retain customers, ultimately driving conversions and boosting your bottom line. 📱 Responsive Design | Intuitive User Interfaces | Enhanced User Experience 🌐 6. Agile Development Process and Timely Delivery: Mozammal follows an agile development process, ensuring efficient project management and seamless collaboration. They provide regular updates on the progress of your application, incorporating feedback along the way to ensure that the end product exceeds your expectations. With a commitment to timely delivery, Mozammal ensures that your project is completed within the agreed-upon timeframe, enabling you to seize new opportunities without delay. ⌛ Agile Development | Timely Delivery | Efficient Project Management ⚡ Conclusion: If you're seeking an exceptional ASP.NET MVC application development service, Mozammal is the expert you can rely on. With their comprehensive expertise, personalized approach, and dedication to delivering outstanding results, Mozammal stands out in the competitive landscape of web development on Fiverr. By choosing Mozammal, you unlock the potential of ASP.NET MVC, accelerating your business growth, and positioning yourself for success in the digital realm. Don't miss out on this opportunity to transform your vision into a reality with Mozammal's exceptional ASP.NET MVC development services. Visit their Fiverr Gig today at [link](https://www.fiverr.com/mozammal/do-asp-dot-net-mvc-application) to get started on your journey to online excellence. đŸ’ģ Unlock Your Business Potential | Exceptional ASP.NET MVC Development | [Visit Mozammal's Fiverr Gig Today!] đŸ’ŧ


Friday, 25 December 2020

ASP.NET Core Security

 

Overview:


ASP.NET Core enables developers to easily configure and manage security for their apps. ASP.NET Core contains features for managing authentication, authorization, data protection, HTTPS enforcement, app secrets, XSRF/CSRF prevention, and CORS management. These security features allow you to build robust yet secure ASP.NET Core apps.

Features: 

ASP.NET Core provides many tools and libraries to secure your apps including built-in identity providers, but you can use third-party identity services such as Facebook, Twitter, and LinkedIn. With ASP.NET Core, you can easily manage app secrets, which are a way to store and use confidential information without having to expose it in the code.


Authentication vs. Authorization

Authentication is a process in which a user provides credentials that are then compared to those stored in an operating system, database, app or resource. If they match, users authenticate successfully, and can then perform actions that they're authorized for, during an authorization process. The authorization refers to the process that determines what a user is allowed to do.

Another way to think of authentication is to consider it as a way to enter a space, such as a server, database, app or resource, while authorization is which actions the user can perform to which objects inside that space (server, database, or app).

Common Vulnerabilities in software

ASP.NET Core and EF contain features that help you secure your apps and prevent security breaches. The following list of links takes you to documentation detailing techniques to avoid the most common security vulnerabilities in web apps:

There are more vulnerabilities that you should be aware of. For more information, see the other articles in the Security and Identity section of the table of contents.



Saturday, 18 July 2020

āĻĢেāχāϏāĻŦুāĻ• āĻĒেāϜ-āĻ āĻ…্āϝাāĻ•āϟিāĻ­ āύা āĻĨেāĻ•েāĻ“ āĻ•াāϏ্āϟāĻŽাāϰāĻ•ে āĻ…āϟো āϰিāĻĒ্āϞাāχ āĻĻিāύ



āĻ…্āϝাāĻ•āϟিāĻ­ āύা āĻĨেāĻ•েāĻ“ āĻ•াāϏ্āϟāĻŽাāϰāĻ•ে āĻ…āϟো āϰিāĻĒ্āϞাāχ āĻĻিāύ

āĻ…āύেāĻ• āϏāĻŽā§Ÿāχ āφāĻŽāϰা āĻĒেāχāϜে āĻāĻ•āϟিāĻ­ āĻĨাāĻ•ি āύা āĻ…āĻĨāĻŦা āĻāĻ•āϟি āϏাāϧাāϰāĻŖ āĻĒ্āϰāĻļ্āύেāϰ āωāϤ্āϤāϰ āĻ…āύেāĻ• āĻ•াāϏ্āϟāĻŽাāϰ āϜাāύāϤে āϚা⧟ āϝেāĻ—ুāϞোāĻ•ে Frequently asked questions āĻŦāϞে। āϤো āφāĻĒāύাāϰ āĻĒেāχāϜে āĻ•িāĻ›ু āĻĒ্āϰāĻļ্āύ āĻāĻŦং āϤাāϰ āωāϤ্āϤāϰ āϏেāϟ āĻ•āϰে āϰাāĻ–āϞেāχ āύāϤুāύ āĻ•েāω āĻāϏে āϏেāχ āĻĒ্āϰāĻļ্āύ āĻ•āϰāϞে āωāϤ্āϤāϰ āĻĒে⧟ে āϝাāĻŦে।

āϝেāĻ­াāĻŦে āϏেāϟিংāϏ āĻ•āϰāĻŦেāύ:

  • āĻĒ্āϰāĻĨāĻŽে āφāĻĒāύাāϰ Page manager app āϟি āĻ“āĻĒেāύ āĻ•āϰুāύ।
  • Tools āĻ…āĻĒāĻļāύে āĻ•্āϞিāĻ• āĻ•āϰুāύ ( āύিāϚেāϰ āĻĻিāĻ•ে āϏāϰ্āĻŦāĻĄাāύে āĻŦ্āϝাāĻ— āφāχāĻ•āύ)
  • āĻāĻŦাāϰ settings āĻ…āĻĒāĻļāύে āĻ•্āϞিāĻ• āĻ•āϰুāύ।
  • āĻāĻŦাāϰ automated responses āĻ āĻ•্āϞিāĻ• āĻ•āϰুāύ।
  • āĻāĻŦাāϰ Frequently asked questions āĻ āĻ•্āϞিāĻ• āĻ•āϰুāύ।
  • Platform messenger āĻ…āύ āĻ•āϰে āĻĻিāĻŦেāύ।
  • āϤাāϰāĻĒāϰ add a questions āĻ āĻ•্āϞিāĻ• āĻ•āϰুāύ।
  • āĻāĻŦাāϰ questions āĻŦāĻ•্āϏ āĻ āĻĒ্āϰāĻļ্āύ āĻāĻŦং response āĻŦāĻ•্āϏ āĻ āϏেāχ āĻĒ্āϰāĻļ্āύেāϰ āωāϤ্āϤāϰ āϞিāĻ–ে āĻĻিāύ।
  • āĻĄাāύāĻĻিāĻ•ে āωāĻĒāϰে save āĻŦাāϟāύ āĻ āĻ•্āϞিāĻ• āĻ•āϰুāύ āĻāĻŦং āφāĻŦাāϰ save āĻ āĻ•্āϞিāĻ• āĻ•āϰুāύ।
āĻāĻ–āύ āϝে āĻ•েāω āĻĒেāϜে āĻāϏে āĻāχ āĻĒ্āϰāĻļ্āύ āĻ•āϰāϞেāχ instant reply āĻĒাāĻŦে।

āĻ•োāύ āϧāϰāύেāϰ āĻĒ্āϰāĻļ্āύ add āĻ•āϰāĻŦেāύ?

  • āϏাāϧাāϰāĻŖāϤ āĻĄেāϞিāĻ­াāϰি āϚাāϰ্āϜ āĻ•āϤ?, āĻ•িāĻ­াāĻŦে āĻ…āϰ্āĻĄাāϰ āĻ•āϰāĻŦ?, āφāĻĒāύাāĻĻেāϰ āϏাāĻĨে āϝোāĻ—াāϝোāĻ— āĻ•িāĻ­াāĻŦে āĻ•āϰāĻŦ? āĻāϧāϰāύেāϰ āĻĒ্āϰāĻļ্āύ āĻāĻŦং āωāϤ্āϤāϰ āϰাāĻ–āϤে āĻĒাāϰেāύ।

Wednesday, 15 July 2020

How to upload a new project to Github repository



Here is how you would do it in Windows:

  1. If you don't have git installed, see this article on how to set it up.
  2. Open up a Windows command prompt.
    1.  [shortcut way: Go to the project root . press Shift+ right click]
    2. Open windows powershell or command prompt
  3. If you follow the above shortcut your directory already located. Otherwise, Change into the directory where your source code is located in the command prompt.
  4. First, create a new repository in this directory git init. This will say "Initialized empty git repository in ....git" (... is the path).
  5. Now you need to tell git about your files by adding them to your repository. Do this with git add filename. If you want to add all your files, you can do git add . Here "." is also important if you need to add all the files and folders .
  6. Now that you have added your files and made your changes, you need to commit your changes so git can track them. Type git commit -m "adding files"-m lets you add the commit message in line.

So far, the above steps is what you would do even if you were not using github. They are the normal steps to start a git repository. Remember that git is distributed (decentralized), means you don't need to have a "central server" (or even a network connection), to use git.

Now you want to push the changes to your git repository hosted with github. To you this by telling git to add a remote location, and you do that with this command:

git remote add origin https://github.com/yourusername/your-repo-name.git


*Note: your-repo-name should be created in GitHub  before you do a git remote add origin ...

New Repository

you must select private if you want to keep the project only for you, not for public.

7. Open your project in Visual Studio and Go to Manage Connection> connect to github


 Once you have done that, git now knows about your remote repository. You can then tell it to push (which is "upload") your commited files:

git push -u origin master

Comments system

Advertising

Disqus Shortname