public ActionResult EditCustomer(int id) { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); CustomersRepository customersRepository = new CustomersRepository(context); CustomersEditCustomerVM model = new CustomersEditCustomerVM(); Customer customer = customersRepository.GetByID(id); if (id > 0) { model.ID = customer.ID; model.PersonalNumber = customer.PersonalNumber; model.FirstName = customer.FirstName; model.LastName = customer.LastName; model.Email = customer.Email; model.Address = customer.Address; model.PicturePath = customer.PicturePath; model.Birthday = customer.Birthday; model.DateIn = customer.DateIn; if (customer.DateOut != null) { model.DateOut = customer.DateOut.Value; } } else { customer = new Customer(); model.DateOut = null; } return View(model); }
public void Activate() { _profileRepository = new ProfileRepository(); _materialsRepository = new MaterialsRepository(); _servicesRepository = new ServicesRepository(); _serviceMaterialRepository = new ServiceMaterialsRepository(); _quotesRepository = new QuotesRepository(); _customersRepository = new CustomersRepository(); }
public async Task UseEfViaRepositoryAsync() { // Arrange var customersRepository = new CustomersRepository(_db); // Act var data = await customersRepository.GetTop10Async(); // Assert AssertCustomerData(data); }
public async Task GetOrder_ExistingOrderId_ReturnsOrder() { using (var context = new CustomersDbContext(_options)) { var repository = new CustomersRepository(context, _mapper); var result = await repository.GetOrderAsync(1111, 1234); result.Should().NotBeNull(); result.Id.Should().Be(1234); } }
public async Task GetOrders_ExistingCustomerId_ReturnsOrders() { using (var context = new CustomersDbContext(_options)) { var repository = new CustomersRepository(context, _mapper); var result = (await repository.GetOrdersAsync(1111)).ToList(); result.Should().NotBeEmpty(); result.First().Id.Should().BeGreaterThan(0); } }
public Customer GetCustomer(int id) { Customer customer = new Customer(); CustomersRepository repo = new CustomersRepository(); if (customer != null) { customer = ParserCustomer(repo.Get(id)); } return(customer); }
public static Customer GetOrderReciever(OrderInfo orderInfo) { if (Random.Next(0, 10) % 5 == 0) { var customerPool = CustomersRepository.LoadCustomersFromDb().Where(c => c.Address.Country == "US"); return(customerPool.ElementAt(Random.Next(0, customerPool.Count() - 1))); } return(orderInfo.Customer); }
public void Start() { var customers = CustomersRepository.LoadCustomersFromDb(); var customersFromParis = customers.Where(customer => customer.Address.City == "Paris").ToList(); foreach (var customer in customersFromParis) { SendOverseasPackage(customer); } }
public async Task <ActionResult> GetCustomer(string id) { var repository = new CustomersRepository(_context); Customer customer = await repository.GetById(id); if (customer == null) { return(NotFound()); } return(Ok(customer)); }
public async void use_EF_via_repository_async() { // Arrange var customersRepository = new CustomersRepository(_db); // Act var data = await customersRepository.GetTop10Async(); // Assert AssertCustomerData(data); }
public ActionResult GetAllCustomers() { var repository = new CustomersRepository(_context); var customers = repository.GetAll().ToList(); if (customers == null) { return(NotFound()); } return(Ok(customers)); }
public HttpResponseMessage AddCustomer(CustomersDto customer) { var repo = new CustomersRepository(); var result = repo.Create(customer); if (result) { return(Request.CreateResponse(HttpStatusCode.Created)); } return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not create recipe, try again later...")); }
public void use_EF_via_repository() { // Arrange var customersRepository = new CustomersRepository(_db); // Act var data = customersRepository.GetTop10().ToList(); // Assert AssertCustomerData(data); }
public ProductsApiController() { var db = new SweetShopDataContext(); var orders = new OrdersRepository(db); var orderDetails = new OrderDetailsRepository(db); var products = new ProductsRepository(db); var customers = new CustomersRepository(db); var uow = new EFUnitOfWork(products, orders, orderDetails, customers, db); _uow = uow; }
public HttpResponseMessage UpdateCustomer(int customerId, CustomersDto customer) { var repository = new CustomersRepository(); var StatusResult = repository.UpdateCustomerStatus(customer.Status, customerId); if (StatusResult) { return(Request.CreateResponse(HttpStatusCode.Created)); } return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not update")); }
public CourierHelperDb(string sqlServerConnectionString) { _context = new CourierHelperDbContext(sqlServerConnectionString); OrdersRepo = new OrdersRepository(_context); CouriersRepo = new CouriersRepository(_context); WarehousesRepo = new WarehousesRepository(_context); CustomersRepo = new CustomersRepository(_context); RoutesRepo = new RoutesRepository(_context); ActivePointsRepo = new ActivePointsRepository(_context); TracksRepo = new TracksRepository(_context); }
public static void AddCustomer(LocalDBExample.DTO.Customer customer) { try { CustomersRepository.AddCustomer(customer); } catch (Exception) { // Log it or do w/e throw; } }
public IActionResult Register([FromBody] RegistrationDto registration) { var customer = new CustomerDto() { ClientId = Guid.NewGuid(), CompanyName = registration.CompanyName, RedirectUrl = registration.RedirectUrl }; CustomersRepository.Add(customer); return(CreatedAtRoute(new { customer.ClientId }, customer)); }
public override async Task <string> GetUserIdByLocalAuthenticationContextAsync(LocalAuthenticationContext context, CancellationToken cancellationToken) { string username = context.UserName; string password = context.Password; if (string.IsNullOrEmpty(username)) { throw new BadRequestException("InvalidUserNameOrPassword"); } if (string.IsNullOrEmpty(password)) { throw new BadRequestException("InvalidUserNameOrPassword"); } if (context.SignInMessage.ClientId == "SanaapResOwner") { string nationalCode = username; string mobile = password; Customer customer = await(await CustomersRepository .GetAllAsync(cancellationToken)) .SingleOrDefaultAsync(c => c.Mobile == mobile && c.NationalCode == nationalCode); if (customer == null) { throw new ResourceNotFoundException("CustomerCouldNotBeFound"); } return(customer.Id.ToString()); } else { //await UsersRepository.AddAsync(new User { UserName = "******", Password = HashUtils.HashPassword("test") }, cancellationToken); User user = await(await UsersRepository .GetAllAsync(cancellationToken)) .SingleOrDefaultAsync(u => u.UserName == username); if (user == null) { throw new ResourceNotFoundException("UserCouldNotBeFound"); } if (!HashUtils.VerifyHash(password, user.Password)) { throw new BadRequestException("InvalidUserNameOrPassword"); } return(user.Id.ToString()); } }
public override async Task <IQueryable <ChangeSetDto> > GetAll(CancellationToken cancellationToken) { // We can declare a view for following sql query in database and then map our dto directly to view using ef db context: // select *, (case (((select count(1) from Deliveries as Delivery where ChangeSet.Id = Delivery.ChangeSetId ))) when (select count(1) from Customers) then 1 else 0 end) as IsDeliveredToAll from ChangeSets as ChangeSet // or we can use ef core execute sql which returns IQueryable // Note: _changeSetsRepository.GetAll(changeSet => new ChangeSetDto { Id = changeSet.Id , ... , IsDeliveredToAll = changeSet.Deliveries.Count() == customersQuery.Count() }); results into problematic sql. // The downside of following code are its database round trips. int customersCount = await(await CustomersRepository.GetAllAsync(cancellationToken)).CountAsync(cancellationToken); return(DtoEntityMapper.FromEntityQueryToDtoQuery((await Repository.GetAllAsync(cancellationToken)), parameters: new { customersCount = customersCount })); }
private Customers FindCustomerByEmail() { Console.WriteLine("Please enter your e-mail:"); var userEmail = Console.ReadLine(); var customers = CustomersRepository.GetAll(); var customer = customers.FirstOrDefault(x => x.Email == userEmail); if (customer == null) { throw new FlowException("Customer not found!"); } return(customer); }
public async Task GetCustomerByName_ExistingId_ReturnsCustomerWithoutOrders() { using (var context = new CustomersDbContext(_options)) { var repository = new CustomersRepository(context, _mapper); var result = (await repository.GetCustomersAsync("Elon Musk")).ToArray(); result.Should().NotBeEmpty(); result[0].Id.Should().BeGreaterThan(0); result[0].Name.Should().Be("Elon Musk"); result[0].Orders.Should().BeEmpty(); } }
public ActionResult CreatePostalAddressPartial(PostalAddressEditViewModel model) { if (ModelState.IsValid) { var repo = new CustomersRepository(); var updatedModel = repo.SavePostalAddress(model); if (updatedModel != null) { return(RedirectToAction("Edit", new { id = model.CustomerID })); } } return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); }
public ActionResult CreateEmailAddressPartial(EmailAddressViewModel model) { if (ModelState.IsValid) { var repo = new CustomersRepository(); bool saved = repo.SaveEmailAddress(model); if (saved) { return(RedirectToAction("Edit", new { id = model.CustomerID })); } } return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); }
public string GetCustomerName(string userName) { CustomersRepository rep = new CustomersRepository(); DataTable dt = rep.GetCustomers(); foreach (DataRow row in dt.Rows) { if (row["CustomerEmailAdress"].ToString() == userName) { return(row["CustomerName"].ToString()); } } return("UserNameNotExcist"); }
public IController CreateController(RequestContext requestContext, string controllerName) { if (controllerName.ToLower().StartsWith("customer")) { var repository = new CustomersRepository(); var controller = new CustomerController(repository); return(controller); } var defaultFactory = new DefaultControllerFactory(); return(defaultFactory.CreateController(requestContext, controllerName)); }
public async Task AddCustomer_WrongEmail_ThrowsException() { using (var context = new CustomersDbContext(_options)) { var customer = new CustomerDto() { Name = "Edward Stark", Email = "edward.stark.from.winterfell" }; var repository = new CustomersRepository(context, _mapper); Func <Task <CustomerDto> > result = async() => await repository.AddCustomerAsync(customer); await result.Should().ThrowAsync <Exception>(); } }
public async Task AddCustomer_ShortName_ThrowsException() { using (var context = new CustomersDbContext(_options)) { var customer = new CustomerDto() { Name = "Ed", Email = "*****@*****.**" }; var repository = new CustomersRepository(context, _mapper); Func <Task <CustomerDto> > result = async() => await repository.AddCustomerAsync(customer); await result.Should().ThrowAsync <Exception>(); } }
public ActionResult EditCustomerPartial(string id) { if (!String.IsNullOrWhiteSpace(id)) { bool isGuid = Guid.TryParse(id, out Guid customerId); if (isGuid && customerId != Guid.Empty) { var repo = new CustomersRepository(); var model = repo.GetCustomer(customerId); return(View(model)); } } return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); }
public ActionResult EditRent() { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); BooksRepository booksRepository = new BooksRepository(context); CustomersRepository customersRepository = new CustomersRepository(context); RentsEditRentVM model = new RentsEditRentVM(); model.Customers = customersRepository.GetAll(); model.Books = booksRepository.GetAll(); model.RentDate = DateTime.Now.Date; model.UserID = AuthenticationManager.LoggedUser.ID; return View(model); }
public async Task TestGetCustomerAsync() { var dbContext = DbContextMocker.GetContext(nameof(this.TestGetCustomerAsync)); var customersRepository = new CustomersRepository(dbContext); var customerService = new CustomersService(customersRepository, null); var controller = new CustomersController(customerService, AutoMapperConfiguration.ConfigureForWeb().CreateMapper()); var response = await controller.GetCustomer(1); var value = response.Value; dbContext.Dispose(); Assert.Equal("John Johnson", value.CustomerName); }
public IEnumerable <string> Validate() { var repoCustomer = new CustomersRepository(); if (repoCustomer.Get(IdCustomer) == null) { yield return($"Customer with id {IdCustomer} not found."); } if (!Content.Any()) { yield return($"An order cannot be empty."); } }
public void GetCustomerById() { Console.WriteLine("Please enter customer ID:"); var checkCustomerId = int.TryParse(Console.ReadLine(), out int customerId); CheckInput(checkCustomerId); var customer = CustomersRepository.GetById(customerId); if (customer == null) { throw new FlowException("Customer not found!"); } customer.PrintInfo(); }
protected void btnSendSMS_Click(object sender, EventArgs e) { List<vwSMS> rs = new List<vwSMS>(); if (!string.IsNullOrEmpty(txtReplyContent.Text.Trim()) || !string.IsNullOrEmpty(txtTitle.Text.Trim())) { ObjLogin adm = (ObjLogin)Session["objLogin"]; rs = repo.GetSMSById(Convert.ToInt32(Request.QueryString["ID"])); var result = rs.FirstOrDefault(); repo.InsertSMS(result.SMSCode, (int)result.Id, adm.Phone, Constant.CustomerType, txtPhoneNumber.Text, (int)result.SenderType, DateTime.Now, txtTitle.Text.Trim(), txtReplyContent.Text.Trim(), true, false, false, (int)result.SmsTypeId, (int)result.PromotionId); // Update UsedSms field of Customer var custRepo = new CustomersRepository(); custRepo.IncreaseCustomerUsedSms(adm.Id, 1); Response.Redirect("Default.aspx"); } }
public ActionResult EditCustomer(CustomersEditCustomerVM model) { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); CustomersRepository customersRepository = new CustomersRepository(context); ModelState.Remove("DateOut"); if (model.Email != null && customersRepository.GetAll().Any(c => c.Email == model.Email) && model.ID != customersRepository.GetAll(filter: c => c.Email == model.Email).FirstOrDefault().ID) { ModelState.AddModelError("Email", "* email already exists"); } if (!ModelState.IsValid) { return View(model); } else { Customer customer = null; if (model.ID > 0) { customer = customersRepository.GetByID(model.ID); customer.PersonalNumber = model.PersonalNumber; } else { customer = new Customer(); customer.PersonalNumber = customersRepository.GetAll().LastOrDefault().PersonalNumber + 1; } customer.ID = model.ID; customer.FirstName = model.FirstName; customer.LastName = model.LastName; customer.Email = model.Email; customer.Address = model.Address; customer.Birthday = model.Birthday; customer.DateIn = model.DateIn; customer.DateOut = model.DateOut != null ? model.DateOut : null; customersRepository.Save(customer); } return RedirectToAction("Index", "Customers"); }
public int GetPagesCount(Expression<Func<Customer, bool>> filter = null) { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); CustomersRepository customersRepository = new CustomersRepository(context); int pagesCount = 0; int pageSize = ApplicationConfiguration.ItemsPerPage; int customersCount = 0; customersCount = customersRepository.Count(filter); pagesCount = customersCount / pageSize; if ((customersCount % pageSize) > 0) { pagesCount++; } return pagesCount; }
public JsonResult GetCustomersNames() { var repository = new CustomersRepository(); var allItems = repository.GetAll().Select(c => c.CompanyName); return Json(new { Items = allItems }); }
public static CustomersRepository GetCustomersRepository(IUnitOfWork unitOfWork) { var repository = new CustomersRepository(); repository.UnitOfWork = unitOfWork; return repository; }
public ActionResult Index(string sortOrder) { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); CustomersRepository customersRepository = new CustomersRepository(context); CustomersIndexVM model = new CustomersIndexVM(); this.TryUpdateModel(model); model.CustomersPager = model.CustomersPager ?? new GenericPagerVM(); model.CustomersPager.CurrentPage = model.CustomersPager.CurrentPage == 0 ? 1 : model.CustomersPager.CurrentPage; model.CustomersPager.Action = "Index"; model.CustomersPager.Controller = "Customers"; model.CustomersPager.Prefix = "CustomersPager"; model.CustomersPager.CurrentParameters = new Dictionary<string, object>() { { "PersonaNumber", model.PersonalNumber }, { "CustomerName", model.CustomerName }, { "Email", model.Email }, { "Address", model.Address }, { "BirthdayStartDate", model.BirthdayStartDate }, { "BirthdayEndDate", model.BirthdayEndDate }, { "DateInStartDate", model.DateInStartDate }, { "DateInEndDate", model.DateInEndDate }, { "DateOutStartDate", model.DateOutStartDate }, { "DateOutEndDate", model.DateOutEndDate }, { "CustomersPager.CurrentPage", model.CustomersPager.CurrentPage } }; #region Sorting and Filtering Expression<Func<Customer, bool>> filter = c => (model.PersonalNumber == default(int) || c.PersonalNumber == model.PersonalNumber) && (string.IsNullOrEmpty(model.CustomerName) || (c.FirstName.Contains(model.CustomerName) || c.LastName.Contains(model.CustomerName))) && (string.IsNullOrEmpty(model.Email) || c.Email.Contains(model.Email)) && (string.IsNullOrEmpty(model.Address) || c.Address.Contains(model.Address)) && (model.BirthdayStartDate == default(DateTime) || (c.Birthday == model.BirthdayStartDate || (c.Birthday >= model.BirthdayStartDate && c.Birthday <= model.BirthdayEndDate))) && (model.DateInStartDate == default(DateTime) || (c.DateIn == model.DateInStartDate || (c.DateIn >= model.DateInStartDate && c.Birthday <= model.DateInEndDate))) && (model.DateOutStartDate == default(DateTime) || (c.DateOut == model.DateOutStartDate || (c.DateOut >= model.DateOutStartDate && c.Birthday <= model.DateOutEndDate))); model.CustomersPager.PagesCount = GetPagesCount(filter); ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.PersonalNumberSortParam = sortOrder == "PersonalNumber" ? "personalNumber_desc" : "PersonalNumber"; ViewBag.EmailSortParam = sortOrder == "Email" ? "email_desc" : "Email"; ViewBag.AddressSortParam = sortOrder == "Address" ? "address_desc" : "Address"; ViewBag.BirthdaySortParam = sortOrder == "Birthday" ? "birthday_desc" : "Birthday"; ViewBag.DateInSortParam = sortOrder == "DateIn" ? "dateIn_desc" : "DateIn"; ViewBag.DateOutSortParam = sortOrder == "DateOut" ? "dateOut_desc" : "DateOut"; switch (sortOrder) { case "name_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.FirstName)); break; case "PersonalNumber": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.PersonalNumber)); break; case "personalNumber_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.PersonalNumber)); break; case "Email": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Email)); break; case "email_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Email)); break; case "Address": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Address)); break; case "address_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Address)); break; case "Birthday": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Birthday)); break; case "birthday_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Birthday)); break; case "DateIn": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.DateIn)); break; case "dateIn_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.DateIn)); break; case "DateOut": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.DateOut)); break; case "dateOut_desc": model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.DateOut)); break; default: model.CustomersList = customersRepository .GetAll(model.CustomersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.FirstName)); break; } #endregion return View(model); }
public static CustomersRepository GetCustomersRepository() { var repository = new CustomersRepository(); repository.UnitOfWork = GetUnitOfWork(); return repository; }
protected void btnImport_Click(object sender, EventArgs e) { btnImport.Enabled = false; fuImport.Enabled = false; btnImport.Text = "Processing..."; if (!fuImport.HasFile) ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Chọn file để nhập');", true); else { string ext = fuImport.FileName.Substring(fuImport.FileName.LastIndexOf('.') + 1).ToLower(); if (!ext.Equals("xls") && !ext.Equals("xlsx")) ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Định dạng file nhập ko đúng');", true); else { string newFileName = Guid.NewGuid().ToString("N") + "." + ext; string pathToFile = Server.MapPath("~\\Import") + "\\" + newFileName; fuImport.SaveAs(pathToFile); try { ObjLogin adm = (ObjLogin)Session["objLogin"]; int smsquota = int.Parse(ConfigurationManager.AppSettings["SMSQuota"]); double expiredDateConfig = Convert.ToDouble(ConfigurationManager.AppSettings["ExpiredDate"]); DateTime expiredDate = Convert.ToDateTime(DateTime.Now.AddDays(expiredDateConfig)); var GRepo = new GroupsRepository(); var RegionRepo = new RegionsRepository(); var AreaRepo = new AreasRepository(); var LocalRepo = new LocalsRepository(); var ChRepo = new ChannelRepository(); var SaleRepo = new SalesmanRepository(); var CLogRepo = new CustomersLogRepository(); var CRepo = new CustomersRepository(); var CTRepo = new CustomerTypeRepository(); var DisRepo = new DistrictsRepository(); var proviceRepo = new ProvincesRepository(); var sectionRepo = new SectionRepository(); SpreadsheetInfo.SetLicense("E24D-D739-F65A-4E00"); ExcelFile ef = new ExcelFile(); ef.LoadXls(pathToFile); ExcelWorksheet ws = ef.Worksheets[0]; for (int i = 2; i < ws.Rows.Count; i++) { try { vwMasterList vmMasterItem = new vwMasterList(ws.Rows[i].Cells[4].Value.ToString(), ws.Rows[i].Cells[5].Value.ToString(), ws.Rows[i].Cells[6].Value.ToString(), ws.Rows[i].Cells[7].Value.ToString(), ws.Rows[i].Cells[8].Value.ToString(), ws.Rows[i].Cells[9].Value.ToString(), ws.Rows[i].Cells[10].Value.ToString(), ws.Rows[i].Cells[11].Value.ToString(), ws.Rows[i].Cells[12].Value.ToString(), ws.Rows[i].Cells[13].Value.ToString(), ws.Rows[i].Cells[14].Value.ToString(), ws.Rows[i].Cells[15].Value.ToString(), ws.Rows[i].Cells[17].Value.ToString(), ws.Rows[i].Cells[18].Value.ToString(), ws.Rows[i].Cells[19].Value.ToString(), ws.Rows[i].Cells[20].Value.ToString(), ws.Rows[i].Cells[22].Value.ToString(), ws.Rows[i].Cells[23].Value.ToString(), ws.Rows[i].Cells[24].Value.ToString()); // Add Group - Region - Area - Local var groupId = GRepo.Import("", vmMasterItem.Group, ""); var regionId = RegionRepo.Import("", vmMasterItem.Region, "", groupId); var areaId = AreaRepo.Import("", vmMasterItem.Area, "", regionId); var localId = LocalRepo.Import("", vmMasterItem.Local, "", areaId); // Add section var sectionId = sectionRepo.Import(vmMasterItem.Area); // Add Province var provinceId = proviceRepo.Import(vmMasterItem.Local, sectionId); // Add District var districtId = DisRepo.Import(vmMasterItem.Local, provinceId); // Add Channel ChRepo.Insert("", vmMasterItem.Channel1, 0); ChRepo.Insert("", vmMasterItem.Channel2, ChRepo.GetChannelIdByName(vmMasterItem.Channel1)); ChRepo.Insert("", vmMasterItem.Channel3, ChRepo.GetChannelIdByName(vmMasterItem.Channel2)); // Add Customer Type CTRepo.Add("", vmMasterItem.Channel3); // Add Salesmen var tromId = SaleRepo.ImportSalesmen("", vmMasterItem.TROM, "", (int)SalesmenRole.TROM, smsquota, expiredDate, -1); var tpsId = SaleRepo.ImportSalesmen("", vmMasterItem.TPS, "", (int)SalesmenRole.TPS, smsquota, expiredDate, tromId); var tprId = SaleRepo.ImportSalesmen("", vmMasterItem.TPR, "", (int)SalesmenRole.TPR, smsquota, expiredDate, tpsId); var eromId = SaleRepo.ImportSalesmen("", vmMasterItem.EROM, "", (int)SalesmenRole.EROM, smsquota, expiredDate, -1); var pss1Id = SaleRepo.ImportSalesmen("", vmMasterItem.PSS1, "", (int)SalesmenRole.PSS1, smsquota, expiredDate, eromId); var psr1Id = SaleRepo.ImportSalesmen("", vmMasterItem.PSR1, "", (int)SalesmenRole.PSR1, smsquota, expiredDate, pss1Id); var erom2Id = SaleRepo.ImportSalesmen("", vmMasterItem.EROM2, "", (int)SalesmenRole.EROM2, smsquota, expiredDate, -1); var pss2Id = SaleRepo.ImportSalesmen("", vmMasterItem.PSS2, "", (int)SalesmenRole.PSS2, smsquota, expiredDate, erom2Id); var psr2Id = SaleRepo.ImportSalesmen("", vmMasterItem.PSR2, "", (int)SalesmenRole.PSR2, smsquota, expiredDate, pss2Id); // Add Salesgroup - salesregion - salesarea - saleslocal ImportSalesGroup(tromId, tpsId, tprId, eromId, pss1Id, psr1Id, erom2Id, pss2Id, psr2Id, GRepo, groupId); ImportSalesRegion(tromId, tpsId, tprId, eromId, pss1Id, psr1Id, erom2Id, pss2Id, psr2Id, RegionRepo, regionId); ImportSalesArea(tromId, tpsId, tprId, eromId, pss1Id, psr1Id, erom2Id, pss2Id, psr2Id, AreaRepo, areaId); ImportSalesLocal(tromId, tpsId, tprId, eromId, pss1Id, psr1Id, erom2Id, pss2Id, psr2Id, LocalRepo, localId); // Add Customer - Customer Log int CustomerId = CRepo.InsertCustomer(vmMasterItem.CustomerCode, vmMasterItem.Customername, vmMasterItem.Customeraddress, "", "", "", "", CTRepo.GetCustomerTypeIdByName(vmMasterItem.Channel3), ChRepo.GetChannelIdByName(vmMasterItem.Channel3), districtId, localId, DateTime.Now, DateTime.Now, true, false); CLogRepo.InsertCustomer(vmMasterItem.CustomerCode, vmMasterItem.Customername, vmMasterItem.Customeraddress, "", "", "", "", CTRepo.GetCustomerTypeIdByName(vmMasterItem.Channel3), ChRepo.GetChannelIdByName(vmMasterItem.Channel3), districtId, localId, DateTime.Now, DateTime.Now, true, CustomerId, false, 0, adm.Id, string.Empty); lstCustomer.Add(vmMasterItem); } catch (Exception ex) { // write log here => TBD } } CustomerList.DataSource = lstCustomer; CustomerList.DataBind(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('" + ex.Message + "');", true); } finally { } } } btnImport.Enabled = true; fuImport.Enabled = true; btnImport.Text = "Import"; }
public ActionResult EditRent(string customerInfo, string bookInfo, RentsEditRentVM model) { LibraryManagementSystemContext context = new LibraryManagementSystemContext(); RentsRepository rentsRepository = new RentsRepository(context); BooksRepository booksRepository = new BooksRepository(context); CustomersRepository customersRepository = new CustomersRepository(context); // makes an customer info array in format {Personal No.}{Empty}{Empty}{First name}{Last name} string[] customerInfoSplitted = customerInfo.Split(' ', '-'); // makes an book info array in format {Barcode No.}{Empty}{Empty}{Book title} string[] bookInfoSplitted = bookInfo.Split(' ', '-'); if (string.IsNullOrEmpty(customerInfo) || customerInfoSplitted[0] == "") { ModelState.AddModelError("CustomerPersonalNumber", "* personal No. required"); } if (string.IsNullOrEmpty(bookInfo) || bookInfoSplitted[0] == "") { ModelState.AddModelError("BookBarcodeNumber", "* barcode required"); } if (!ModelState.IsValid) { if (model.ID <= 0) { model.RentDate = DateTime.Now; } model.Customers = customersRepository.GetAll(); model.Books = booksRepository.GetAll(); return View(model); } model.CustomerPersonalNumber = int.Parse(customerInfoSplitted[0]); model.Customer = customersRepository .GetAll(filter: c => c.PersonalNumber == model.CustomerPersonalNumber) .FirstOrDefault(); model.BookBarcodeNumber = int.Parse(bookInfoSplitted[0]); model.Books = booksRepository .GetAll(filter: b => b.Barcodes.Any(bc => bc.BarcodeNumber == model.BookBarcodeNumber)); if (model.Books.Any(b => b.StockCount > 0)) { Rent rent = new Rent(); rent.Books = new List<Book>(); rent.Books = model.Books; rent.Books.FirstOrDefault().StockCount--; rent.DateToReturn = DateTime.Now.AddMonths(1); rent.RentDate = model.RentDate; rent.UserID = model.UserID; rent.CustomerID = model.Customer.ID; rentsRepository.Save(rent); } else { ModelState.AddModelError("BookBarcodeNumber", "* book not in stock at the moment"); if (model.ID <= 0) { model.RentDate = DateTime.Now; } model.Customers = customersRepository.GetAll(); model.Books = booksRepository.GetAll(); return View(model); } return RedirectToAction("Index", "Rents"); }