Monday 8 August 2016

Payment gateway with authorize .net

  [HttpPost]
        public ActionResult PaymentCreditCard(PaymentGatewayModel model)
        {
         

            sbLog = new StringBuilder();
            sbLog.Append("Start of PaymentCreditCard() Post method of PaymentGateway Controller");
            model.LstMonth = objCommonBLL.GetMonthList();
            model.LstYear = objCommonBLL.GetYearList();


            try
            {
                // By default, this sample code is designed to post to our test server for
                // developer accounts: https://test.authorize.net/gateway/transact.dll
                // for real accounts (even in test mode), please make sure that you are
                // posting to: https://secure.authorize.net/gateway/transact.dll

                String post_url = "https://test.authorize.net/gateway/transact.dll";

                Dictionary<string, string> post_values = new Dictionary<string, string>();
                //the API Login ID and Transaction Key must be replaced with valid values
                if (Session["EmailID"] != null)
                {
                    objMyAccount = objUserBLL.GetAccountDetailsByEmail(Session["EmailID"].ToString().Trim());
                }
                else
                {
                    TempData["UserMessage"] = "Please Enter Valid Email ID which you entered at registration Time";
                    RedirectToAction("Login", "UserAccount");
                }


                post_values.Add("x_login", "7pf2RTt5W69t");
                post_values.Add("x_tran_key", "35nbVPh6Z79R26ab");


                post_values.Add("x_delim_data", "TRUE");
                post_values.Add("x_delim_char", "|");
                post_values.Add("x_relay_response", "FALSE");

                post_values.Add("x_type", "AUTH_CAPTURE");
                post_values.Add("x_method", "CC");

                //Credit Card Number
                //post_values.Add("x_card_num", "4007000000027");
                post_values.Add("x_card_num", model.CreditCardNo.ToString().Trim());

                //Expiration Date Card Number
                //post_values.Add("x_exp_date", "0418");
                post_values.Add("x_exp_date", model.ExpiryMonth.ToString() + model.ExpiryYear.ToString());

                //Order Amount

                if (Session["SubscrAmount"] != null)
                {
                    post_values.Add("x_amount", Session["SubscrAmount"].ToString().Trim());
                }
                else
                {
                    if (objMyAccount.IsWholesaler)
                    {
                        post_values.Add("x_amount", ConfigurationManager.AppSettings["PremiumPlan"].ToString());
                    }
                    else
                    {
                        post_values.Add("x_amount", ConfigurationManager.AppSettings["BasicPlan"].ToString());
                    }

                }

                post_values.Add("x_description", "Sample Transaction");
                post_values.Add("x_first_name", objMyAccount.FirstName.Trim());
                post_values.Add("x_last_name", objMyAccount.LastName.Trim());
                post_values.Add("x_address", objMyAccount.Address);
                post_values.Add("x_zip", objMyAccount.ZipCode);
                post_values.Add("x_cust_id", objMyAccount.UserId.ToString());

                String post_string = "";

                foreach (KeyValuePair<string, string> post_value in post_values)
                {
                    post_string += post_value.Key + "=" +
                    HttpUtility.UrlEncode(post_value.Value) + "&";
                }
                post_string = post_string.TrimEnd('&');


                // create an HttpWebRequest object to communicate with Authorize.net
                HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
                objRequest.Method = "POST";
                objRequest.ContentLength = post_string.Length;
                objRequest.ContentType = "application/x-www-form-urlencoded";

                // post data is sent as a stream
                StreamWriter myWriter = null;
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(post_string);
                myWriter.Close();

                // returned values are returned as a stream, then read into a string
                String post_response;
                HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
                using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
                {
                    post_response = responseStream.ReadToEnd();
                }
                // the response string is broken into an array
                // The split character specified here must match the delimiting character specified above
                Array response_array = post_response.Split('|');
                if (response_array.GetValue(0).ToString() == "1")
                {

                    model.ResponseCode = Convert.ToInt32(response_array.GetValue(0));
                    model.ResponseSubCode = Convert.ToInt32(response_array.GetValue(1));
                    model.ResponseReasonCode = Convert.ToInt32(response_array.GetValue(2));
                    model.ResponseResonText = response_array.GetValue(3).ToString();
                    model.AuthorizationCode = response_array.GetValue(4).ToString();
                    model.AVSResponse = response_array.GetValue(6).ToString();
                    model.PaymentTransactionId = response_array.GetValue(7).ToString();
                    model.InvoiceNumber = "INV" + objMyAccount.UserId;
                    model.Description = response_array.GetValue(8).ToString();
                    model.Amount = Convert.ToDecimal(response_array.GetValue(9));
                    model.PaymentMethod = response_array.GetValue(10).ToString();
                    model.TransactionType = response_array.GetValue(11).ToString();
                    model.CustomerID = "CUST" + objMyAccount.UserId;
                    model.FirstName = response_array.GetValue(13).ToString();
                    model.LastName = response_array.GetValue(14).ToString();
                    model.Company = response_array.GetValue(15).ToString();
                    model.Address = response_array.GetValue(16).ToString();
                    model.City = response_array.GetValue(17).ToString();
                    model.State = response_array.GetValue(18).ToString();
                    model.PostalCode = response_array.GetValue(19).ToString();
                    model.UserID = objMyAccount.UserId;
                    Session["UserId"] = objMyAccount.UserId;
                    Session["UserName"] = objMyAccount.UserName;
                    Session["IsWholeSaler"] = objMyAccount.IsWholesaler;

                    bool result = objUserBLL.InsertPaymentGateway(model);
                    if (result == true)
                    {
                        return RedirectToAction("Dashboard", "Home");
                    }
                    else
                    {
                        Session["UserId"] = null;
                        TempData["Error"] = response_array.GetValue(3).ToString();
                        model.LstMonth = objCommonBLL.GetMonthList();
                        model.LstYear = objCommonBLL.GetYearList();
                        return View(model);
                    }
                }
                else
                {
                    Session["UserId"] = null;
                    TempData["Error"] = response_array.GetValue(3).ToString();
                    model.LstMonth = objCommonBLL.GetMonthList();
                    model.LstYear = objCommonBLL.GetYearList();
                    return View(model);
                }
             

            }
            catch (Exception ex)
            {
                sbLog.Append("End of PaymentCreditCard() Post method of PaymentGateway Controller");
                sbLog.AppendLine();
                sbLog.Append("Error: " + ex);
                ErrorLog.GetDefault(null).Log(new Error(new InvalidOperationException("Log:" + sbLog.ToString())));

                return View("Error", new HandleErrorInfo(ex, "Payment through Credit Card info", "PaymentCreditCard"));

            }

         
        }

JS creation

var party

function ValidateEmail() {
    debugger;
    var userEmail = $('#Email').val();
    var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
    if (userEmail!="" && !re.test(userEmail)) {
        $('#spnEmail').show();
        return false;
    }
    else {
        $('#spnEmail').hide();
        return true;
    }
};
///To fill customers in customer texbox as autocomplete
var $j = jQuery.noConflict();

$(document).ready(function () {

    $('#example1').DataTable({

        "aoColumnDefs": [{
            "bSortable": false,
            "aTargets": [0]
        }],

        "order": [[1, "desc"]],
        "scrollX": true,
        dom: 'Bfrtip',
        buttons: [
               {
                   extend: 'collection',
                   text: '<i class="fa fa-upload"></i>&nbsp;Export',
                   buttons: [
                         {
                             extend: 'excel',
                             text: '<i class="fa fa-file-excel-o"></i>&nbsp;Export to Excel',
                             titleAttr: 'Excel',
                             exportOptions: {
                                 columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
                             }
                         },
                             {
                                 extend: 'csv',
                                 text: '<i class="fa fa-file-text-o"></i>&nbsp;Export to CSV',
                                 titleAttr: 'CSV',
                                 exportOptions: {
                                     columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
                                 }
                             }

                   ]
               },

               {
                   extend: 'print',
                   text: '<i class="fa fa-print"></i>&nbsp;Print',
                   titleAttr: 'Print',
                   exportOptions: {
                       columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
                   }
               }
        ],
        "bSort": true,
    });


    //To Adjust the Export Buttons

    $(".dt-buttons").insertAfter("#hdExport");

    //autofill on sales entry form
    $j("#custmer").autocomplete({
        source: function (request, response) {
            jQuery.ajax({
                url: RootUrl + '/Sales/AutoCompleteCustomers',
                type: "POST",
                dataType: "json",
                data: { term: request.term },
                success: function (data) {
                    response(data);
                }
            })
        },
        messages: {
            noResults: "", results: ""
        }
    });

    var discount = $('#Discount').val();
    var subTotal = $('#SubTotal').val();
    var totalAmount = $('#TotalAmt').val();
    var taxRate = $('#Tax').val();
    var shipping = $('#Shipping').val();

    if (discount == 0) { $('#Discount').val(''); }
    if (subTotal == 0) { $('#SubTotal').val(''); }
    if (totalAmount == 0) { $('#TotalAmt').val(''); }
    if (taxRate == 0) { $('#Tax').val(''); }
    if (shipping == 0) { $('#Shipping').val(''); }

    var id = $('#hdnSalesId').val();
    if (id > 0) {
        SalesDetailsData(id);
    }
    debugger;
    //For Default Date overriden prevention on Edit
    var date = new Date();
    var newFromDate = "";
    if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
        newFromDate = date.toLocaleDateString("en-US");
    }

    else {
        newFromDate = dateFormat(date, "mm-dd-yyyy");
    }


    var salesId = $('#hdnSalesId').val();
    $("#datepicker").datepicker({
        autoclose: true,
        useCurrent: false,
        todayHighlight: true,
        Default: true,
        defaultDate: new Date(newFromDate),
        endDate: new Date(newFromDate)
    });

    if (salesId <= 0) {

        $("#datepicker").datepicker("setDate", new Date(newFromDate));
    };

});

//To validate sales entry form
function SalesValidate() {
    var Cust = $('#custmer').val();
    var x = true;
    if (Cust == '') {
        $('#spnCustomer').show();
        x = false;
    }
    else {
        $('#spnCustomer').hide();

    }

    if (party == "Party") {
        var ddlParty = $('#party').val();
        if (ddlParty == '') {
            $('#spnParty').show();
            x = false;
        }
        else {
            $('#spnParty').hide();

        }
    }

    var pMethod = $('#pMethod').val();
    if (pMethod == '') {
        $('#spnPMethod').show();
        x = false;
    }
    else {
        $('#spnPMethod').hide();
    }
    var salesType = $('#salesType').val();
    if (salesType == '') {
        $('#spnSalesType').show();
        x = false;
    }
    else {
        $('#spnSalesType').hide();
    }

    $('#tblSales > #tBodyH1 tr').each(function () {
        var row = $(this);
        var pId = row.find('td').eq(1).find('select').val();
        var desc = row.find('td').eq(2).find('input').val();
        var qty = row.find('td').eq(3).find('input').val();

        if (pId == "") {
            row.find('td').eq(1).find('span').show();
            x = false;
        }
        else {
            row.find('td').eq(1).find('span').hide();
        }
        if (qty == "") {
            row.find('td').eq(3).find('span').show();
            x = false;
        }
        else {
            row.find('td').eq(3).find('span').hide();
        }

    });

    if (x == false) {
        return false;
    }
    else {
        return true;
    }
};

//to get Expense Detail Data for id provided
function SalesDetails(salesId) {
    window.location.href = RootUrl + '/Sales/SalesEntry/' + salesId;
};
function SalesDetailsData(id) {
    var editid = id;
    $.ajax({
        url: RootUrl + '/Sales/EditSalesEntry',
        type: "POST",
        dataType: "JSON",
        data: { salesId: editid },
        success: function (data) {
            party = data.SalesTypeId;
            if (party == "3") {
                $("#divParty").show();
                $("#PartyID").val(data.PartyID);
            }
            else { $("#divParty").hide(); }

            $('#pMethod').val(data.PaymentMethodId)

            $(data.ListSalesDetailData).each(function (index, item) {
                var row = $('#tblSales #tBodyH1 tr:first').html();
                var rowData = '<tr>' + row + '</tr>'
                $('#tblSales > #tBodyH1:last').append(rowData);

            });
            $('#tblSales #tBodyH1 tr:last').remove();
            $('#tblSales > #tBodyH1 tr').each(function (index, itemr) {
                var listdata = data.ListSalesDetailData;
                var row = $(this);
                var DropDown = row.find('td').eq(1).find('select');
                var pId = listdata[index].ProductID;
                DropDown.val(pId);

                row.find('td').eq(0).find('input').val(listdata[index].Size);
                row.find('td').eq(2).find('input').val(listdata[index].Description);
                row.find('td').eq(3).find('input').val(listdata[index].Quantity.toFixed(2));
                row.find('td').eq(4).find('input').val(listdata[index].Amount.toFixed(2));
                row.find('td').eq(5).find('input').val(listdata[index].ExtendedAmount.toFixed(2));
            });

            $("#TaxRate").val(data.TaxRate.toFixed(2));
            $("#Tax").val(data.Tax.toFixed(2));
            $("#Shipping").val(data.Shipping.toFixed(2));
            $("#Discount").val(data.Discount.toFixed(2));
            $("#SubTotal").val(data.SubTotal.toFixed(2));
            $("#TotalAmt").val(data.TotalAmount.toFixed(2));
            var taxableAmount = (data.SubTotal - data.Discount) + data.Shipping;
            $("#txtTaxableAmt").val(parseFloat(taxableAmount).toFixed(2));
        },

        error: function (err) {

            alert(err);
        }
    });
};
//To calculate discount and tax
function CalculateTaxDiscount() {
    var subTotal = $("#SubTotal").val();
    var discount = $("#Discount").val();
    var tax = $("#TaxRate").val();
    var shipping = $("#Shipping").val();

    var totalAmount = subTotal;
    if (discount != "") {
        totalAmount = parseFloat(totalAmount) - parseFloat(discount)
    }
    if (shipping != "") {
        totalAmount = parseFloat(totalAmount) + parseFloat(shipping)
    }
    if (isNaN(totalAmount)) {
        $("#txtTaxableAmt").val('0.00');
    }
    else {
        $("#txtTaxableAmt").val(parseFloat(totalAmount).toFixed(2));
    }

    var totalTax = 0;
    if (tax != "") {
        totalTax = (parseFloat(totalAmount)) * tax / 100;

    }
    var amountWithTax = parseFloat(totalAmount) + parseFloat(totalTax);

    if (isNaN(totalTax)) {
        $("#Tax").val('0.00');
    }
    else {
        $("#Tax").val(parseFloat(totalTax).toFixed(2))
    }

    if (isNaN(amountWithTax)) {
        $("#TotalAmt").val('0.00');
    }
    else {
        $("#TotalAmt").val(parseFloat(amountWithTax).toFixed(2));
    }
};
//clicked of product dropdown and fill data
function calculateSum(data) {
    var sum = 0;
    //iterate through each textboxes and add the values
    $(".txt").each(function () {

        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            sum += parseFloat(this.value);
        }
        if (isNaN(sum)) {
            $("#SubTotal").val('0.00');
        }
        else {
            $("#SubTotal").val(sum.toFixed(2));
        }
    });
};
var pQty;
var isRow = 1;
$(document).on("change", "#ddlProduct", function () {
    var pid = $(this).val();
    var txtsize = $(this).closest('tr').find('td').eq(0).find('input');
    var txtdesc = $(this).closest('tr').find('td').eq(2).find('input');
    var txtqty = $(this).closest('tr').find('td').eq(3).find('input');
    var txtamt = $(this).closest('tr').find('td').eq(4).find('input');
    var txtextamnt = $(this).closest('tr').find('td').eq(5).find('input');

    var lstPid = [];
    $('#tblSales > #tBodyH1 tr').each(function () {
        var pId = $(this).closest('tr').find('td').eq(1).find('select').val()
        lstPid.push(pId);
    });
    var hasDups = !lstPid.every(function (v, i) {
        return lstPid.indexOf(v) == i;
    });
    if (hasDups) {
        $("#myAlert").modal({ show: true, backdrop: 'static', keyboard: false });
        $("#myAlert .modal-header").addClass("delete");
        $("#myAlert div#AlertMsg").empty();
        $("#myAlert div#AlertMsg").append('This product alredy selected');
        //$('#salesModal1').modal('show');
        $(this).prop('selectedIndex', 0);
    }
    else {
        if (pid == 0) {
            txtsize.val('');
            txtqty.val('');
            txtamt.val('');
            $("#Discount").val('0.00');
            $("#SubTotal").val('0.00');
            $("#TaxRate").val('0.00');
            $("#Shipping").val('0.00');
            $("#Tax").val('0.00');
        }
        else {
            GetItemDetails(pid, txtqty, txtamt, txtextamnt, txtsize, txtdesc);
            calculateSum(txtextamnt);
            //CalculateTaxDiscount();
        }
    }
    //SalesValidate();
});

$(document).on("change", "#salesType", function () {
    party = $('#salesType option:selected').text();
    if (party == "Party") {

        $("#divParty").show();
    }
    else { $("#divParty").hide(); }
});

$(document).on("keyup", "#Quanity", function (e) {
    var row = $(this);
    var amount = $(this).closest('tr').find('td').eq(4).find('input').val();
    var quantity = row.val();
    var extendAmt = $(this).closest('tr').find('td').eq(5).find('input');

    var qty = $(this).closest('tr').find('td').eq(3).find('input');
    var result = ValidateQuantity(qty);

    if (result == true) {
        if (amount != '') {
            sumCall(amount, quantity, extendAmt);
        }
    }
    else {
        sumCall(amount, pQty, extendAmt);
    }
    CalculateTaxDiscount();
});

$(document).on("blur", "#Quanity", function (e) {
    var row = $(this);
    var quantity = row.val();
    if (quantity == "") {
        row.val('');
    }
    else {
        row.val(parseFloat(quantity).toFixed(2));
    }
    AddNewRow();
    calculateSum();
});

$(document).on("keyup", "#Discount", function () {
    var discount = parseFloat($('#Discount').val()).toFixed(2);
    var total = $('#SubTotal').val();

    if (parseFloat(discount) > parseFloat(total)) {

        $("#myAlert").modal({ show: true, backdrop: 'static', keyboard: false });
        $("#myAlert .modal-header").addClass("delete");
        $("#myAlert div#AlertMsg").empty();
        $("#myAlert div#AlertMsg").append('Discount should not greater than Subtotal');
        $('#Discount').val('');
    }

    CalculateTaxDiscount();
});
$(document).on("blur", "#Discount", function () {
    var discount = parseFloat($('#Discount').val()).toFixed(2);
    if (isNaN(discount)) {
        $("#Discount").val('0.00');
    }
    else {
        $("#Discount").val(parseFloat(discount).toFixed(2))
    }
});


$(document).on("keyup", "#TaxRate", function () {
    CalculateTaxDiscount();
});
$(document).on("keyup", "#Shipping", function (e) {
    CalculateTaxDiscount();
});
$(document).on("blur", "#Shipping", function (e) {
    var shipping = parseFloat($('#Shipping').val()).toFixed(2);

    if (isNaN(shipping)) {
        $("#Shipping").val('0.00');
    }
    else {
        $('#Shipping').val(parseFloat(shipping).toFixed(2));
    }

});
$(document).on("blur", "#TaxRate", function () {
    var taxrate = parseFloat($('#TaxRate').val()).toFixed(2);
    $('#TaxRate').val(parseFloat(taxrate).toFixed(2));
});

$(document).on("click", "#btnSaveClose", function () {
    RemoveRow();
    if (SalesValidate()) {
        var btnValue = $(this).val();
        CreateSalesModel(btnValue)
    }
});

$(document).on("click", "#btnSaveAndNew", function () {
    RemoveRow();
    if (SalesValidate()) {
        var btnValue = $(this).val();
        CreateSalesModel(btnValue)
    }
});

$(document).on("click", "#btnUpdate", function () {
    RemoveRow();
    if (SalesValidate()) {
        var btnValue = $(this).val();
        CreateSalesModel(btnValue)
    }
});
//create sales model and sales detail model
function CreateSalesModel(btnValue) {
    debugger;
    var lstSales = [];

    $('#tblSales > #tBodyH1 tr').each(function () {
        var row = $(this);

        var pId = row.find('td').eq(1).find('select').val();
        var desc = row.find('td').eq(2).find('input').val();
        var size = row.find('td').eq(0).find('input').val();
        var qty = row.find('td').eq(3).find('input').val();
        var amt = row.find('td').eq(4).find('input').val();
        var extAmt = row.find('td').eq(5).find('input').val();

        if (pId > 0 && qty > 0 && amt > 0 && extAmt > 0) {

            var SalesDetailModel =
                                {
                                    "ProductId": pId,
                                    "Description": desc,
                                    "Size": size,
                                    "Quantity": qty,
                                    "Amount": amt,
                                    "ExtendedAmount": extAmt
                                };
            lstSales.push(SalesDetailModel);
        }
    });

    var SalesModel =
                          {
                              "SalesDate": $("#date").val(),
                              "SalesID": $("#salesId").val(),
                              "Customer": $("#custmer").val(),
                              "Email": $("#Email").val(),
                              "PaymentMethodId": $("#pMethod").val(),
                              "SalesTypeID": $("#salesType").val(),
                              "PartyID": $("#party").val(),
                              "SubTotal": $("#SubTotal").val(),
                              "Discount": $("#Discount").val(),
                              "Shipping": $("#Shipping").val(),
                              "TaxRate": $("#TaxRate").val(),
                              "Tax": $("#Tax").val(),
                              "TotalAmount": $("#TotalAmt").val() - $("#Tax").val()
                          };

    InsertSalesDetails(SalesModel, lstSales, btnValue);

};

//to calculate extended amount
function sumCall(amount, quantity, extendAmt) {

    var result = parseFloat(amount) * parseFloat(quantity);
    if (isNaN(result)) {
        extendAmt.val('0.00');
    }
    else {
        //extendAmt.val(result);
        extendAmt.val(parseFloat(result).toFixed(2));
    }
    calculateSum();
};
//to add new row in the sales table
function AddNewRow() {
    var row = $('#tblSales #tBodyH1 tr:first').html();
    var rowData = '<tr>' + row + '</tr>'
    $('#tblSales > #tBodyH1 tr:last').each(function () {
        var pId = $(this).closest('tr').find('td').eq(1).find('select').val()
        if (pId > 0) {
            $('#tblSales > #tBodyH1:last').append(rowData);
        }
    });
};

$(document).on("click", "#btnDeleteRow", function () {

    //$(this).closest('tr').remove()
    //$(this).parent().parent().remove()

    if ($("#tblSales >#tBodyH1 tr").length > 1) {

        $(this).parent().parent("tr").remove();
        calculateSum();
        CalculateTaxDiscount();
    }
});
//validate product quantity i.e. user can not enter more than product quantity.
function ValidateQuantity(qty) {
    var result = true;
    if (qty.val() > pQty) {

        $("#myAlert").modal({ show: true, backdrop: 'static', keyboard: false });
        $("#myAlert .modal-header").addClass("delete");
        $("#myAlert div#AlertMsg").empty();
        $("#myAlert div#AlertMsg").append('Quantity must be less than equal to Inventory');

        isRow = 0;
        qty.val(pQty);
        result = false;
    }
    else { result = true; }
    return result;
};
//to get product details
function GetItemDetails(pid, txtqty, txtamt, txtextamnt, txtsize, txtdesc) {
    $.ajax({
        url: RootUrl + '/Sales/GetProductDetails',
        type: "GET",
        dataType: "JSON",
        data: { ProductId: pid },
        success: function (data) {
            if ($("#tblSales >#tBodyH1 tr").length == 1) {

                $("#SubTotal").val(data.ExtendedAmount);
                $("#TotalAmt").val(data.ExtendedAmount);
            }

            if (data.Quantity > 0) {
                txtqty.val(data.Quantity.toFixed(2));
                pQty = data.Quantity;
                txtamt.val(data.Amount.toFixed(2));
                txtextamnt.val(data.ExtendedAmount.toFixed(2));
                txtsize.val(data.Size);

                txtqty.removeAttr("disabled");
                txtdesc.removeAttr("disabled");

                calculateSum(txtextamnt);
                CalculateTaxDiscount();

            }
            else {
                txtdesc.val('');
                txtqty.val('');
                txtamt.val('');
                txtextamnt.val('');
                txtqty.attr("disabled", "disabled");
                txtdesc.attr("disabled", "disabled");
                $('#btnAddInventory').val(pid);
                $('#salesModal3').modal('show');
            }
        }
    });
};

//insert sales detail data
function InsertSalesDetails(salesmodel, salesdata, btnValue) {
    $.ajax({
        url: RootUrl + '/Sales/SalesEntry',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ SalesModel: salesmodel, SalesData: salesdata, SubmitButton: btnValue }),
        type: 'POST',
        success: function (salesId) {
            if (salesId > 0) {
                if (btnValue == "Save and New") {
                    window.location.href = RootUrl + "/Sales/SalesEntry";
                }
                else if (btnValue == "Update") {
                    window.location.href = RootUrl + "/Sales/SalesSummary";
                }
                else if (btnValue == "Save and Close") {

                    window.location.href = RootUrl + '/Sales/SalesSummary';

                }
                if (btnValue == "Update") {
                    $(".alert-success").removeAttr('style');
                    $("label[for='Success']").text('Sales Updated Successfully..');
                }
                else if (btnValue == "Save and New" || btnValue == "Save and Close") {
                    $(".alert-success").removeAttr('style');
                    $("label[for='Success']").text('Sales Submitted Successfully');
                }
            }
        },
        error: function (err) {

            $("#myAlert").modal({ show: true, backdrop: 'static', keyboard: false });
            $("#myAlert .modal-header").addClass("delete");
            $("#myAlert div#AlertMsg").empty();
            $("#myAlert div#AlertMsg").append(err);
        }
    });
};
//clear values
function ClearValues() {
    $("#custmer").val('');
    $('#pMethod').prop('selectedIndex', 0);
    $('#salesType').prop('selectedIndex', 0);
    $('#ddlProduct').prop('selectedIndex', 0);
    $('#party').prop('selectedIndex', 0);
    $("#Discount").val('0.00');
    $("#SubTotal").val('0.00');
    $("#Shipping").val('0.00');
    $("#Tax").val('0.00');
    $("#TotalAmt").val('0.00');

    $('#tblSales >#tBodyH1 tr:gt(0)').remove();

    $('#Desc').val('');
    $('#Quanity').val('');
    $('#Amount').val('');
    $('#ExtendedAmount').val('');

}

//To remove blank row
function RemoveRow() {
    if ($("#tblSales >#tBodyH1 tr").length > 1) {
        $('#tblSales > #tBodyH1 tr:last').each(function () {
            var pId = $(this).closest('tr').find('td').eq(1).find('select').val();

            if (pId == null || pId == "" || pId == 'undefined' || pId < 0) {
                $(this).remove();
            }
        });
    }

}

////////////////Start of Sales Summary////////////////////////////////
function myfunction(sId) {
    if (sId > 0) {
        GetSalesDetail(sId);
    }
};

function GetSalesDetail(salesId) {
    $.ajax({
        url: RootUrl + '/Sales/SalesDetail',
        type: "GET",
        dataType: "JSON",
        data: { salesId: salesId },
        success: function (data) {
            if (result != '') {

            }

        }
    });
};

$(document).on("click", "#checkAllItems", function () {
    $(".checkBox").prop('checked',
        $(this).prop('checked'));
});
$(document).on("click", "#btnDeleteReturn", function () {
    var selectedIDs = ValidateDeleteData();
    if (selectedIDs.length > 0)
    { $('#deletePopup').modal("show"); }
    else {
        $("#myAlert").modal({ show: true, backdrop: 'static', keyboard: false });
        $("#myAlert .modal-header").addClass("delete");
        $("#myAlert div#AlertMsg").empty();
        $("#myAlert div#AlertMsg").append('Please select an item');
    }
});
//To validate Sales item for delete
function ValidateDeleteData() {
    var selectedItems = new Array();
    $('input:checkbox.checkBox').each(function () {
        if ($(this).prop('checked')) {
            selectedItems.push($(this).val());
        }
    });
    return selectedItems;
};
//For Delete Action
$(document).on("click", "#btnDelete", function () {
    var selectedIds = new Array();
    $('input:checkbox.checkBox').each(function () {
        if ($(this).prop('checked')) {
            selectedIds.push($(this).val());
        }
    });

    var options = {};
    options.url = RootUrl + "/Sales/DeleteReturn";
    options.type = "POST";
    options.data = JSON.stringify(selectedIds);
    options.contentType = "application/json";
    options.dataType = "json";
    options.success = function (msg) {

        window.location.href = RootUrl + "/Sales/SalesReturnSummary";

    };
    options.error = function (error) {
        $("label[for='Error']").text(error.msg);
    };
    $.ajax(options);

});


/////////////////////End of Sales Summary//////////////////////////




Elmah Exception logs

  /// <summary>
        /// Created By-Salik Ram Maurya
        /// To edit inventory data
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ActionResult EditInventory(int? itemId)
        {
            sbLog = new StringBuilder();
            sbLog.Append("Start of EditInventory() get method of InventoryController");
            sbLog.Append("Inventory Item Id" + itemId);

            try
            {
                if (Session["UserId"] != null)
                {
                    if (itemId > 0)
                    {
                        ViewBag.Id = itemId;
                        InventoryModel objInt = objInventory.EditInventoryData(itemId);
                        sbLog.Append("Item name:");
                        sbLog.Append(objInt.Item);
                        sbLog.Append("End of EditInventory method");
                        return View(objInt);
                    }
                    else
                    {
                        sbLog.Append("Item id is null");
                        sbLog.Append("End of EditInventory method");
                        return RedirectToAction("InventorySummary", "Inventory");
                    }
                }
                else
                {
                    return RedirectToAction("Login", "UserAccount");
                }

            }
            catch (Exception ex)
            {
                sbLog.AppendLine();
                sbLog.Append("Error: " + ex);
                ErrorLog.GetDefault(null).Log(new Error(new InvalidOperationException("Log:" + sbLog.ToString())));

                return View("Error", new HandleErrorInfo(ex, "Edit Inventory Info", "EditInventory"));
            }

        }
config file
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
    </sectionGroup>

  <section name="chargify" type="ChargifyNET.Configuration.ChargifyAccountRetrieverSection"/></configSections>

  <elmah>
    <security allowRemoteAccess="yes"/>
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="BluSavvyConnectionString"/>
    <errorMail from="salikm@chetu.com" to="salikm@chetu.com" subject="BluSavvy-TX - Exception Notification" async="true"/>

    <errorFilter>
      <test>
        <jscript>
          <expression>
            <![CDATA[
                    // @assembly mscorlib
                    // @assembly System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
                    // @import System.IO
                    // @import System.Web

                    $.Context.Request.UserAgent.match('/*+/arterySignalR/ping')                    
                    ]]>
          </expression>
        </jscript>
      </test>
    </errorFilter>
   
  </elmah>

  <connectionStrings>
    <!--<add name="BluSavvyConnectionString" connectionString="Data Source=DATA-PROD\SQL2014;Initial Catalog=BluSavvy-TX;Persist Security Info=True;User ID=BluSavvy;Password=Blu@123" providerName="System.Data.SqlClient" />-->
    <add name="BluSavvyConnectionString" connectionString="Data Source=WEBSERVER\SQL2014;Initial Catalog=BluSavvy;Persist Security Info=True;User ID=BluSavvy;Password=Chetu@123" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="mahtabh@chetu.com">
        <specifiedPickupDirectory pickupDirectoryLocation="D:\mailroot"></specifiedPickupDirectory>
        <!--<network host="localhost" port="25" defaultCredentials="true" enableSsl="false" />-->
        <!--Uncomment for sending email of elmah exceptions-->
        <network host="mail01.chetu.com" userName="salikm@chetu.com" password="Chetu@21" port="25" defaultCredentials="false" enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>

  <appSettings>
    <add key="webpages:Version" value="2.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="PreserveLoginUrl" value="true"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

    <add key="userName" value="rajukumar637@gmail.com"/>
    <add key="password" value="cabps6453c"/>
    <add key="MailServerName" value="smtp.gmail.com,587"/>
    <add key="MailFrom" value="rajukumar637@gmail.com"/>
    <add key="Host" value="smtp.gmail.com"/>
    <add key="Port" value="587"/>

    <add key="Subject" value="Password Reset Link"/>
    <add key="ReferralSubject" value="Congratulations..!! Referral is successful."/>
    <add key="Welcome" value="Welcome..!! You have successfully subscribed"/>
    <add key="Register" value="Welcome..!! You have successfully registered"/>


    <!--status of Sales-->
    <add key="DepositStatus" value="Deposited"/>
    <add key="UndepositStatus" value="Undeposited"/>
    <add key="EncryptionKey" value="MAKV2SPBNI99212"/>
    <add key="BasicPlan" value="14.99"/>
    <add key="PremiumPlan" value="29.99"/>

    <add key="elmah.mvc.disableHandler" value="false"/>
    <add key="elmah.mvc.disableHandleErrorFilter" value="false"/>
    <add key="elmah.mvc.requiresAuthentication" value="false"/>
    <add key="elmah.mvc.IgnoreDefaultRoute" value="false"/>
    <add key="elmah.mvc.allowedRoles" value="*"/>
    <add key="elmah.mvc.allowedUsers" value="*"/>
    <add key="elmah.mvc.route" value="elmah"/>
    <add key="elmah.mvc.UserAuthCaseSensitive" value="true"/>
  </appSettings>
  <system.web>
    <customErrors mode="Off">
      <error statusCode="404" redirect="~/Error.html"/>
    </customErrors>

    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <authentication mode="Forms">
      <forms loginUrl="~/UserAccount/Login" timeout="5760"/>
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers"/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
    </httpModules>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
    </httpHandlers>

  </system.web>
  <system.webServer>


    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="Elmah.ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler"/>
      <add name="Elmah.ErrorMail" type="Elmah.ErrorMailModule" preCondition="managedHandler"/>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler"/>
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler"/>
    </modules>

    <handlers>
      <add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode"/>

      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
    <!--<directoryBrowse enabled="true" />
        <staticContent>
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
        </staticContent>-->
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246"/>
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246"/>
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-1.2.15.0" newVersion="1.2.15.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework.MappingAPI" publicKeyToken="7ee2e825d201459e" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.9" newVersion="5.0.0.9"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>


  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v12.0"/>
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>


    <chargify defaultAccount="TestSiteAccount">
      <accounts>
      <add name="TestSiteAccount" site="https://yoursubdomain.chargify.com" apiKey="AbCdEfGhIjKlMnOpQrSt" apiPassword="P" sharedKey="AbCdEfGhIjKlMnOpQrSt"/>
      </accounts>
    </chargify>

</configuration>

Import file

 [HttpPost]
        public ActionResult ImportFile(string submitButton)
        {
            sbLog = new StringBuilder();
            sbLog.Append("Start of ImportFile() method of InventoryController");
            sbLog.Append(", Path:InventoryController/ImportFile()");
            if (submitButton.Equals("Upload"))
            {
                if (Request.Files["fileupload1"].ContentLength > 0)
                {
                    try
                    {
                        string ext = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
                        if (ext.ToUpperInvariant() == ".XLSX" || ext.ToUpperInvariant() == ".XLS" || ext.ToUpperInvariant() == ".CSV")
                        {
                            sbLog.Append(", File extension:" + ext);
                            string filePath = string.Format(culture, "{0}/{1}", Server.MapPath("~/Content/UploadFile"), Request.Files["FileUpload1"].FileName);

                            if (System.IO.File.Exists(filePath))
                                System.IO.File.Delete(filePath);

                            Request.Files["FileUpload1"].SaveAs(filePath);
                            string excelConnectionString = string.Empty;

                            if (ext.ToUpperInvariant() == ".XLSX")
                            {
                                excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath.Trim() + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
                            }
                            else if (ext.ToUpperInvariant() == ".XLS")
                            {
                                excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath.Trim() + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                            }
                            else if (ext.ToUpperInvariant() == ".CSV")
                            {
                                excelConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(filePath) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"";
                            }
                            string sql = "";
                            using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
                            {
                                if (ext.ToUpperInvariant() == ".CSV")
                                {
                                    sql = InventoryMessages.ImportCsvQuery + " " + Request.Files["FileUpload1"].FileName;
                                }
                                else
                                {
                                    sql = InventoryMessages.ImportExcelQuery;
                                }

                                using (OleDbCommand cmd = new OleDbCommand(sql, excelConnection))
                                {
                                    excelConnection.Open();

                                    using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                                    {

                                        using (DataTable dt = new DataTable())
                                        {
                                            dt.Locale = culture;
                                            da.Fill(dt);

                                            if (dt.Columns.Count.Equals(5) || dt.Columns.Count.Equals(6) || dt.Columns.Count.Equals(7))
                                            {
                                                if (dt.Rows.Count > 0)
                                                {
                                                    List<InventoryModel> lstInventory = new List<InventoryModel>();

                                                    string Message = ToValidateExcelCsvFile(dt);

                                                    if (!string.IsNullOrEmpty(Message))
                                                    {
                                                        TempData["Error"] = Message;
                                                        return RedirectToAction("InventoryListing", "Inventory");
                                                    }

                                                    else
                                                    {
                                                        foreach (DataRow dr in dt.Rows)
                                                        {
                                                            lstInventory.Add(new InventoryModel
                                                            {
                                                                Item = dr[0].ToString(),
                                                                Size = dr[1].ToString(),
                                                                Unit = Convert.ToDecimal(dr[2], culture),
                                                                WholSaleCostPerUnit = Convert.ToDecimal(dr[3], culture),
                                                                RetailValuePerUnit = Convert.ToDecimal(dr[4], culture),
                                                                ExtendedCost = Convert.ToDecimal(dr[2], culture) * Convert.ToDecimal(dr[3], culture),
                                                                ExtendedRetailValue = Convert.ToDecimal(dr[2], culture) * Convert.ToDecimal(dr[4], culture)
                                                            });
                                                        }
                                                        //find duplicate record in excel/csv file.
                                                        List<InventoryModel> lstDuplicateInventory = lstInventory.Except(lstInventory.GroupBy(i => new { i.Item, i.Size }).Select(ss => ss.FirstOrDefault())).ToList();
                                                        List<InventoryModel> lstDistinctInventoryFromExcel = new List<InventoryModel>();
                                                        bool isExcelDuplicate = false;
                                                        bool isDuplicateinDB = false;
                                                        if (lstDuplicateInventory.Count() > 0)
                                                        {
                                                            sbLog.Append("Duplicate record in excel file");
                                                            ViewBag.IsDuplicateInExcel = true;
                                                            ViewBag.DuplicateInExcel = lstDuplicateInventory;
                                                            isExcelDuplicate = true;
                                                            lstDistinctInventoryFromExcel = lstInventory.GroupBy(item => new { item.Item, item.Size }).Select(group => group.First()).ToList();
                                                        }
                                                        else
                                                        {
                                                            ViewBag.IsDuplicateInExcel = false;
                                                            ViewBag.DuplicateInExcel = null;
                                                            isExcelDuplicate = false;
                                                        }

                                                        List<InventoryModel> lstDuplicateInDB = new List<InventoryModel>();
                                                        //find duplicate record in database table.
                                                        if (isExcelDuplicate)
                                                        {
                                                            isDuplicateinDB = objInventory.CheckDuplicateFromDB(lstDistinctInventoryFromExcel, Convert.ToInt16(Session["UserId"], culture), out lstDuplicateInDB);
                                                        }
                                                        else
                                                        {
                                                            isDuplicateinDB = objInventory.CheckDuplicateFromDB(lstInventory, Convert.ToInt16(Session["UserId"], culture), out lstDuplicateInDB);
                                                        }

                                                        if (isDuplicateinDB)
                                                        {
                                                            sbLog.Append("Duplicate record in database file");
                                                            ViewBag.IsDuplicateInDB = true;
                                                            ViewBag.DuplicateInDB = lstDuplicateInDB;
                                                        }
                                                        else
                                                        {
                                                            ViewBag.IsDuplicateInDB = false;
                                                            ViewBag.DuplicateInDB = null;
                                                        }

                                                        var lstDistinctInventory = (object)null;

                                                        if (isExcelDuplicate && isDuplicateinDB)
                                                        {
                                                            lstDistinctInventory = lstDistinctInventoryFromExcel.Where(a => !lstDuplicateInDB.Any(b => a.Item == b.Item && a.Size == b.Size)).ToList();

                                                        }
                                                        else if (!isExcelDuplicate && isDuplicateinDB)
                                                        {
                                                            lstDistinctInventory = lstInventory.Where(ah => !lstDuplicateInDB.Any(h => h.Item == ah.Item && h.Size == ah.Size)).ToList();
                                                        }
                                                        else if (isExcelDuplicate)
                                                        {
                                                            lstDistinctInventory = lstDistinctInventoryFromExcel;
                                                        }
                                                        else
                                                            lstDistinctInventory = lstInventory;

                                                        ViewBag.IsData = true;

                                                        Session["ImportList"] = lstDistinctInventory;
                                                        sbLog.Append("Inventory excel/csv file read successfully ");
                                                        return View(lstDistinctInventory);
                                                    }
                                                }
                                            }
                                            else if (dt.Columns.Count < 5)
                                            {
                                                TempData["Error"] = InventoryMessages.InvalidColumn;
                                                return RedirectToAction("InventoryListing", "Inventory");
                                            }
                                            else
                                            {
                                                TempData["Error"] = InventoryMessages.InvalidFileFormat;
                                                return RedirectToAction("InventoryListing", "Inventory");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sbLog.AppendLine();
                        sbLog.Append("Error: " + ex);
                        ErrorLog.GetDefault(null).Log(new Error(new InvalidOperationException("Log:" + sbLog.ToString())));

                        TempData["Error"] = InventoryMessages.InvalidFileFormat;
                        return RedirectToAction("InventoryListing", "Inventory");
                    }
                }
            }
            else if (submitButton.Equals("Import"))
            {
                if (Session["ImportList"] != null)
                {
                    List<InventoryModel> lstInventory = (List<InventoryModel>)Session["ImportList"];

                    List<InventoryModel> lstduplicate = new List<InventoryModel>();
                    bool isResult = objInventory.ImportInventory(lstInventory, Convert.ToInt16(Session["UserId"], culture));

                    if (!isResult)
                    {
                        ViewBag.IsDuplicateInExcel = true;
                        ViewBag.IsDuplicateInDB = true;
                        ViewBag.IsData = false;
                        ViewBag.DuplicateInExcel = lstduplicate;
                        ViewBag.DuplicateInDB = lstduplicate;
                        TempData["dup"] = lstduplicate;
                        return View();
                    }
                    else
                    {
                        ViewBag.IsDuplicateInExcel = false;
                        ViewBag.IsDuplicateInDB = false;

                        ViewBag.IsData = true;
                        ViewBag.DuplicateInExcel = null;
                        ViewBag.DuplicateInDB = null;
                        TempData["dup"] = null;
                        sbLog.Append("Inventory excel/csv file imported successfully ");
                        TempData["Success"] = InventoryMessages.ImportFileMessage;
                        return RedirectToAction("InventoryListing", "Inventory");
                    }
                }

            }
            else if (submitButton.Equals("Cancel"))
            {

                return RedirectToAction("InventoryListing", "Inventory");
            }

            // return View();
            return RedirectToAction("InventoryListing", "Inventory");
        }

private static string ToValidateExcelCsvFile(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            bool isItem = false;
            bool isSize = false;
            bool isUnit = false;
            bool isWholeSale = false;
            bool isRetail = false;

            bool unit = true;
            bool wholSale = true;
            bool retailValue = true;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                    {
                        if (j == 0)
                        {
                            isItem = true;
                        }
                        if (j == 1)
                        { isSize = true; }
                        if (j == 2)
                        { isUnit = true; }
                        if (j == 3)
                        { isWholeSale = true; }
                        if (j == 4)
                        { isRetail = true; }
                    }
                }
            }

            foreach (DataRow drow in dt.Rows)
            {

                if (!string.IsNullOrEmpty(drow[2].ToString()))
                {
                    unit = ValidateDecimalValues(drow[2].ToString());
                }
                if (!string.IsNullOrEmpty(drow[3].ToString()))
                {
                    wholSale = ValidateDecimalValues(drow[3].ToString());
                }
                if (!string.IsNullOrEmpty(drow[4].ToString()))
                {
                    retailValue = ValidateDecimalValues(drow[4].ToString());
                }

                if (!unit)
                {
                    sb.Append(InventoryMessages.Unit);
                    sb.Append(",");
                }
                if (!wholSale)
                {
                    sb.Append(InventoryMessages.WholSale);
                    sb.Append(",");
                }
                if (!retailValue)
                {
                    sb.Append(InventoryMessages.RetailValue);
                    sb.Append(",");
                }

            }
            if (isItem)
            {
                sb.Append(InventoryMessages.ItemRequired);
                sb.Append(",");
            }
            if (isSize)
            {
                sb.Append(InventoryMessages.SizeRequired);
                sb.Append(",");
            }
            if (isUnit)
            {
                sb.Append(InventoryMessages.UntiRequired);
                sb.Append(",");
            }
            if (isWholeSale)
            {
                sb.Append(InventoryMessages.WholSaleRequired);
                sb.Append(",");
            }
            if (isRetail)
            {
                sb.Append(InventoryMessages.RetailValueRequired);
                sb.Append(",");
            }

            String input = sb.ToString();
            String[] inputArray = input.Split(',');
            //Select distinct array
            String[] distinctInputArray = inputArray.Distinct().ToArray();
            StringBuilder Result = new StringBuilder();
            foreach (String s in distinctInputArray)
            {
                Result.Append(s);
            }

            return Result.ToString();
        }