public ActionResult DeleteConfirmed(string id) { SupplierModels supplierModels = db.SupplierModels.Find(id); try { var path = Path.Combine(Server.MapPath(db.SupplierModels.Where(m => m.SupplierName == id).Select(m => m.pictureURL).FirstOrDefault())); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } db.SupplierModels.Remove(supplierModels); db.SaveChanges(); } catch (DbUpdateException ex) { var sqlException = ex.InnerException.InnerException as SqlException; if (sqlException != null && sqlException.Number == 2627) { ModelState.AddModelError("", "Supplier already registered!"); return(View(supplierModels)); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message.ToString()); return(View(supplierModels)); } return(RedirectToAction("Index")); }
public ActionResult LoadIngredientUnSelect(string Id, string CompanyId) { SupplierModels model = new SupplierModels(); try { var ListSupIng = _IngredientSupplierFactory.GetDataForSupplier(Id, CompanyId); var ListIng = _ingredientFactory.GetIngredient(null).Where(x => x.IsActive && x.CompanyId.Equals(CompanyId)).ToList(); foreach (var item in ListIng) { model.ListSupIngUnSelected.Add(new Ingredients_SupplierModel { IngredientId = item.Id, IngredientName = item.Name, IngredientCode = item.Code, IsCheck = false, CompanyId = item.CompanyId }); } model.ListSupIngUnSelected = model.ListSupIngUnSelected.OrderBy(oo => oo.IngredientCode).ThenBy(x => x.IngredientName).ToList(); model.ListSupIngUnSelected = model.ListSupIngUnSelected.Where(Ing => !(ListSupIng).Any(a1 => a1 == Ing.IngredientId)).ToList(); } catch (Exception e) { _logger.Error("SupplierLoadIngredientUn: " + e); return(new HttpStatusCodeResult(400, e.Message)); } return(PartialView("_ListIngredientUnSelected", model)); }
public ActionResult Create(SupplierModels model) { try { if (!ModelState.IsValid) { // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(View(model)); } model.CreatedBy = CurrentUser.UserName; model.ModifierBy = CurrentUser.UserName; model.CreatedDate = DateTime.Now; model.ModifierDate = DateTime.Now; model.ListSupIng = model.ListSupIng.Where(x => x.IsActived).ToList(); string msg = ""; bool result = _factory.Insert(model, ref msg); if (result) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("Name", msg); // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(View(model)); } } catch (Exception ex) { _logger.Error("SupplierCreate: " + ex); return(new HttpStatusCodeResult(400, ex.Message)); } }
public ActionResult Create(SupplierModels supplier) { //Create new supplier supplierRepository.newSupplier(supplier); return(RedirectToAction("Index")); }
public ActionResult Import(SupplierModels model) { try { if (model.ListCompanys == null || model.ListCompanys.Count == 0) { ModelState.AddModelError("ListCompanys", CurrentUser.GetLanguageTextFromKey("Please choose company.")); return(View(model)); } if (model.ExcelUpload == null || model.ExcelUpload.ContentLength <= 0) { ModelState.AddModelError("ExcelUpload", CurrentUser.GetLanguageTextFromKey("Excel filename cannot be null")); return(View(model)); } ImportModel importModel = new ImportModel(); string msg = ""; int totalRowExcel; if (model.ExcelUpload != null && model.ExcelUpload.ContentLength > 0) { string fileName = Path.GetFileName(model.ExcelUpload.FileName); string filePath = string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/Uploads"), fileName); //upload file to server if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } model.ExcelUpload.SaveAs(filePath); StatusResponse response = _factory.Import(filePath, CurrentUser.UserName, out totalRowExcel, model.ListCompanys, ref importModel, ref msg); if (!response.Status) { ModelState.AddModelError("", response.MsgError); return(View(model)); } } if (msg.Equals("")) { return(View("ImportDetail", importModel)); } else { _logger.Error("Supplier_Import: " + msg); ModelState.AddModelError("ExcelUpload", msg); return(View(model)); } } catch (Exception e) { _logger.Error("Supplier: " + e); ModelState.AddModelError("ExcelUpload", CurrentUser.GetLanguageTextFromKey("Import file have error")); return(View(model)); } }
public void InsertOrUpdateContactXero(string typeAction, SupplierModels model, string SupplierId) { var xeroInfo = Commons.GetIntegrateInfoWithComId(model.CompanyId); if (xeroInfo != null) { SupplierXeroFactory _facSupplier = new SupplierXeroFactory(); var modelsXero = new SupplierXeroModels() { AppRegistrationId = xeroInfo.ThirdPartyID, StoreId = xeroInfo.IPAddress, Contact = new ContactModels { ContactID = typeAction.Equals("update") ? model.Id : "", Name = model.Name, EmailAddress = model.Email, BankAccountDetails = "", IsSupplier = true, IsCustomer = false, HasAttachments = false, Addresses = new List <AddressesModels> { new AddressesModels { AddressType = 1, City = model.City, Country = model.Country, PostalCode = model.ZipCode, Region = "", } }, Phones = new List <PhonesModels> { new PhonesModels { PhoneType = 1, PhoneNumber = model.Phone1, PhoneAreaCode = "", PhoneCountryCode = "", }, new PhonesModels { PhoneType = 1, PhoneNumber = model.Phone2, PhoneAreaCode = "", PhoneCountryCode = "", } }, UpdatedDateUTC = DateTime.Now }, }; var msgXero = string.Empty; var resultXero = _facSupplier.CreateOrUpdateSupplier(xeroInfo.ApiURL, modelsXero, SupplierId, ref msgXero); } }
//Create Supplier public SupplierModels newSupplier(SupplierModels supplier) { if (ModelState.IsValid) { _db.SupplierModels.Add(supplier); _db.SaveChanges(); } return(supplier); }
public ActionResult Edit([Bind(Include = "SupplierName,SupplierGroup,CompanyName,PhoneNumber,CellNumber,Email,password,BarCodeNumber,IDCardNumber,pictureURL,Published,Address")] SupplierModels supplierModels, HttpPostedFileBase filepicture) { ViewBag.CompanyNamelist = new SelectList(db.CompanyNameModels.ToList(), "CompanyName", "CompanyName"); ViewBag.SupplierGrouplist = new SelectList(db.SupplierGroupModels.ToList(), "GroupName", "GroupName"); if (ModelState.IsValid) { var Prevpath = Path.Combine(Server.MapPath(db.SupplierModels.Where(m => m.SupplierName == supplierModels.SupplierName).Select(m => m.pictureURL).FirstOrDefault())); supplierModels.pictureURL = db.SupplierModels.Where(m => m.SupplierName == supplierModels.SupplierName).Select(m => m.pictureURL).FirstOrDefault(); if (System.IO.File.Exists(Prevpath) && filepicture != null) { System.IO.File.Delete(Prevpath); } if (filepicture != null) { var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" }; var fileName = Path.GetFileName(filepicture.FileName); var ext = Path.GetExtension(filepicture.FileName); //getting the extension(ex-.jpg) if (allowedExtensions.Contains(ext)) //check what type of extension { string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension string myfile = supplierModels.SupplierName + ext; //appending the name with id // store the file inside ~/project folder(Img) var path = Path.Combine(Server.MapPath("~/SupplierPic/" + supplierModels.SupplierName), myfile); supplierModels.pictureURL = Path.Combine("~/SupplierPic/" + supplierModels.SupplierName, myfile); filepicture.SaveAs(path); } } try { db.Entry(supplierModels).State = EntityState.Modified; db.SaveChanges(); } catch (DbUpdateException ex) { var sqlException = ex.InnerException.InnerException as SqlException; if (sqlException != null && sqlException.Number == 2627) { ModelState.AddModelError("", "Supplier already registered!"); return(View(supplierModels)); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message.ToString()); return(View(supplierModels)); } ////////////// ///////////// return(RedirectToAction("Index")); } return(View(supplierModels)); }
// GET: SupplierModels/Delete/5 public ActionResult Delete(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SupplierModels supplierModels = db.SupplierModels.Find(id); if (supplierModels == null) { return(HttpNotFound()); } return(View(supplierModels)); }
public ActionResult Edit(string id) { ViewBag.CompanyNamelist = new SelectList(db.CompanyNameModels.ToList(), "CompanyName", "CompanyName"); ViewBag.SupplierGrouplist = new SelectList(db.SupplierGroupModels.ToList(), "GroupName", "GroupName"); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SupplierModels supplierModels = db.SupplierModels.Find(id); if (supplierModels == null) { return(HttpNotFound()); } return(View(supplierModels)); }
public ActionResult Export(SupplierModels model) { try { // set name for sheet in file excel XLWorkbook wb = new XLWorkbook(); var wsSupplier = wb.Worksheets.Add("Supplier"); var wsSupplierIngerdient = wb.Worksheets.Add("Ingredients_Supplier"); var response = _factory.Export(ref wsSupplier, ref wsSupplierIngerdient, model.ListCompanys, lstCompany); if (!response.IsOk) { ModelState.AddModelError("Supplier", response.Message); return(View(response)); } ViewBag.wb = wb; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Charset = System.Text.UTF8Encoding.UTF8.WebName; Response.ContentEncoding = System.Text.UTF8Encoding.UTF8; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", CommonHelper.GetExportFileName("Supplier").Replace(" ", "_"))); using (var memoryStream = new System.IO.MemoryStream()) { wb.SaveAs(memoryStream); memoryStream.WriteTo(HttpContext.Response.OutputStream); memoryStream.Close(); } HttpContext.Response.End(); return(RedirectToAction("Export")); } catch (Exception e) { _logger.Error("SupplierExport: " + e); //return new HttpStatusCodeResult(400, e.Message); ModelState.AddModelError("List", CurrentUser.GetLanguageTextFromKey("Export file have error")); return(View(model)); } }
public ActionResult Create() { SupplierModels model = new SupplierModels(); // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(View(model)); }
public PartialViewResult Edit(string id) { SupplierModels model = GetDetail(id); // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(PartialView("_Edit", model)); }
public ActionResult Delete(SupplierModels model) { try { string msg = ""; var result = _factory.Delete(model.Id, ref msg); if (!result) { ModelState.AddModelError("Name", msg); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(PartialView("_Delete", model)); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (Exception ex) { _logger.Error("SupplierDelete: " + ex); ModelState.AddModelError("Name", CurrentUser.GetLanguageTextFromKey("Have an error when you delete an Supplier")); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(PartialView("_Delete", model)); } }
public ActionResult Edit(SupplierModels model) { ViewData["CountryList"] = new SelectList(_supplierServices.GetAllCountry(), "Id", "CountryName"); if (ModelState.IsValid) { if (model.Id > 0) { model.ModifiedBy = currentUser.Id; model.DateModify = DateTime.Now; _supplierServices.UpdateSupplier(model); } else { model.CreatedBy = currentUser.Id; model.DateCreate = DateTime.Now; model.Id = 0; _supplierServices.InsertSupplier(model); } return(Json(1)); } return(PartialView("_formEditView", model)); }
public SupplierModels GetDetail(string id) { try { SupplierModels model = _factory.GetDetail(id); if (!string.IsNullOrEmpty(model.CompanyId)) { model.CompanyName = lstCompany.Where(z => z.Value.Equals(model.CompanyId)).FirstOrDefault().Text; } //============= var ListSupIng = _IngredientSupplierFactory.GetDataForSupplier(model.Id, model.CompanyId); var ListIng = _ingredientFactory.GetIngredient(null).Where(x => x.IsActive).ToList(); foreach (var item in ListIng) { model.ListSupIng.Add(new Ingredients_SupplierModel { IngredientId = item.Id, IngredientName = item.Name, IngredientCode = item.Code, //IsCheck = ListSupIng.Any(z => z.Equals(item.Id)), IsActived = ListSupIng.Any(x => x.Equals(item.Id)), }); } //model.ListSupIng.ForEach(x => //{ // x.IsCheck = ListSupIng.Any(z => z.Equals(x.IngredientId)); //}); model.ListSupIng = model.ListSupIng.Where(x => x.IsActived).OrderByDescending(x => x.IsActived ? 1 : 0).ThenBy(x => x.IngredientName).ToList(); //model.ListSupIng = model.ListSupIng.OrderByDescending(x => x.IsActived ? 1 : 0).ThenBy(x => x.IngredientName).ToList(); return(model); } catch (Exception ex) { _logger.Error("SupplierDetail: " + ex); return(null); } }
public Dictionary <string, object> UploadTargets(string path_and_file) { try { //variable for logs int success = 0; int fail = 0; int total = 0; //get current workweek and year //di ko sure kung kailangan to //List<int> curr_ww = workweek_helper.GetCurrentWorkWeek(); //int current_workweek = curr_ww[0]; //int current_year = curr_ww[1]; response = new Dictionary <string, object>(); //kailangan ko to SupplierModels t = new SupplierModels(); FileStream stream = File.Open(path_and_file, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = null; string ext = Path.GetExtension(stream.Name); if (ext == ".xls") { //1. Reading from a binary Excel file ('97-2003 format; *.xls) excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (ext == ".xlsx") { //2. Reading from a OpenXml Excel file (2007 format; *.xlsx) excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else { throw new Exception("Invalid file type."); } //Choose one of either 3, 4, or 5 //3. DataSet - The result of each spreadsheet will be created in the result.Tables //DataSet result = excelReader.AsDataSet(); //4. DataSet - Create column names from first row excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(); //5. Data Reader methods DateTime dateCreated = DateTime.Now; int ctr = 0; string log_output = ""; ////override function //if (allowOverride) //{ // t.DeleteTestTargets("WW" + current_workweek.ToString().PadLeft(2, '0'), current_year); //} while (excelReader.Read()) { if (ctr >= 1) { SupplierObject targets = new SupplierObject(); targets.Name = excelReader.IsDBNull(0) ? string.Empty : excelReader.GetString(0); targets.Email = excelReader.IsDBNull(1) ? string.Empty : excelReader.GetString(1); targets.ContactNbr = excelReader.IsDBNull(2) ? string.Empty : excelReader.GetString(2); targets.UnitNbr = excelReader.IsDBNull(3) ? string.Empty : excelReader.GetString(3); targets.StreetName = excelReader.IsDBNull(4) ? string.Empty : excelReader.GetString(4); targets.Municipality = excelReader.IsDBNull(5) ? string.Empty : excelReader.GetString(5); targets.City = excelReader.IsDBNull(6) ? string.Empty : excelReader.GetString(6); targets.Country = excelReader.IsDBNull(7) ? string.Empty : excelReader.GetString(7); targets.Zip = excelReader.IsDBNull(8) ? 0 : Convert.ToInt32(excelReader.GetString(8)); targets.ImpexRefNbr = excelReader.IsDBNull(9) ? string.Empty : excelReader.GetString(9); targets.IsActive = true; targets.AddedBy = Convert.ToInt32(HttpContext.Current.Session["userId_local"]); targets.DateAdded = dateCreated; t.SaveNewSupplier(targets); total++; success++; //buburahin ko to titira ko lang "t.SaveTargets(targets)" //if (targets.WorkWeek != "WW" + current_workweek.ToString().PadLeft(2, '0') || targets.FiscalYear != current_year) //{ // fail++; // log_output += "<p><span class='label label-danger'>[" + targets.ProductGroup + "] [" + targets.PackageGroupA + "] [" + targets.PackageGroupB + "] [" + targets.Target + "] [" + targets.WorkWeek + "] [" + targets.FiscalYear + "] = work week or year mismatch</span></p>"; //} //else //{ // if (t.CheckExistingTestTarget(targets) > 0) // { // fail++; // log_output += "<p><span class='label label-danger'>[" + targets.ProductGroup + "] [" + targets.PackageGroupA + "] [" + targets.PackageGroupB + "] [" + targets.Target + "] [" + targets.WorkWeek + "] [" + targets.FiscalYear + "] = already exists</span></p>"; // } // else // { // if (!t.SaveTargets(targets)) // { // fail++; // log_output += "<p><span class='label label-danger'>[" + targets.ProductGroup + "] [" + targets.PackageGroupA + "] [" + targets.PackageGroupB + "] [" + targets.Target + "] [" + targets.WorkWeek + "] [" + targets.FiscalYear + "] = failed</span></p>"; // } // else // { // hasSuccess = true; // success++; // log_output += "<p><span class='label label-success'>[" + targets.ProductGroup + "] [" + targets.PackageGroupA + "] [" + targets.PackageGroupB + "] [" + targets.Target + "] [" + targets.WorkWeek + "] [" + targets.FiscalYear + "] = added</span></p>"; // } // } //} //hanggang dito //total++; } ctr++; } //if (hasSuccess) //{ // t.RefreshData(); //} //6. Free resources (IExcelDataReader is IDisposable) excelReader.Close(); Dictionary <string, int> stats = new Dictionary <string, int>(); stats.Add("success", success); stats.Add("fail", fail); Dictionary <string, string> msg = new Dictionary <string, string>(); if (total <= 0) { throw new Exception("Uploaded file is empty or is in the wrong format. Kindly check the guidelines for uploading."); } else { if (success == total) { msg.Add("title", "Uploading Successful!"); msg.Add("body", "New targets uploaded successfully!"); msg.Add("type", "success"); } else { msg.Add("title", "Uploading Unsuccessful!"); msg.Add("body", success + " / " + total + " uploaded successfully!"); msg.Add("type", "danger"); } } response.Add("success", true); response.Add("error", false); response.Add("stats", stats); response.Add("logs", log_output); response.Add("message", msg); } catch (Exception e) { response.Add("success", false); response.Add("error", true); response.Add("message", e.ToString()); } return(response); }
public ActionResult Edit(SupplierModels model) { try { if (!ModelState.IsValid) { Response.StatusCode = (int)HttpStatusCode.BadRequest; // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(PartialView("_Edit", model)); } model.ModifierDate = DateTime.Now; model.ModifierBy = CurrentUser.UserId; model.ListSupIng = model.ListSupIng.Where(x => x.IsActived).ToList(); model.ListSupIngUnSelected = model.ListSupIngUnSelected.Where(x => x.IsActived).ToList(); model.ListSupIng.AddRange(model.ListSupIngUnSelected); //==================== string msg = ""; var result = _factory.Update(model, ref msg); if (result) { return(RedirectToAction("Index")); } else { ModelState.AddModelError("Name", msg); Response.StatusCode = (int)HttpStatusCode.BadRequest; // Get list Countries // Updated 08292017 List <CountryApiModels> lstCountries = CommonHelper.GetListCountry(); foreach (var country in lstCountries) { model.ListCountries.Add(new SelectListItem { Value = country.Name, Text = country.Name, Selected = country.Name.Equals(model.Country) ? true : false }); } return(PartialView("_Edit", model)); } } catch (Exception ex) { _logger.Error("SupplierEdit: " + ex); return(new HttpStatusCodeResult(400, ex.Message)); } }
public PartialViewResult Delete(string id) { SupplierModels model = GetDetail(id); return(PartialView("_Delete", model)); }
public ActionResult Export() { SupplierModels model = new SupplierModels(); return(View(model)); }
public bool Update(SupplierModels model, ref string msg) { bool result = true; using (NuWebContext cxt = new NuWebContext()) { using (var transaction = cxt.Database.BeginTransaction()) { try { var itemUpdate = (from tb in cxt.I_Supplier where tb.Id == model.Id select tb).FirstOrDefault(); if (itemUpdate != null) { itemUpdate.Name = model.Name; itemUpdate.Address = model.Address; itemUpdate.City = model.City; itemUpdate.Country = model.Country; itemUpdate.ZipCode = model.ZipCode; itemUpdate.Phone1 = model.Phone1; itemUpdate.Phone2 = model.Phone2; itemUpdate.Fax = model.Fax; itemUpdate.Email = model.Email; itemUpdate.ContactInfo = model.ContactInfo; itemUpdate.ModifierDate = model.ModifierDate; itemUpdate.ModifierBy = model.ModifierBy; itemUpdate.IsActived = model.IsActived; /*Detail*/ var ListDelSupIng = (from IS in cxt.I_Ingredient_Supplier where IS.SupplierId.Equals(model.Id) && IS.IsActived == true select IS.Id).ToList(); if (ListDelSupIng.Count > 0) { //ListDelSupIng.ForEach(x => x.IsActived = false); cxt.I_Ingredient_Supplier.Where(w => ListDelSupIng.Contains(w.Id)).ForEach(x => x.IsActived = false); } List <I_Ingredient_Supplier> LstSupplierIng = new List <I_Ingredient_Supplier>(); foreach (var SupIng in model.ListSupIng) { LstSupplierIng.Add(new I_Ingredient_Supplier { Id = Guid.NewGuid().ToString(), IngredientId = SupIng.IngredientId, SupplierId = model.Id, CreatedBy = model.ModifierBy, CreatedDate = model.ModifierDate, ModifierDate = model.ModifierDate, ModifierBy = model.ModifierBy, IsActived = true }); } cxt.I_Ingredient_Supplier.AddRange(LstSupplierIng); cxt.SaveChanges(); transaction.Commit(); /* INSERT OR UPDATE CONTACTS XERO */ InsertOrUpdateContactXero("update", model, model.Id); } } catch (Exception ex) { _logger.Error(ex); result = false; transaction.Rollback(); } finally { if (cxt != null) { cxt.Dispose(); } } } } return(result); }
public ActionResult Create([Bind(Include = "SupplierName,ID,SupplierGroup,CompanyName,PhoneNumber,CellNumber,Email,password,BarCodeNumber,IDCardNumber,pictureURL,Published,Address")] SupplierModels supplierModels, HttpPostedFileBase filepicture) { ViewBag.CompanyNamelist = new SelectList(db.CompanyNameModels.ToList(), "CompanyName", "CompanyName"); ViewBag.SupplierGrouplist = new SelectList(db.SupplierGroupModels.ToList(), "GroupName", "GroupName"); if (ModelState.IsValid) { string subPath = "~/SupplierPic/" + supplierModels.SupplierName.ToString(); // your code goes here bool exists = System.IO.Directory.Exists(Server.MapPath(subPath)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(subPath)); } if (filepicture != null) { var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" }; var fileName = Path.GetFileName(filepicture.FileName); var ext = Path.GetExtension(filepicture.FileName); //getting the extension(ex-.jpg) if (allowedExtensions.Contains(ext)) //check what type of extension { string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension string myfile = supplierModels.SupplierName + ext; //appending the name with id // store the file inside ~/project folder(Img) var path = Path.Combine(Server.MapPath("~/SupplierPic/" + supplierModels.SupplierName), myfile); supplierModels.pictureURL = Path.Combine("~/SupplierPic/" + supplierModels.SupplierName, myfile); filepicture.SaveAs(path); } } //////////// ApplicationDbContext context = new ApplicationDbContext(); var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); if (!RoleManager.RoleExists("Supplier")) { var roleresult = RoleManager.Create(new IdentityRole("Supplier")); } //Create User=Admin with password=123456 //var user = new ApplicationUser(); var user = new ApplicationUser { UserName = supplierModels.SupplierName, Email = supplierModels.Email, roleName = "Supplier" }; //user.UserName = "******";//supplierModels.SupplierName; //user.Email = supplierModels.Email; //user.roleName = "Supplier"; var adminresult = UserManager.Create(user, supplierModels.password); //Add User Admin to Role Admin if (adminresult.Succeeded) { var result = UserManager.AddToRole(user.Id, "Supplier"); } AddErrors(adminresult); ///////////////////////// try { db.SupplierModels.Add(supplierModels); db.SaveChanges(); } catch (DbUpdateException ex) { var sqlException = ex.InnerException.InnerException as SqlException; if (sqlException != null && sqlException.Number == 2627) { ModelState.AddModelError("", "Supplier already registered!"); } return(View(supplierModels)); } catch (Exception ex) { ModelState.AddModelError("", ex.Message.ToString()); return(View(supplierModels)); } //////////// ///////////// return(RedirectToAction("Index")); } return(View(supplierModels)); }
//Import Supplier public StatusResponse Import(string filePath, string userName, out int totalRowExcel, List <string> ListCompanyId, ref ImportModel importModel, ref string msg) { totalRowExcel = 0; StatusResponse Response = new StatusResponse(); using (NuWebContext cxt = new NuWebContext()) { using (var transaction = cxt.Database.BeginTransaction()) { DataTable dtSupplier = ReadExcelFile(filePath, "Supplier"); DataTable dtIngSupplier = ReadExcelFile(filePath, "Ingredients_Supplier"); string tmpExcelPath = System.Web.HttpContext.Current.Server.MapPath("~/ImportExportTemplate") + "/SupplierImportTemplate.xlsx"; DataTable dtTmpSupplier = ReadExcelFile(@tmpExcelPath, "Supplier"); DataTable dtTmpSupplierIng = ReadExcelFile(@tmpExcelPath, "Ingredients_Supplier"); if (dtSupplier.Columns.Count != dtTmpSupplier.Columns.Count) { msg = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey(Commons._MsgDoesNotMatchFileExcel); return(Response); } if (dtIngSupplier.Columns.Count != dtTmpSupplierIng.Columns.Count) { msg = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey(Commons._MsgDoesNotMatchFileExcel); return(Response); } //======== var listcountry = cxt.I_Country.Where(x => x.IsActived).ToList(); var listing = cxt.I_Ingredient.Where(x => x.IsActive).ToList(); bool flagInsert = true; string msgError = ""; ImportItem itemErr = null; List <SupplierModels> Models = new List <SupplierModels>(); SupplierModels SupModel = null; foreach (var company in ListCompanyId) { foreach (DataRow item in dtSupplier.Rows) { flagInsert = true; msgError = ""; if (item[0].ToString().Equals("")) { continue; } int index = int.Parse(item[0].ToString()); //var Country = listcountry.Where(x => x.FullName.Trim().ToLower().Equals(item[4].ToString().Trim().ToLower())).FirstOrDefault(); //if (Country == null) //{ // flagInsert = false; // msgError += "<br/>Country is not exsits!"; //} //======================= SupModel = new SupplierModels(); string SupplierId = Guid.NewGuid().ToString(); SupModel.Id = SupplierId; SupModel.CompanyId = company; SupModel.Index = index.ToString(); SupModel.Name = item[1].ToString(); SupModel.Address = item[2].ToString(); SupModel.City = item[3].ToString(); SupModel.Country = item[4].ToString().Trim();//Country == null ? "" : Country.Id; SupModel.ZipCode = item[5].ToString(); SupModel.Phone1 = item[6].ToString(); SupModel.Phone2 = item[7].ToString(); SupModel.Fax = item[8].ToString(); SupModel.Email = item[9].ToString(); SupModel.ContactInfo = item[10].ToString(); SupModel.IsActived = string.IsNullOrEmpty(_AttributeForLanguage.CurrentUser.GetLanguageTextFromKey(item[11].ToString())) ? false : bool.Parse(_AttributeForLanguage.CurrentUser.GetLanguageTextFromKey(item[11].ToString()).ToLower().Equals("true").ToString()) ? true : false; /*List Ingredient Supplier*/ List <Ingredients_SupplierModel> lstSupplierIng = new List <Ingredients_SupplierModel>(); DataRow[] IngSupplier = dtIngSupplier.Select("[" + _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Supplier Index") + "] = " + index + ""); foreach (DataRow ingsupplier in IngSupplier) { var Ingredient = listing.Where(x => x.Code.ToLower().Equals(ingsupplier[3].ToString().ToLower())).FirstOrDefault(); if (string.IsNullOrEmpty(ingsupplier[1].ToString())) { flagInsert = false; msgError += "<br/>" + _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Supplier Index is required"); } //==== if (string.IsNullOrEmpty(ingsupplier[3].ToString())) { flagInsert = false; msgError += "<br/>" + _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Ingredient Code is required"); } else if (Ingredient == null) { flagInsert = false; msgError += "<br/>" + _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Ingredient is not exsits"); } if (string.IsNullOrEmpty(ingsupplier[4].ToString())) { flagInsert = false; msgError += "<br/>" + _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Ingredient Name is required"); } if (flagInsert) { Ingredients_SupplierModel SupplierIngredient = new Ingredients_SupplierModel() { IngredientId = Ingredient.Id }; lstSupplierIng.Add(SupplierIngredient); } } SupModel.ListSupIng = lstSupplierIng; //====================== if (flagInsert) { Models.Add(SupModel); } else { itemErr = new ImportItem(); itemErr.Name = SupModel.Name; itemErr.ListFailStoreName.Add(""); itemErr.ListErrorMsg.Add(_AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Row") + ": " + SupModel.Index + msgError); importModel.ListImport.Add(itemErr); } } } //================= Response.Status = true; try { List <I_Supplier> lstSave = new List <I_Supplier>(); I_Supplier item = null; foreach (var model in Models) { item = new I_Supplier(); item.Id = model.Id; item.CompanyId = model.CompanyId; item.Name = model.Name; item.Address = model.Address; item.City = model.City; item.Country = model.Country; item.ZipCode = model.ZipCode; item.Phone1 = model.Phone1; item.Phone2 = model.Phone2; item.Fax = model.Fax; item.Email = model.Email; item.ContactInfo = model.ContactInfo; item.CreatedBy = userName; item.CreatedDate = DateTime.Now; item.ModifierDate = DateTime.Now; item.ModifierBy = userName; item.IsActived = model.IsActived; item.Status = (int)Commons.EStatus.Actived; lstSave.Add(item); } cxt.I_Supplier.AddRange(lstSave); //Supplier Ingredient foreach (var model in Models) { /*Detail*/ //Insert Ingredient Supplier List <I_Ingredient_Supplier> LstSupplierIng = new List <I_Ingredient_Supplier>(); foreach (var SupIng in model.ListSupIng) { LstSupplierIng.Add(new I_Ingredient_Supplier { Id = Guid.NewGuid().ToString(), IngredientId = SupIng.IngredientId, SupplierId = model.Id, CreatedBy = userName, CreatedDate = DateTime.Now, ModifierDate = DateTime.Now, ModifierBy = userName, IsActived = model.IsActived, }); } if (LstSupplierIng.Count > 0) { cxt.I_Ingredient_Supplier.AddRange(LstSupplierIng); } /*End Detail*/ } cxt.SaveChanges(); transaction.Commit(); if (importModel.ListImport.Count == 0) { ImportItem impItem = new ImportItem(); impItem.Name = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Supplier"); impItem.ListSuccessStoreName.Add(_AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Import Supplier Successful")); importModel.ListImport.Add(impItem); } } catch (Exception ex) { transaction.Rollback(); _logger.Error(ex); } } } return(Response); }
public bool Insert(SupplierModels model, ref string msg) { bool result = true; using (NuWebContext cxt = new NuWebContext()) { using (var transaction = cxt.Database.BeginTransaction()) { try { I_Supplier item = new I_Supplier(); string SupplierId = Guid.NewGuid().ToString(); item.Id = SupplierId; item.CompanyId = model.CompanyId; item.Name = model.Name; item.Address = model.Address; item.City = model.City; item.Country = model.Country; item.ZipCode = model.ZipCode; item.Phone1 = model.Phone1; item.Phone2 = model.Phone2; item.Fax = model.Fax; item.Email = model.Email; item.ContactInfo = model.ContactInfo; item.CreatedBy = model.CreatedBy; item.CreatedDate = model.CreatedDate; item.ModifierDate = model.ModifierDate; item.ModifierBy = model.ModifierBy; item.IsActived = model.IsActived; item.Status = (int)Commons.EStatus.Actived; //Supplier Ingredient List <I_Ingredient_Supplier> LstSupplierIng = new List <I_Ingredient_Supplier>(); foreach (var SupIng in model.ListSupIng) { LstSupplierIng.Add(new I_Ingredient_Supplier { Id = Guid.NewGuid().ToString(), IngredientId = SupIng.IngredientId, SupplierId = SupplierId, CreatedBy = model.CreatedBy, CreatedDate = model.CreatedDate, ModifierDate = model.ModifierDate, ModifierBy = model.ModifierBy, IsActived = true }); } cxt.I_Supplier.Add(item); cxt.I_Ingredient_Supplier.AddRange(LstSupplierIng); cxt.SaveChanges(); transaction.Commit(); /* INSERT OR UPDATE CONTACTS XERO */ InsertOrUpdateContactXero("insert", model, SupplierId); } catch (Exception ex) { NSLog.Logger.Error("Insert Supplier error:", ex); result = false; transaction.Rollback(); } finally { if (cxt != null) { cxt.Dispose(); } } } } return(result); }