Monday 8 August 2016

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();
        }

No comments:

Post a Comment