Friday, 15 September 2017

Bulk Product Upload Using Excel Sheet

What we want to achieve?
  • We want to upload product and its features using Excel Sheet. 
  • Excel sheet should be validated as per our sample data. 
  • If the Excel sheet is invalid list of errors should be display with link to that particular error so that user can reach there by clicking on link itself. 
  • Also we should be able to correct invalid excel sheet on the screen upload it again.
Sample Excel : 


Screen 01 : When we upload Invalid Excel Sheet.



Screen 02 : When we click on error link then that particular error will be focused.


Screen 03 : When we click on error link then that particular error will be focused.



Screen 04: When we correct all errors and upload again.


Step 01 : We have two tables : Products and ProductFeatures

Table Products 
CREATE TABLE [dbo].[Products](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nvarchar](40) NOT NULL,
[SupplierID] [int] NULL,
[CategoryID] [int] NULL,
[QuantityPerUnit] [nvarchar](20) NULL,
[UnitPrice] [money] NULL,
[UnitsInStock] [smallint] NULL,
[UnitsOnOrder] [smallint] NULL,
[ReorderLevel] [smallint] NULL,
[Discontinued] [bit] NOT NULL,
[CreatedOn] [date] NULL,
 CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Table ProductFeatures
CREATE TABLE [dbo].[ProductFeatures](
[FeatureId] [int] IDENTITY(1,1) NOT NULL,
[ProductId] [int] NULL,
[ProductFeature] [nvarchar](max) NULL,
[Status] [bit] NOT NULL,
[IsDeleted] [bit] NOT NULL,
[CreatedOn] [date] NULL,
 CONSTRAINT [PK_ProductFeatures] PRIMARY KEY CLUSTERED
(
[FeatureId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 02 : We have got function and Procedures

Function to Split string using delimiter.
CREATE FUNCTION [dbo].[func_Split]
    (  
    @DelimitedString    varchar(8000),
    @Delimiter              varchar(100)
    )
RETURNS @tblArray TABLE
    (
    ElementID   int IDENTITY(1,1),  -- Array index
    Element     varchar(1000)               -- Array element contents
    )
AS
BEGIN

    -- Local Variable Declarations
    -- ---------------------------
    DECLARE @Index      smallint,
                    @Start      smallint,
                    @DelSize    smallint

    SET @DelSize = LEN(@Delimiter)

    -- Loop through source string and add elements to destination table array
    -- ----------------------------------------------------------------------
    WHILE LEN(@DelimitedString) > 0
    BEGIN

        SET @Index = CHARINDEX(@Delimiter, @DelimitedString)

        IF @Index = 0
            BEGIN

                INSERT INTO
                    @tblArray
                    (Element)
                VALUES
                    (LTRIM(RTRIM(@DelimitedString)))

                BREAK
            END
        ELSE
            BEGIN

                INSERT INTO
                    @tblArray
                    (Element)
                VALUES
                    (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))

                SET @Start = @Index + @DelSize
                SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)

            END
    END

    RETURN
END

Procedure 01:

CREATE PROC [dbo].[Usp_InsertProductAndFeatures]
@ProductName NVARCHAR(MAX),
@CategoryId INT,
@ProductFeatures VARCHAR(MAX)
AS
BEGIN
   DECLARE @PId INT
   DECLARE @Feature VARCHAR(MAX)

   INSERT Products
   (
   ProductName,
   CategoryID,
   CreatedOn
    )
   VALUES
   (
   @ProductName,
   @CategoryId,
   GETDATE()
    );

  SET @PId= @@IDENTITY;

  DECLARE @ExecQuery NVARCHAR(MAX);
  SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(@PId AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split(@ProductFeatures, '*|*');

  EXECUTE sp_executesql @ExecQuery;

END

Procedure 02:

CREATE PROCEDURE [dbo].[Usp_AddProductFeatures]  
     (  
   @PId INT,  
   @CreatedDate DATETIME,  
   @element    VARCHAR(MAX),  
   @delimiter VARCHAR(MAX)  
     )  
AS  
BEGIN  
  DECLARE @result BIT = 0;  
 
  ;WITH prodFeature AS(  
   SELECT * FROM dbo.func_split(@element, '+|+')  
  )  
 
     INSERT INTO ProductFeatures  
  (  
   ProductId,  
   CreatedOn,  
   ProductFeature  
  )  
    VALUES  
    (  
     @PId,  
     @createdDate,  
     (select Element from prodFeature where elementId = 1)  
    )  
     RETURN @result  

END

Step 03 : We have got models in SampleMvc.Models :

1.) Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleMvc.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public int CategoryId { get; set; }
        public string ProductName { get; set; }
        public string ProductFeature { get; set; }
        public DateTime CreateOn { get; set; }
    }

}

2.) ProductExcel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleMvc.Models
{
    public class ProductExcel
    {
        public int ProductId { get; set; }
        public string PNameAndFeature { get; set; }
    }
}

3) ProductExcelRowCheck.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleMvc.Models
{
    public class ProductExcelRowCheck
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public List<ExcelProductFeatureChk> PFeature { get; set; }
        public bool IsBlockDone { get; set; }
    }
}

4) ExcelProductFeatureChk.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleMvc.Models
{
    public class ExcelProductFeatureChk
    {
        public int FID { get; set; }
        public string ProductFreature { get; set; }
    }
}

Step 04 : We have got methods in SampleMvc.DA:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SampleMvc.Models;
using System.Data.SqlClient;

namespace SampleMvc.DA
{
    public class ProductDA : SQLHelper
    {
        public void AddProductAndFeatures(Product product, string productFeature)
        {
            try
            {
                int i = ExecNonQueryProc("Usp_InsertProductAndFeatures",
                new SqlParameter("@ProductName", product.ProductName),
                new SqlParameter("@CategoryId", product.CategoryId),
                new SqlParameter("@ProductFeatures", productFeature));
            }
            catch
            {
                throw;
            }
            finally
            {
                CloseConnection();
            }
        }
    }

}

Step 05 : We have got methods in SampleMvc.Helpers :

FlowHelper.cs :

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace SampleMvc.Helpers
{
    public static class FlowHelper
    {
        public static bool CreateDirectoryIfNotExists(string folderPath)
        {
            try
            {
                bool folderExists = Directory.Exists((folderPath));
                if (!folderExists)
                {
                    Directory.CreateDirectory((folderPath));
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                throw;
            }
        }
        public static bool TryToDeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                throw;
            }
        }
    }
}

SessionHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SampleMvc.Models;

namespace SampleMvc.Helpers
{
    public class SessionHelper
    {
        public Product Product
        {
            get
            {
                return HttpContext.Current.Session["Productinfo"] as Product;
            }
            set
            {
                HttpContext.Current.Session["Productinfo"] = value;
            }
        }
    }
}

Step 06 : In ProductController Class :

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleMvc.Helpers;
using SampleMvc.Models;
using SampleMvc.DA;
using ExcelDataReader;

namespace SampleMvc.Controllers
{
    public class ProductController : Controller
    {
        public ActionResult Product()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Product(HttpPostedFileBase postedFile)
        {
            string ext = Path.GetExtension(postedFile.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {
                string folderPath = Server.MapPath("/BulkUpload");
                FlowHelper.CreateDirectoryIfNotExists(folderPath);

                string filePath = "";
                filePath = "/BulkUpload/" + "QA" + ext;
                string path = Server.MapPath(filePath);
                postedFile.SaveAs(path);
                // Install ExcelDataReader 3.1.0 and ExcelDataReader.DataSet 3.1.0 : Use command to do so as given below.
                // Install-Package ExcelDataReader -Version 3.1.0
                // Install-Package ExcelDataReader.DataSet -Version 3.1.0
                // Reading excel file using excel data reader.
                using (var stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        DataSet result = reader.AsDataSet();
                        DataTable dt = result.Tables[0];

                        if (ValidateExcelFile(dt))
                        {
                            // Save Product and features.
                            CreateValidatedExcelFile(dt);
                        }
                        else
                        {
                            // Invalid excel action.
                            return View(dt);
                        }
                    }
                }
                // Delete uploaded excel file after bulk upload.
                bool fileDeleted = FlowHelper.TryToDeleteFile(path);
                TempData["ErrorLists"] = null;
            }
            return View();
        }

        [HttpPost]
        public JsonResult ValidatedProductExcelUpload(List<ProductExcel> bulkExcelList)
        {
            DataTable dt = new DataTable();
            dt = ConvertListToDataTable(bulkExcelList);
            if (ValidateExcelFile(dt))
            {
                // Save Product and features.
                CreateValidatedExcelFile(dt);
            }

            string json = string.Empty;
            List<string> errList = TempData["ErrorLists"] as List<string>;
            if (errList != null && errList.Count > 0)
            {
                json = string.Format("<h3 id=\"errList\"><i class=\"fa fa-minus-square\"></i> List(s) of Errors in Excel Sheet.</h3><ul class=\"ulerrlist\">{0}</ul>", string.Join(string.Empty, errList.Select(i => string.Concat("<li>", i, "</li>")).ToList()));
            }
            return Json(json);
        }

        /// <summary>
        /// Method to validate excel data
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        ///
        private bool ValidateExcelFile(DataTable dt)
        {
            List<ProductExcelRowCheck> eRowCheck = new List<ProductExcelRowCheck>();
            List<string> errList = new List<string>();
            int excelColumnCount = dt.Columns.Count;
            int excelRowCount = dt.Rows.Count;

            for (int row = 0; row < excelRowCount; row++)
            {
                // Id Check
                if (IsNumber(Convert.ToString(dt.Rows[row][0])))
                {
                    int id = Convert.ToInt32(dt.Rows[row][0]);
                    var lastExcelRow = eRowCheck.LastOrDefault();

                    ProductExcelRowCheck ExcelRow = eRowCheck.FirstOrDefault(q => q.ProductId == id && q.IsBlockDone == true);
                    if (ExcelRow == null)
                    {

                        if (lastExcelRow != null && lastExcelRow.IsBlockDone == false)
                        {
                            // Title Check
                            if (Convert.ToString(dt.Rows[row][1]) == string.Empty)
                            {
                                errList.Add("<a href='javascript:;' class='exErrLnk' rc='" + row + "1'>Product name or Product feature can not be blank at [" + row + "][B]</a>");
                            }
                            else
                            {
                                if (lastExcelRow != null)
                                {
                                    if (lastExcelRow.ProductId == id)
                                    {
                                        if (lastExcelRow.PFeature == null)
                                        {
                                            lastExcelRow.PFeature = new List<ExcelProductFeatureChk>();
                                        }
                                        // Adding Options
                                        lastExcelRow.PFeature.Add(new ExcelProductFeatureChk
                                        {
                                            ProductFreature = Convert.ToString(dt.Rows[row][1])
                                        });

                                        // Duplicate Options Check
                                        List<ExcelProductFeatureChk> dublicateFeature = lastExcelRow.PFeature.GroupBy(o => o.ProductFreature).SelectMany(grp => grp.Skip(1)).ToList();
                                        if (dublicateFeature != null && dublicateFeature.Count > 0)
                                        {
                                            errList.Add("<a href='javascript:;' class='exErrLnk' t='f' pid='" + lastExcelRow.ProductId + "' col='1'>Duplicate features</a>");
                                            //lastExcelRow.IsBlockDone = true;
                                        }
                                    }
                                    else
                                    {
                                        lastExcelRow.IsBlockDone = true;

                                        // Adding Question
                                        eRowCheck.Add(new ProductExcelRowCheck
                                        {
                                            ProductId = Convert.ToInt32(dt.Rows[row][0]),
                                            ProductName = Convert.ToString(dt.Rows[row][1]),
                                            IsBlockDone = false
                                        });

                                        // Duplicate Question Check
                                        List<ProductExcelRowCheck> dublicateProduct = eRowCheck.GroupBy(o => o.ProductName)
                                                                                 .Where(c => c.Count() > 1)
                                                                                 .SelectMany(grp => grp.Skip(1)).ToList();

                                        if (dublicateProduct != null && dublicateProduct.Count > 0)
                                        {
                                            var lastdublicateProduct = dublicateProduct.LastOrDefault();
                                            errList.Add("<a href='javascript:;' class='exErrLnk' t='p' pid='" + lastdublicateProduct.ProductId + "' col='1'>Duplicate Products</a>");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            eRowCheck.Add(new ProductExcelRowCheck
                            {
                                ProductId = Convert.ToInt32(dt.Rows[row][0]),
                                ProductName = Convert.ToString(dt.Rows[row][1]),
                                IsBlockDone = false
                            });
                        }
                    }
                    else
                    {
                        errList.Add("<a href='javascript:;' class='exErrLnk' t='p' tr='" + row + "'>Duplicate ProductId[" + ExcelRow.ProductId + "] at [" + row + "][A]</a>");
                    }
                }
                else
                {
                    errList.Add("Product Id must be numberic value at <a href='javascript:;' class='exErrLnk' rc='" + row + "0'>[" + row + "][A]</a>");
                }
            }

            TempData["ErrorLists"] = errList;
            return !(errList.Count > 0);
            //return false;
        }
        private bool IsNumber(string v)
        {
            int result;
            bool isNumeric = int.TryParse(v, out result);
            return isNumeric;
        }

        private static DataTable ConvertListToDataTable(List<ProductExcel> list)
        {
            DataTable table = new DataTable();
            // Get max columns.
            int columns = 2;

            // Add columns.
            for (int i = 0; i < columns; i++)
            {
                table.Columns.Add();
            }
            // Add rows.          
            foreach (var array in list)
            {
                table.Rows.Add(array.ProductId, array.PNameAndFeature);
            }
            return table;
        }
        private void CreateValidatedExcelFile(DataTable dt)
        {
            //SessionHelper sessionHelper = new SessionHelper();
            //if (sessionHelper.Product != null)
            //{
            int prodColumnCount = dt.Columns.Count;
            int prodRowCount = dt.Rows.Count;
            int prodID = Convert.ToInt32(dt.Rows[0][0]);
            Product product = new Product();
            ProductDA productDA = new ProductDA();
            bool isFeature = false;
            string ProductFeature = string.Empty;

            for (int row = 0; row < prodRowCount; row++)
            {
                if (prodID == Convert.ToInt32(dt.Rows[row][0]))
                {
                    if (!isFeature)
                    {
                        product.ProductName = Convert.ToString(dt.Rows[row][1]);
                        //product.CategoryId = sessionHelper.Product.CategoryId;
                        //Get CategoryId from session or Where ever you want.
                        product.CategoryId = 2;
                        isFeature = true;
                    }
                    else
                    {
                        ProductFeature += Convert.ToString(dt.Rows[row][1]) + "*|*";
                        if (row == prodRowCount - 1)
                        {
                            //Call function to save last set of record before exiting loop.
                            ProductFeature = ProductFeature.Substring(0, ProductFeature.Length - 3);
                            productDA.AddProductAndFeatures(product, ProductFeature);
                            TempData["message"] = "Bulk upload successful.";
                        }
                    }
                }
                else
                {
                    //If Pid differs then call function to save data.
                    ProductFeature = ProductFeature.Substring(0, ProductFeature.Length - 3);
                    productDA.AddProductAndFeatures(product, ProductFeature);
                    prodID = Convert.ToInt32(dt.Rows[row][0]);
                    ProductFeature = "";
                    row--;
                    isFeature = false;
                }
            }
            //}
        }
    }

}

Step 07 : In Views :

@{
    Layout = null;
}

@model System.Data.DataTable
@using System.Data

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Product and feature upload in bulk using Excel Sheet.</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="~/Contents/Bootstrap/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/Bootstrap/jquery.min.js"></script>
    <script src="~/Scripts/Bootstrap/bootstrap.min.js"></script>
    <link href="~/Contents/CSS/Site.css" rel="stylesheet" />
    <link href="~/Contents/CSS/ProductExcel.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script type="text/javascript">
        $(document).ready(function () {
            $('div[id^="err"]').html("");

            var columns = ["A", "B", "C", "D", "E", "F", "G"];

            $(".readExcel table th").each(function () {
                $(this).html(columns[parseInt($(this).text())]);
            });

            ApplyEvents();        
        });

        function ApplyEvents() {
            $("#btnUpload").click(function () {
                if ($("#flExcel").val() != "") {
                }
                else {
                    $("#errflExcel").html("Please select file for bulk upload.");
                    return false;
                }
            });

            $('input[type="text"]').on('focus', function () {
                $(this).parent().addClass('activeCell');
            });
            $('input[type="text"]').on('blur', function () {
                $(this).parent().removeClass('activeCell');
            });

            $("#btnVExcelUpload").on('click', function () {
                $(".successMsg").html("");
                var bulkExcelList = [];
                var counter = 0;
                $(".readExcel table tr").each(function (i, tr) {
                    var bulkExcel = { ProductId: 0, PNameAndFeature: "" };
                    if (counter++ > 0) {
                        bulkExcel.ProductId = $(tr).find("td:eq(0) input:text").val();
                        bulkExcel.PNameAndFeature = $(tr).find("td:eq(1) input:text").val();
                        bulkExcelList.push(bulkExcel);
                    }
                });

                bulkExcelList = JSON.stringify({ 'bulkExcelList': bulkExcelList });

                $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: 'POST',
                    url: '/Product/ValidatedProductExcelUpload',
                    data: bulkExcelList,
                    success: function (data) {
                        $("#divErrLists").html(data);
                        if (!data) {
                            $("#readExcel").hide();                      
                            $(".successMsg").html("Bulk upload successful.");
                        }
                        ApplyErrorLinks();
                    }
                });
            });
            ApplyErrorLinks();
        }

        function ApplyErrorLinks() {
            $(".exErrLnk").on('click', function () {
                $('.activeCell').removeClass("activeCell");
                var exEle = $(this).attr("rc");
                if (exEle) {
                    $("#" + exEle).focus();
                    $("#txt" + exEle).focus();
                } else {
                    var type = $(this).attr("t");
                    var pid = $(this).attr("pid");
                    var col = $(this).attr("col");
                    var tr = $(this).attr("tr");

                    if (type == "f") {
                        if (pid && col) {
                            var counter = 0;
                            $(".readExcel table tr").each(function (i, tr) {
                                if ($(tr).find("td:eq(0) input:text").val() == pid) {
                                    if (counter++ > 0) {
                                        $(tr).find("td:eq(" + col + ")").addClass('activeCell');
                                    }
                                }
                            });
                        }
                    }
                    if (type == "p") {
                        if (pid && col) {
                            $(".readExcel table tr").each(function (i, tr) {
                                if ($(tr).find("td:eq(0) input:text").val() == pid) {
                                    $(tr).find("td:eq(" + col + ")").addClass('activeCell');

                                    var product = $(tr).find("td:eq(" + col + ") input:text").val();

                                    $(".readExcel table tr").each(function (i, tr) {
                                        if ($(tr).find("td:eq(1) input:text").val() == product)
                                            $(tr).find("td:eq(1)").addClass('activeCell');

                                    });
                                }
                            });
                        }
                    }
                    if (tr) {
                        alert("");
                        tr++
                        $(".readExcel table tr:eq(" + tr + ")").addClass('activeCell');
                    }
                }
            });

            $("#errList").on('click', function () {
                if ($(".ulerrlist").css("display") == "none") {
                    $(this).find("i").attr("class", "fa fa-minus-square");
                    $(".ulerrlist").slideDown();
                } else {
                    $(this).find("i").attr("class", "fa fa-plus-square");
                    $(".ulerrlist").slideUp();
                }
            });
        }
    </script>
</head>
<body>
    <div class="container-fluid">
        <div class="row content">
            <div class="col-sm-3 sidenav">
                <h4>Add Product</h4>
                <ul class="nav nav-pills nav-stacked">
                    <li class="active"><a href="#section1">Home</a></li>
                    <li><a href="/Product/Product">Bulk Product Upload</a></li>
                    <li><a href="#section3">Family</a></li>
                    <li><a href="#section3">Photos</a></li>
                </ul>
                <br>
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search Blog..">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button">
                            <span class="glyphicon glyphicon-search"></span>
                        </button>
                    </span>
                </div>
            </div>

            <div class="col-sm-9">
                <h4><small>Product Bulk Upload with its features.</small></h4>
                <hr>
                <div class="col-sm-12">
                    <div class="col-sm-3">
                        Select File :
                    </div>
                    <div class="col-sm-9">
                        <div id="divExcel" class="divExcelUP">
                            @using (Html.BeginForm("Product", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
                            {
                             
                                <div class="editor-field">
                                    <input type="file" id="flExcel" name="postedFile" />
                                    <div id="errflExcel" class="divErr"></div>
                                </div>
                                <br />
                                <div class="editor-field">
                                    <input class="Button" id="btnUpload" type="submit" value="Upload" />
                                </div>
                                <br />
                                <div class="editor-field">
                                    <div class="successMsg">
                                        @TempData["Msg"]
                                    </div>
                                </div>
                            }
                        </div>
                    </div>
                </div>

                <div class="col-sm-12">
                    <div class="clearfix"></div>
                    <div id="divErrLists" class="errlists">
                        @if (TempData["ErrorLists"] != null)
                        {
                            <h3 id="errList"><i class="fa fa-minus-square"></i>List(s) of Errors in Excel Sheet.</h3>
                            <ul class="ulerrlist">
                                @foreach (var errlist in (List<string>)TempData["ErrorLists"])
                                {
                                    <li>
                                        @Html.Raw(errlist)
                                    </li>
                                }
                            </ul>
                        }
                    </div>
                    <div class="clearfix"></div>
                    <div id="readExcel" class="readExcel">
                        @if (Model != null)
                        {
                            <input class="Button floatright marginbottom" id="btnVExcelUpload" type="submit" value="Upload Excel" />
                            <table class="table table-responsive table-bordered">
                                <thead>
                                    <tr>
                                        @foreach (DataColumn column in Model.Columns)
                                        {
                                            <th>@column.Ordinal</th>
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @{
                                        for (int r = 0; r < Model.Rows.Count; r++)
                                        {
                                            DataRow row = Model.Rows[r];
                                        <tr class="beRow" id="@r">
                                            @for (int c = 0; c < Model.Columns.Count; c++)
                                            {
                                                <td id="@string.Concat(r, c)">
                                                    <input type="text" id="@string.Concat("txt", r, c)" class="txtExcel" value="@row[c]" />
                                                </td>
                                            }
                                        </tr>
                                        }
                                    }
                                </tbody>
                            </table>
                        }
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

Saturday, 9 September 2017

Cursor Replacement : By creating dynamic query.

We have a situation where we have to store product details in Product table and Product features in ProductFeatures Table using single screen.

So We'll insert Product details in Product table and get its product to insert product features in
ProductFeatures table.

We will use two Procedures and one Function to achieve this.

We will use dynamic query :

DECLARE @ExecQuery NVARCHAR(MAX);
  SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(@PId AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split(@ProductFeatures, '*|*');

  EXECUTE sp_executesql @ExecQuery;

Example : Passing some values to @ProductFeatures and Lets see output using print.

  DECLARE @ExecQuery NVARCHAR(MAX);
  SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(1 AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split('Feature 01*|*Feature 02*|*Feature 03', '*|*');

  print @ExecQuery

Output:

  EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  3:48PM', 'Feature 01', '+|+';
  EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  3:48PM', 'Feature 02', '+|+';
  EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  3:48PM', 'Feature 03', '+|+'

Result : If we execute @ExecQuery, all queries will be executed one by one.

Practical Example 1 : With Only one value to be inserted into ProductFeatures table.

Step 1 : Create function

CREATE FUNCTION [dbo].[func_Split]
    (  
    @DelimitedString    varchar(8000),
    @Delimiter              varchar(100)
    )
RETURNS @tblArray TABLE
    (
    ElementID   int IDENTITY(1,1),  -- Array index
    Element     varchar(1000)               -- Array element contents
    )
AS
BEGIN

    -- Local Variable Declarations
    -- ---------------------------
    DECLARE @Index      smallint,
                    @Start      smallint,
                    @DelSize    smallint

    SET @DelSize = LEN(@Delimiter)

    -- Loop through source string and add elements to destination table array
    -- ----------------------------------------------------------------------
    WHILE LEN(@DelimitedString) > 0
    BEGIN

        SET @Index = CHARINDEX(@Delimiter, @DelimitedString)

        IF @Index = 0
            BEGIN

                INSERT INTO
                    @tblArray
                    (Element)
                VALUES
                    (LTRIM(RTRIM(@DelimitedString)))

                BREAK
            END
        ELSE
            BEGIN

                INSERT INTO
                    @tblArray
                    (Element)
                VALUES
                    (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))

                SET @Start = @Index + @DelSize
                SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)

            END
    END

    RETURN
END

Step 2 : Create first procedure to insert product details in product table and pass values to insert product features to productfeatures table using dynamic query.


CREATE PROC [dbo].[Usp_InsertProductAndFeatures]
@ProductName NVARCHAR(MAX),
@CategoryId INT,
@ProductFeatures VARCHAR(MAX)
AS
BEGIN
   DECLARE @PId INT
   DECLARE @Feature VARCHAR(MAX)

   INSERT Products
   (
   ProductName,
   CategoryID,
   CreatedOn
    )
   VALUES
   (
   @ProductName,
   @CategoryId,
   GETDATE()
    );

  SET @PId= @@IDENTITY;

  DECLARE @ExecQuery NVARCHAR(MAX);
  SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(@PId AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split(@ProductFeatures, '*|*');

  EXECUTE sp_executesql @ExecQuery;

END


Step 3 : Create second procedure to insert product features.

CREATE PROCEDURE [dbo].[Usp_AddProductFeatures]
     (
   @PId INT,
   @CreatedDate DATETIME,
   @element    VARCHAR(MAX),
   @delimiter VARCHAR(MAX)
     )
AS
BEGIN
  DECLARE @result BIT = 0;

  ;WITH prodFeature AS(
   SELECT * FROM dbo.func_split(@element, '+|+')
  )

     INSERT INTO ProductFeatures
  (
   ProductId,
   CreatedOn,
   ProductFeature
  )
    VALUES
    (
     @PId,
     @createdDate,
     (select Element from prodFeature where elementId = 1)
    )
     RETURN @result

END

==================================================================
Practical Example 2 : With multiple value to be inserted into ProductFeatures table.

For multiple values we'll pass all values to @ProductFeature separating them with delimiter +|+ like : If we have to pass product feature, its type and it made in details then we can pass in single string separated by +|+ as shown below :

ProductFeature+|+Type+|+Made In Details

Example : 

'Feature 01+|+New+|+Made In India*|*Feature 02+|+Old+|+Made In China*|*Feature 03+|+New+|+Made In India'

Note the output of the following query :


Select * from  dbo.func_split('Feature 01+|+New+|+Made In India*|*Feature 02+|+Old+|+Made In China*|*Feature 03+|+New+|+Made In India','*|*')




Note the output of the following query :


DECLARE @ExecQuery NVARCHAR(MAX);
SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(1 AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split('Feature 01+|+New+|+Made In India*|*Feature 02+|+Old+|+Made In China*|*Feature 03+|+New+|+Made In India', '*|*');

  print @ExecQuery

Output : 

EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  9:48PM', 'Feature 01+|+New+|+Made In India', '+|+';
EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  9:48PM', 'Feature 02+|+Old+|+Made In China', '+|+';

EXEC [dbo].[Usp_AddProductFeatures] 1, 'Sep  9 2017  9:48PM', 'Feature 03+|+New+|+Made In India', '+|+'

So we'll use this way as :

DECLARE @ExecQuery NVARCHAR(MAX);
SELECT @ExecQuery  = COALESCE(@ExecQuery +';' ,'') + 'EXEC [dbo].[Usp_AddProductFeatures] '+CAST(@PId AS VARCHAR)+', '''+ CAST(GETDATE() AS VARCHAR) +''', ''' + Element+''', ''+|+'''
  FROM dbo.func_split(@ProductFeatures, '*|*');

  EXECUTE sp_executesql @ExecQuery;

Example Steps : 

Step 1 : We have already created function [dbo].[func_Split].

Step 2 : We have already created first procedure [dbo].[Usp_InsertProductAndFeatures] to insert product details in product table and pass values to insert product features to productfeatures table using dynamic query.

Step 3 :  Create second procedure to insert product features with slight change as :

CREATE PROCEDURE [dbo].[Usp_AddProductFeatures]
     (
   @PId INT,
   @CreatedDate DATETIME,
   @element    VARCHAR(MAX),
   @delimiter VARCHAR(MAX)
     )
AS
BEGIN
  DECLARE @result BIT = 0;

  ;WITH prodFeature AS(
   SELECT * FROM dbo.func_split(@element, '+|+')
  )

     INSERT INTO ProductFeatures
  (
   ProductId,
   CreatedOn,
   ProductFeature,
   Type,
   MadeInDetail
  )
    VALUES
    (
     @PId,
     @createdDate,
     (select Element from prodFeature where elementId = 1),
     (select Element from prodFeature where elementId = 2),
     (select Element from prodFeature where elementId = 3)
    )
     RETURN @result

END

Note the output of CTE prodFeature we have used in our last step.

;WITH prodFeature AS(
   SELECT * FROM dbo.func_split('Feature 01+|+New+|+Made In India', '+|+')
  )

  Select * from prodFeature

Friday, 18 August 2017

Miscellaneous


  1. The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
================================================================

Datatable.Net Grid Event Bind For Paging

 $("a[data-dt-idx]").click(function(){
            $(".btnUrl").off().click(function () {
                vDialog.OpenURL($(this).attr("url"));
            });

            $(".btnEdit").off().click(function () {
                window.location.href = "/Event/ManageEvent?eid=" + $(this).attr("eid");
            });

            $(".btnDelete").off().click(function () {
                vDialog.DeleteEvent($(this).attr("eid"));
            });
        });

=========================================================
Get Query String using jquery

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.href);

    return results[1] || 0;
}

Call method to get query string

 mid: $.urlParam("mid")
or
var mid = $.urlParam("mid")

------------------------------------------------------------------------------------------------------

Create file and directory


Create file and directory 
We can use System.IO.Directory.CreateDirectory

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

                    // Creating Directory using static methods in class FlowHelper
                    string folderPath = Server.MapPath("/FileUpload");
                    FlowHelper.CreateDirectoryIfNotExists(folderPath);

                    // Saving file to given folder
                    string ext = Path.GetExtension(postedFile.FileName);
                    if (ext == ".jpg" || ext == ".png" || ext == ".jpeg" || ext == ".gif")
                    {
                    string filePath = "";
                    filePath = "/FileUpload/" + "abc" + ext;
                    string path = Server.MapPath(filePath);
                    postedFile.SaveAs(path);
                    }

                    // Deleting file  using static method in class FlowHelper
                    bool fileDeleted = FlowHelper.TryToDeleteFile(path);


    public class FlowHelper
    {
        public static bool CreateDirectoryIfNotExists(string folderPath)
        {
            try
            {
                bool folderExists = Directory.Exists((folderPath));
                if (!folderExists)
                {
                    Directory.CreateDirectory((folderPath));
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                throw;
            }
        }
        public static bool TryToDeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                throw;
            }
        }
    }

Sunday, 13 August 2017

Part 4 : CRUD in ASP.NET MVC using jquery modal popup.

What we want to achieve?

1.) We want to display list of employee in table as shown figure.

2) When we click Add Employee button, modal popup show open to add employee.



3) When  we click Edit button, modal popup show open to edit employee


Project Solution is name as SampleMvc.



In SQLHELPER Class : Inherited by data access class.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Configuration;

namespace SampleMvc.DA
{
    /// <summary>
    /// Summary description for Class_SQLHelper
    /// </summary>
    public class SQLHelper
    {
        private SqlCommand cmd = new SqlCommand();
        private SqlConnection conn;
        private bool bool_Status;
        private string str_Error;

        public SQLHelper()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
        }

        protected void OpenConnection()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
            }
            catch (Exception ex)
            {
                OperationStatus = false;
                ErrorMessage = "Error : " + ex.Message;
            }
        }

        protected void CloseConnection()
        {
            try
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
            catch (Exception ex)
            {
                OperationStatus = false;
                ErrorMessage = "Error : " + ex.Message;
            }
        }

        public SqlConnection Connection
        {
            get { return conn; }
        }

        public SqlCommand Command
        {
            get { return cmd; }
            set { cmd = value; }
        }

        public bool OperationStatus
        {
            get { return bool_Status; }
            set { bool_Status = value; }
        }

        public string ErrorMessage
        {
            get { return str_Error; }
            set { str_Error = value; }
        }

        /// <summary>
        /// Constructs a SqlCommand with the given parameters. This method is normally called
        /// from the other methods and not called directly. But here it is if you need access
        /// to it.
        /// </summary>
        /// <param name="qry">SQL query or stored procedure name</param>
        /// <param name="type">Type of SQL command</param>
        /// <param name="args">Query arguments. Arguments should be in pairs where one is the
        /// name of the parameter and the second is the value. The very last argument can
        /// optionally be a SqlParameter object for specifying a custom argument type</param>
        /// <returns></returns>
        public SqlCommand CreateCommand(string qry, CommandType type, params object[] args)
        {
            SqlCommand cmd = new SqlCommand(qry, conn);
            OpenConnection();
            // Set command type
            cmd.CommandType = type;

            // Construct SQL parameters
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] is string && i < (args.Length - 1))
                {
                    SqlParameter parm = new SqlParameter();
                    parm.ParameterName = (string)args[i];
                    parm.Value = args[++i];
                    cmd.Parameters.Add(parm);
                }
                else if (args[i] is SqlParameter)
                {
                    cmd.Parameters.Add((SqlParameter)args[i]);
                }
                else throw new ArgumentException("Invalid number or type of arguments supplied");
            }

            return cmd;
        }

        /// <summary>
        /// Executes a stored procedure that returns no results
        /// </summary>ExecNonQueryProc
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>The number of rows affected</returns>
        public int ExecNonQueryProc(string proc, params object[] args)
        {

            int result = 0;
            //using (conn)
            //{
            //    OpenConnection();
                using (SqlCommand cmd = CreateCommand(proc, CommandType.StoredProcedure, args))
                {
                    result= cmd.ExecuteNonQuery();
                    CloseConnection();
                    return result;
                }
            //}
        }

        /// <summary>
        /// Executes a query that returns a single value
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Value of first column and first row of the results</returns>
        public object ExecScalarProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                return cmd.ExecuteScalar();
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a SqlDataReader
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a SqlDataReader</returns>
        public SqlDataReader ExecDataReaderProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                return cmd.ExecuteReader();
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a DataSet</returns>
        public DataSet ExecDataSetProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                return ds;
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a DataTable</returns>
        public DataTable ExecDataTableProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                return dt;
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <returns>Results as a DataTable</returns>
        public DataTable ExecDataTableProc(string qry)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                return dt;
            }
        }
    }

}

In Modal Class Library :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleMvc.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public DateTime BirthDate { get; set; }
    }
}

In Data Access Class Library :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SampleMvc.Models;
using System.Data.SqlClient;
using System.Data;

namespace SampleMvc.DA
{
    public class EmployeeDA : SQLHelper
    {
        public void AddEmployee(Employee emp)
        {
            try
            {
                int i = ExecNonQueryProc("Usp_AddEmployee",
                new SqlParameter("@LastName", emp.LastName),
                new SqlParameter("@FirstName", emp.FirstName),
                new SqlParameter("@Title", emp.Title),
                new SqlParameter("@Birthdate", emp.BirthDate));
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error : " + ex.Message;
                OperationStatus = false;
            }
            finally
            {
                CloseConnection();
            }
        }
        public DataTable GetAllEmployees()
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_GetAllEmployees");
            return dt;
        }
        public DataTable GetAllEmps()
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_GetAllEmps");
            return dt;
        }
        public DataTable GetAllEmpById(Employee emp)
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_GetAllEmpById", new SqlParameter("@EmployeeId", emp.EmployeeID));
            return dt;
        }
        public DataTable UpdateEmployeeById(Employee emp)
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_UploadEmployeeById",
                 new SqlParameter("@EmployeeId", emp.EmployeeID),
                 new SqlParameter("@LastName", emp.LastName),
                 new SqlParameter("@FirstName", emp.FirstName),
                 new SqlParameter("@Title", emp.Title),
                 new SqlParameter("@Birthdate", emp.BirthDate));
            return dt;
        }
        public DataTable DeleteEmployeeById(Employee emp)
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_DeleteEmployeeById",
                 new SqlParameter("@EmployeeId", emp.EmployeeID));
            return dt;
        }
    }
}

In Controller Class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;
using SampleMvc.DA;
using SampleMvc.Models;
using System.Web.Script.Serialization;

namespace SampleMvc.Controllers
{
    public class EmpController : Controller
    {
        public ActionResult AddEmployee()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddEmployee(Employee emp)
        {
            EmployeeDA employeeDA = new EmployeeDA();
            employeeDA.AddEmployee(emp);
            return View();
        }
        public ActionResult GetAllEmployees()
        {
            DataTable dt = new DataTable();
            EmployeeDA employeeDA = new EmployeeDA();
            dt = employeeDA.GetAllEmps();
            String emp = ConvertDataTableTojSonString(dt);
            return Json(emp);
        }

        public ActionResult GetEmployeeById(Employee emp)
        {
            DataTable dt = new DataTable();
            EmployeeDA employeeDA = new EmployeeDA();
            dt = employeeDA.GetAllEmpById(emp);
            String _emp = ConvertDataTableTojSonString(dt);
            return Json(_emp);
        }

        public ActionResult UpdateEmployeeById()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UpdateEmployeeById(Employee emp)
        {
            DataTable dt = new DataTable();
            EmployeeDA employeeDA = new EmployeeDA();
            dt = employeeDA.UpdateEmployeeById(emp);
            String _emp = ConvertDataTableTojSonString(dt);
            return Json(_emp);
        }

        public ActionResult DeleteEmployeeById()
        {
            return View();
        }
        [HttpPost]
        public ActionResult DeleteEmployeeById(Employee emp)
        {
            DataTable dt = new DataTable();
            EmployeeDA employeeDA = new EmployeeDA();
            dt = employeeDA.DeleteEmployeeById(emp);
            String _emp = ConvertDataTableTojSonString(dt);
            return Json(_emp);
        }

        public String ConvertDataTableTojSonString(DataTable dataTable)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer =
                   new System.Web.Script.Serialization.JavaScriptSerializer();

            List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();

            Dictionary<String, Object> row;

            foreach (DataRow dr in dataTable.Rows)
            {
                row = new Dictionary<String, Object>();
                foreach (DataColumn col in dataTable.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                tableRows.Add(row);
            }
            return serializer.Serialize(tableRows);
        }
    }
}


In View AddEmployee : 

@{
    Layout = null;
}

<script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<link href="~/Contents/CSS/jquery-ui.css" rel="stylesheet" />

<script type="text/javascript">
    $(document).ready(function () {
        var dialogDiv = $('#dialog');
        //Create dialog
        $("#dialog .ui-dialog-titlebar").css("background-color", "red");
        dialogDiv.dialog({
            autoOpen: false,
            modal: true,
            title: 'Add Employee',
            buttons: {
                'Create': CreateEmployee,
                'Cancel': function () {
                    dialogDiv.dialog('close');
                    clearInputFields();
                }
            }
        });
        // Functon to create employee    
        function CreateEmployee() {
            var employee = {};
            employee.LastName = $('#txtLastName').val();
            employee.FirstName = $('#txtFirstName').val();
            employee.Title = $('#txtTitle').val();
            employee.BirthDate = $('#txtDob').val();

            $.ajax({
                url: 'Emp/AddEmployee',
                method: 'post',
                data: '{emp: ' + JSON.stringify(employee) + '}',
                contentType: "application/json; charset=utf-8",
                success: function () {
                    getAllEmployees();
                    dialogDiv.dialog('close');
                    clearInputFields();
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
        // Functon to update employee by employee id
        function UpdateEmployee() {
            var employee = {};
            employee.EmployeeID = $('#txtEmpId').val();
            employee.LastName = $('#txtLastName').val();
            employee.FirstName = $('#txtFirstName').val();
            employee.Title = $('#txtTitle').val();
            employee.BirthDate = $('#txtDob').val();

            $.ajax({
                url: 'Emp/UpdateEmployeeById',
                method: 'post',
                data: '{emp: ' + JSON.stringify(employee) + '}',
                contentType: "application/json; charset=utf-8",
                success: function () {
                    getAllEmployees();
                    dialogDiv.dialog('close');
                    clearInputFields();
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
        // Functon to get all employees
        function getAllEmployees() {
            var tboby = $('#tblEmployee tbody');
            tboby.empty();

            $.ajax({
                url: 'Emp/GetAllEmployees',
                dataType: "json",
                method: 'post',
                success: function (data) {
                    var employeeTable = $('#tblEmployee tbody');
                    employeeTable.empty();
                    $(JSON.parse(data)).each(function (index, emp) {
                        employeeTable.append('<tr><td>'
                        + emp.EmployeeID + '</td><td>'
                        + emp.LastName + '</td><td>'
                        + emp.FirstName + '</td><td>'
                        + emp.Title + '</td><td>'
                        + emp.BirthDate + '</td><td>'
                        + '<input class="btnEdit" type="button" value="Edit" Id="' + emp.EmployeeID + '" /> '
                        + '<input class="btnDelete" type="button" value="Delete" Id="btndelete_' + emp.EmployeeID + '" /> '
                        + '<input class="btnView" type="button" value="View"/> </td></tr>');

                        // Find button click by dynamic Id to retrive data to update.
                        $("#" + emp.EmployeeID).click(function () {
                            //alert($(this).attr("Id"));
                            getEmployeeById($(this).attr("Id"));
                        });
                        // Find button click by dynamic Id to delete data.
                        $("#btndelete_" + emp.EmployeeID).click(function () {
                            //alert($(this).attr("Id"));
                            deleteEmployeeById($(this).attr("Id").replace("btndelete_", ""));
                        });

                    });
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
        // Functon to clear all inputs
        function clearInputFields() {
            $('#dialog input[type="text"]').val('');
        }
        // Functon to get employee details by employee id
        function getEmployeeById(eId) {
            var employee = {};
            employee.EmployeeId = eId;

            $.ajax({
                url: 'Emp/GetEmployeeById',
                method: 'post',
                data: '{emp: ' + JSON.stringify(employee) + '}',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $(JSON.parse(data)).each(function (index, emp) {
                        $('#txtEmpId').val(emp.EmployeeID);
                        $('#txtLastName').val(emp.LastName);
                        $('#txtFirstName').val(emp.FirstName);
                        $('#txtTitle').val(emp.Title);
                        $('#txtDob').val(emp.BirthDate);
                    });
                    // Creating dialog to edit employee
                    dialogDiv.dialog({
                        autoOpen: false,
                        modal: true,
                        title: 'Edit Employee',
                        buttons: {
                            'Update': UpdateEmployee,
                            'Cancel': function () {
                                dialogDiv.dialog('close');
                                clearInputFields();
                            }
                        }
                    });
                    dialogDiv.dialog('open');
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
        // Function to delete employee by Id.
        function deleteEmployeeById(eId) {
            var employee = {};
            employee.EmployeeId = eId;

            if (confirm('Are you sure you want to continue?')) {
                $.ajax({
                    url: 'Emp/DeleteEmployeeById',
                    method: 'post',
                    data: '{emp: ' + JSON.stringify(employee) + '}',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        getAllEmployees();
                        dialogDiv.dialog('close');
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            }  
        }
        // Functon to create dialog to add employee on Add Employee button click.
        $('#btnAddEmployee').click(function () {
            //Creating dialog to add employee
            dialogDiv.dialog({
                autoOpen: false,
                modal: true,
                title: 'Add Employee',
                buttons: {
                    'Create': CreateEmployee,
                    'Cancel': function () {
                        dialogDiv.dialog('close');
                        clearInputFields();
                    }
                }
            });
            dialogDiv.dialog("open");
        });
        // Calling function to get all employees on page load.
        getAllEmployees();
    });
</script>

<table id="tblEmployee" border="1" style="border-collapse: collapse">
    <thead>
        <tr>
            <th>Employee ID</th>
            <th>Last Name</th>
            <th>First Name</th>
            <th>Title</th>
            <th>DOB</th>
            <th>Action</th>
            @* style="display:none;"*@
        </tr>
    </thead>
    <tbody></tbody>
</table>
<br />
<br />
<input type="button" value="Add Employee" id="btnAddEmployee" />
@*Just need to set id of div to dialog in order to use jquery modal.*@
<div id="dialog">
    <div class="container">
    <input type="hidden" id="txtEmpId" />
    Last Name<br />
    <input type="text" id="txtLastName" /><br />
    First Name<br />
    <input type="text" id="txtFirstName" /><br />
    Title
    <br />
    <input type="text" id="txtTitle" /><br />
    DOB<br />
    <input type="text" id="txtDob" />
    <br />
    </div>
    <div class="msgConfirm" style="display:none;">
        Do you want to delete this employee.?
    </div>
</div>


Image uploading and saving its path is database.



 protected void btn_submit_Click(object sender, EventArgs e)
    {
        bool flag = true;
        image.CenterImagePath = "";
        image.CenterImageID = Convert.ToInt32(lbl_CenterImageID.Text);

        if (FileUpload1.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".png" || fileExt == ".jpeg")
            {
                image.CenterImagePath = @"~/CenterImage1/" + image.CenterImageID + Class_Additionalresources.Getextention(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath(image.CenterImagePath));
                flag = true;
            }
            else
            {

                flag = false;
                lblMsg.Text = "Only jpg,gif and png file are allowed";
                div_message.Visible = true;
                img_right.Visible = false;
                img_error.Visible = true;
                lblMsg.ForeColor = System.Drawing.Color.Red;

            }

        }

        if (flag)
        {

            image.NavigateUrl = txt_url.Text;
            image.Status = chk_Status.Checked;
            image.UpdateCenterImage1ByID();
            if (image.OperationStatus)
            {
                lblMsg.Text = "Image updated Successfully";
                div_message.Visible = true;
                img_right.Visible = true;
                img_error.Visible = false;
                lblMsg.ForeColor = System.Drawing.Color.Green;
                Div_Image.Visible = true;
                div_update.Visible = false;
                bindgrid();
            }
            else
            {
                lblMsg.Text = image.ErrorMessage;
                div_message.Visible = true;
                img_right.Visible = false;
                img_error.Visible = true;
                lblMsg.ForeColor = System.Drawing.Color.Red;

            }


        }

    }

=============================================================================


    public static string Getextention(string Filename)
    {
        string _extention;
        int index;
        index = Filename.IndexOf('.');
        _extention = Filename.Substring(index);
        return _extention;

    }
=============================================================================

  public void UpdateCenterImage1ByID()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SP_UpdateCenterImage1ByID";
            cmd.Parameters.AddWithValue("@CenterImageID", CenterImageID);
            cmd.Parameters.AddWithValue("@CenterImagePath", CenterImagePath);
            cmd.Parameters.AddWithValue("@NavigateUrl", NavigateUrl);
            cmd.Parameters.AddWithValue("@Status", Status);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            CenterImageID = Convert.ToInt32(cmd.ExecuteScalar());
            if (CenterImageID == -1)
            {
                OperationStatus = false;
                ErrorMessage = "Error : Image does not Exist.";
            }
            else
            {
                OperationStatus = true;
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

=============================================================================

CREATE PROCEDURE [dbo].[SP_UpdateCenterImage1ByID]                
@CenterImageID int,                
@CenterImagePath nvarchar(200),     
@NavigateUrl nvarchar(max),      
@Status bit                
as                
begin         
  if(@CenterImagePath = '')        
  update tbl_CenterImage1 set NavigateUrl=@NavigateUrl,Status = @Status               
  where CenterImageID = @CenterImageID       
  else      
  begin      
     update tbl_CenterImage1 set CenterImagePath = @CenterImagePath,NavigateUrl=@NavigateUrl,Status = @Status               
  where CenterImageID = @CenterImageID         
  end             
end 

=============================================================================