Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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.



Sunday, 5 February 2017

Convert DataGridview to DataTable with BindingSource By JSon


     Model.Sell sell = new Model.Sell();
     BindingSource bindingSource = new BindingSource();

        private void btnAdd_Click(object sender, EventArgs e)
        {
                sell.ID=1;
               sell.Name=tbxName.Text;
               bindingSource.Add(sell);
               BindData();

        }

       private void BindData()
       {
            DataGridView1.DataSource=bindingSource;
        }


        private DataTable ConvertToDataTable()
        {
                DataTable dt = new DataTable();
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(bindingSource.List);
                dt = JsonConvert.DeserializeObject<DataTable>(json);          
               return dt;
        }

Thursday, 10 November 2016

How to use procedure in DapperClass in C# .Net

using Dapper;
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Windows.Forms;
class DataClassDapper
    {
        private string connectionString;
        private static DataClassDapper dataClass;

        public static DataClassDapper getInstance()
        {
            if (dataClass == null)
                dataClass = new DataClassDapper();

            return dataClass;
        }

        private DataClassDapper()
        {
            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["PRDb"].ConnectionString;
        }

        public IDbConnection OpenConnection()
        {
            IDbConnection connection = new SqlConnection();

            connection.ConnectionString = connectionString;

            try
            {
                connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Error Connecting database.");
            }

            return connection;
        }

  internal static bool ExecuteProc(string sql, List<SqlParameter> paramList = null)
        {
            try
            {
                using (IDbConnection connection = DataClass.getInstance().OpenConnection())
                {

                    DynamicParameters dp = new DynamicParameters();
                    if (paramList != null)
                        foreach (SqlParameter sp in paramList)
                            dp.Add(sp.ParameterName, sp.SqlValue, sp.DbType);
                
                    return connection.Execute(sql, dp, commandType: CommandType.StoredProcedure) > 0;
                }
            }
            catch (Exception e)
            {
                //do logging
                return false;
            }
        }
}





Your Model:
    public class Company : IEquatable<Company>
    {
        public int id { get; set; }

        public string name { get; set; }
               
        public string address { get; set; }
               
        public string phone { get; set; }

        public string fax { get; set; }
       
        public string email { get; set; }

        public string website { get; set; }
     }


using System;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Collections.Generic;
using PayrollManagementSystem.Model;
using PayrollManagementSystem.Database;
using Dapper;
public  class CompanyManager
    {
       public static CompanyManager companyManager;

        public CompanyManager()
        {
       
        }
  public bool AddNewCompanyProc(Company company)
        {
            string insertQuery = @"usp_insertCompany";
            List<SqlParameter> list = new List<SqlParameter>();
            SqlParameter param = new SqlParameter();
            param.ParameterName = "@name";
            param.Value = company.name;
            list.Add(param);
            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@address";
            param1.Value = company.address;
            list.Add(param1);

         

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = "@phone";
            param2.Value = company.phone;
            list.Add(param2);
            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = "@fax";
            param3.Value = company.fax;
            list.Add(param3);

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = "@email";
            param4.Value = company.email;
            list.Add(param4);

            SqlParameter param5 = new SqlParameter();
            param5.ParameterName = "@website";
            param5.Value = company.website;
            list.Add(param5);
            return DataClassDapper.ExecuteProc(insertQuery, list);
        }

}


CompanyEntryForm.cs





void SaveData()
        {

            try
            {


                Company company = new Company(0, tbxCompanyName.Text, tbxAddress.Text, tbxPhone.Text, tbxFax.Text, tbxEmail.Text, tbxWebAddress.Text);
                bool success= CompanyManager.getInstance().AddNewCompanyProc(company);
                if (success)
                {
                    KryptonMessageBox.Show("Company saved successfully!", "Add Company.", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else
                {
                    KryptonMessageBox.Show("Company saved failed!", "Add Company.", MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {


            }

        }

Comments system

Advertising

Disqus Shortname