Exemplo n.º 1
0
        public ActionResult BatchUpload(HttpPostedFileBase sectorFile)
        {
            using (var scope = new TransactionScope())
            {
                try
                {
                    var affectedRows = 0;
                    var sectors      = new List <SectorInfo>();

                    if (sectorFile == null || sectorFile.ContentLength <= 0)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Invalid File!", "File is empty or corrupted.");
                        return(RedirectToAction("Index"));
                    }
                    // 1048567 bytes = 1 MegaByte
                    if (sectorFile.FileName == string.Empty || sectorFile.ContentLength > 1048576)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Large File!", "File cannot be more than 1 MegaByte.");
                        return(RedirectToAction("Index"));
                    }
                    var extension = Path.GetExtension(sectorFile.FileName);
                    // ReSharper disable once InvertIf
                    if (extension == null || _allowedUploadFile.IndexOf(extension) == -1)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Invalid File!", "Unsupported file, only .xls, .xlsx, .csv file are allowed.");
                        return(RedirectToAction("Index"));
                    }


                    // File reading begin with following format
                    // +--------------+--------------+--------+
                    // | Airport Name | Airport Code | Status |
                    // | xcxcxcxcxcxc | codecxcxcxcc |   0/1  |

                    if (extension == ".csv")
                    {
                        using (var reader = new BinaryReader(sectorFile.InputStream))
                        {
                            var binData   = reader.ReadBytes(sectorFile.ContentLength);
                            var result    = System.Text.Encoding.UTF8.GetString(binData);
                            var rows      = result.Split('\n');
                            var rowNumber = 0;
                            foreach (var row in rows)
                            {
                                if (rowNumber < 1)
                                {
                                    rowNumber++; continue;
                                }
                                if (string.IsNullOrWhiteSpace(row.Trim()))
                                {
                                    continue;
                                }
                                var cells  = row.Trim().Replace("\r", "").Split(',');
                                var sector = new SectorInfo
                                {
                                    SectorName = cells[0].ToUpper().Trim(),
                                    SectorCode = cells[1].ToUpper().Trim(),
                                    Status     = cells[2].Trim() == "Active" ? Status.Active : Status.Inactive,
                                    EntryBy    = _db.Users.First(x => x.UserName == User.Identity.Name).Id,
                                    EntryDate  = DateTime.Now
                                };
                                if (_db.SectorInfos.Any(x => x.SectorName == sector.SectorName && x.SectorCode == sector.SectorCode))
                                {
                                    continue;
                                }
                                sector.SectorId = string.Format("BI-{0:000000}", _db.SectorInfos.Count() + 1);
                                sectors.Add(sector);
                            }
                        }
                    }
                    else
                    {
                        using (var stream = sectorFile.InputStream)
                        {
                            IExcelDataReader reader;
                            switch (extension)
                            {
                            case ".xls":
                                reader = ExcelReaderFactory.CreateBinaryReader(stream);
                                break;

                            case ".xlsx":
                                reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                                break;

                            default:
                                reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                                break;
                            }

                            var isHeading = true;
                            while (reader != null && reader.Read())
                            {
                                //skip heading from excel file
                                if (isHeading)
                                {
                                    isHeading = false; continue;
                                }

                                var sector = new SectorInfo
                                {
                                    SectorName = reader.GetString(0).ToUpper().Trim(),
                                    SectorCode = reader.GetString(1).ToUpper().Trim(),
                                    Status     = reader.GetString(2) == "Active" ? Status.Active : Status.Inactive,
                                    EntryBy    = _db.Users.First(x => x.UserName == User.Identity.Name).Id,
                                    EntryDate  = DateTime.Now
                                };

                                if (_db.SectorInfos.Any(x => x.SectorName == sector.SectorName && x.SectorCode == sector.SectorCode))
                                {
                                    continue;
                                }
                                sector.SectorId = string.Format("BI-{0:000000}", _db.SectorInfos.Count() + 1);
                                sectors.Add(sector);
                            }
                        }
                    }

                    foreach (var sector in sectors)
                    {
                        _db.SectorInfos.Add(sector);
                        affectedRows += _db.SaveChanges();
                        //Sending Progress using SignalR
                        Common.SendProgress("Uploading..", affectedRows, sectors.Count);
                    }
                    scope.Complete();

                    Thread.Sleep(1000);

                    TempData["Toastr"] = Toastr.CustomSuccess(string.Format("Sector file uploaded successfully. {0} items added.", affectedRows));
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    Transaction.Current.Rollback();
                    TempData["Toastr"] = Toastr.CustomError("Exception!", ex.Message);
                    return(RedirectToAction("Index"));
                }
            }
        }
Exemplo n.º 2
0
        public ActionResult BatchInsert(HttpPostedFileBase navigationFile)
        {
            using (var scope = new TransactionScope())
            {
                try
                {
                    var affectedRows = 0;
                    var menus        = new List <Menu>();

                    if (navigationFile == null || navigationFile.ContentLength <= 0)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Invalid File!", "File is empty or corrupted.");
                        return(RedirectToAction("Index"));
                    }
                    // 1048567 bytes = 1 MegaByte
                    if (navigationFile.FileName == string.Empty || navigationFile.ContentLength > 1048576)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Large File!", "File cannot be more than 1 MegaByte.");
                        return(RedirectToAction("Index"));
                    }
                    var extension = Path.GetExtension(navigationFile.FileName);
                    // ReSharper disable once InvertIf
                    if (extension == null || _allowedUploadFile.IndexOf(extension) == -1)
                    {
                        TempData["Toastr"] = Toastr.CustomError("Invalid File!", "Unsupported file, only .xls, .xlsx, .csv file are allowed.");
                        return(RedirectToAction("Index"));
                    }

                    // File reading begin with following format
                    // +-------------+-----------------+-------------+-------+
                    // | Module Name | Controller Name | Action Name |Status |
                    // | 1/2/3/4/5/6 | Clients         | Index       |0/1    |

                    if (extension == ".csv")
                    {
                        using (var reader = new BinaryReader(navigationFile.InputStream))
                        {
                            var binData   = reader.ReadBytes(navigationFile.ContentLength);
                            var result    = System.Text.Encoding.UTF8.GetString(binData);
                            var rows      = result.Split('\n');
                            var rowNumber = 0;
                            foreach (var row in rows)
                            {
                                if (rowNumber < 1)
                                {
                                    rowNumber++; continue;
                                }
                                if (string.IsNullOrWhiteSpace(row.Trim()))
                                {
                                    continue;
                                }
                                var cells = row.Trim().Replace("\r", "").Split(',');
                                var menu  = new Menu
                                {
                                    ModuleName     = (Module)Convert.ToInt32(cells[0].Trim()),
                                    ControllerName = cells[1].ToLower().Trim(),
                                    ActionName     = cells[2].ToLower().Trim(),
                                    Status         = (Status)Convert.ToInt32(cells[3].Trim())
                                };
                                if (_db.Menus.Any(x => x.ModuleName == menu.ModuleName && x.ControllerName == menu.ControllerName && x.ActionName == menu.ActionName))
                                {
                                    continue;
                                }
                                menus.Add(menu);
                            }
                        }
                    }
                    else
                    {
                        using (var stream = navigationFile.InputStream)
                        {
                            IExcelDataReader reader;
                            switch (extension)
                            {
                            case ".xls":
                                reader = ExcelReaderFactory.CreateBinaryReader(stream);
                                break;

                            case ".xlsx":
                                reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                                break;

                            default:
                                reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                                break;
                            }

                            var isHeading = true;
                            while (reader != null && reader.Read())
                            {
                                //skip heading from excel file
                                if (isHeading)
                                {
                                    isHeading = false; continue;
                                }

                                var menu = new Menu
                                {
                                    ModuleName     = (Module)Convert.ToInt32(reader.GetDouble(0)),
                                    ControllerName = reader.GetString(1).ToLower().Trim(),
                                    ActionName     = reader.GetString(2).ToLower().Trim(),
                                    Status         = (Status)Convert.ToInt32(reader.GetDouble(3))
                                };

                                if (_db.Menus.Any(x => x.ModuleName == menu.ModuleName && x.ControllerName == menu.ControllerName && x.ActionName == menu.ActionName))
                                {
                                    continue;
                                }
                                menus.Add(menu);
                            }
                        }
                    }

                    foreach (var menu in menus)
                    {
                        _db.Menus.Add(menu);
                        affectedRows += _db.SaveChanges();
                        //Sending Progress using SignalR
                        Common.SendProgress("Uploading..", affectedRows, menus.Count);
                    }
                    scope.Complete();

                    Thread.Sleep(1000);

                    TempData["Toastr"] = Toastr.CustomSuccess(string.Format("Navigation file uploaded successfully. {0} items added.", affectedRows));
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    Transaction.Current.Rollback();
                    TempData["Toastr"] = Toastr.CustomError("Exception!", ex.Message);
                    return(RedirectToAction("Index"));
                }
            }
        }
Exemplo n.º 3
0
        public ActionResult Index(FormCollection collection)
        {
            var generalSettings = new List <GeneralSetting>();
            var siteLogo        = Request.Files["SiteLogo"];

            // ReSharper disable once PossibleNullReferenceException
            if (siteLogo.ContentLength > 0)
            {
                // 1048567 bytes = 1 MegaBytes
                if (siteLogo.FileName == string.Empty || siteLogo.ContentLength > 1048576)
                {
                    TempData["Toastr"] = Toastr.CustomError("Max file size: 1 MB!");
                    return(RedirectToAction("Index"));
                }
                var extension = Path.GetExtension(siteLogo.FileName);

                if (extension == null)
                {
                    return(View());
                }
                extension = extension.ToLower();
                if (_allowedLogoFileTypes.IndexOf(extension) == -1)
                {
                    TempData["Toastr"] = Toastr.CustomError("Only .png, .jpg, .jpeg, .gif, .bmp file types allowed.");
                    return(RedirectToAction("Index"));
                }

                var image = Image.FromStream(siteLogo.InputStream);
                if (image.Width != image.Height)
                {
                    TempData["Toastr"] = Toastr.CustomError("Image size should be Square.");
                    return(RedirectToAction("Index"));
                }

                var setting = new GeneralSetting {
                    SettingName = "SiteLogo", SettingValue = "site-logo" + extension
                };
                generalSettings.Add(setting);
                var serverPath = Server.MapPath("~/Content/Template/img/site");
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }
                var filePath = Path.Combine(serverPath, "site-logo" + extension);
                siteLogo.SaveAs(filePath);
            }

            collection.AllKeys.ForEach(key =>
            {
                var setting = new GeneralSetting {
                    SettingName = key, SettingValue = collection[key].ToString()
                };
                generalSettings.Add(setting);
            });

            using (var dbTransaction = _db.Database.BeginTransaction())
            {
                try
                {
                    generalSettings.ForEach(setting =>
                    {
                        if (_db.GeneralSettings.Any(x => x.SettingName == setting.SettingName))
                        {
                            _db.GeneralSettings
                            .Where(x => x.SettingName == setting.SettingName)
                            .Update(u => new GeneralSetting {
                                SettingValue = setting.SettingValue
                            });

                            _db.SaveChanges();
                        }
                        else
                        {
                            _db.GeneralSettings.Add(setting);
                            _db.SaveChanges();
                        }
                    });

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    TempData["Toastr"] = Toastr.DbError(ex.Message);
                    dbTransaction.Rollback();
                    return(RedirectToAction("Index"));
                }
            }
            TempData["Toastr"] = Toastr.CustomSuccess("General Setting Saved!");
            return(RedirectToAction("Index", "GeneralSettings"));
        }