public static CustomerLocationDto ToDto(this CustomerLocation customerLocation) => new CustomerLocationDto { CustomerLocationId = customerLocation.CustomerLocationId, Name = customerLocation.Name, Version = customerLocation.Version };
public async Task <bool> AddNewLocation(Customer customer, Location location) { try { Location tmp = await Entity.GetLocationByName(location.Name); if (tmp != null) { CustomerLocation cl = new CustomerLocation() { Customer = customer, Location = tmp }; await CustomerLocationEntity.AddNewCustomerLocation(cl); } else { await Entity.AddNewLocation(location); CustomerLocation cl = new CustomerLocation() { Customer = customer, Location = location }; await CustomerLocationEntity.AddNewCustomerLocation(cl); } return(true); } catch (Exception e) { return(false); } }
public CustomerLocation ToCustomerLocation(CustomerLocation customerLocation = null) { if (customerLocation == null) { customerLocation = new CustomerLocation { OrderDetail = new Collection <OrderDetail>() } } ; customerLocation.Address1 = Address1; customerLocation.Address2 = Address2; customerLocation.City = City; customerLocation.Fax = Fax; customerLocation.IsBillTo = IsBillTo; customerLocation.IsShipTo = IsShipTo; customerLocation.Name = Name; customerLocation.ShortName = ShortName; customerLocation.Phone = Phone; customerLocation.StateCode = StateCode; customerLocation.ZipCode = ZipCode; customerLocation.Email = Email; return(customerLocation); } }
//Update House Owner Location public CustomerLocation UpdateLocation(CustomerLocation customerLocation) { using (var dbContext = new OmContext()) { try { var customer = dbContext.Customers.FirstOrDefault(h => h.UserId == customerLocation.UserId); var address = dbContext.Addresses.First(a => a.AddressId == customer.AddressId); address.Latitude = customerLocation.Latitude; address.Longitude = customerLocation.Longitude; dbContext.SaveChanges(); return(new CustomerLocation() { UserId = customer.UserId, Latitude = address.Latitude, Longitude = address.Longitude } ); } catch (Exception ex) { return(null); } } }
public async Task <bool> DeleteLocation(Customer customer, Location location) { try { IEnumerable <CustomerLocation> enumerable = customer.CustomerLocations; CustomerLocation del = null; if (enumerable != null) { foreach (CustomerLocation cl in enumerable) { if (location.Id == cl.Location.Id) { del = cl; break; } } } if (del != null) { await CustomerLocationEntity.DeleteCustomerLocation(del); } return(true); } catch (Exception e) { return(false); } }
public void FindCustomersWhoAreAtTheDesiredDistance() { var customerLocation1 = new CustomerLocation(new Customer(12, "foo"), new Location(60, 124)); var customerLocation2 = new CustomerLocation(new Customer(13, "bar"), new Location(62, 125)); var customerLocation3 = new CustomerLocation(new Customer(14, "foobar"), new Location(70, 126)); var customerLocations = new List <CustomerLocation> { customerLocation1, customerLocation2, customerLocation3 }; var configuration = new Mock <Configuration>(); configuration.Setup(x => x.MaxDistance).Returns(20); customerFinder.LocationReaderMock.Setup(x => x.Read(It.IsAny <string>())).Returns(customerLocations); customerFinder.DistanceCalculatorMock.Setup(x => x.GetBoundingRectangle(20, It.IsAny <Location>())).Returns(new BoundingRectangle(new Location(-90, -180), new Location(90, 180))); customerFinder.DistanceCalculatorMock.Setup(x => x.CalculateDistanceAsKm(customerLocation1.Location, configuration.Object.OfficeLocation)).Returns(configuration.Object.MaxDistance - 10); customerFinder.DistanceCalculatorMock.Setup(x => x.CalculateDistanceAsKm(customerLocation2.Location, configuration.Object.OfficeLocation)).Returns(configuration.Object.MaxDistance + 10); customerFinder.DistanceCalculatorMock.Setup(x => x.CalculateDistanceAsKm(customerLocation3.Location, configuration.Object.OfficeLocation)).Returns(configuration.Object.MaxDistance - 5); var customers = customerFinder.Find(configuration.Object); Assert.NotNull(customers); Assert.Equal(2, customers.Count()); Assert.DoesNotContain(customers, x => x.Id == customerLocation2.Customer.Id); }
public TResponse UpdateStatus(int ID, bool Status) { using (var db = new UnitOfWork()) { try { CustomerLocation objCustomerLocation = db.CustomerLocationRepository.GetById(ID); if (objCustomerLocation != null && objCustomerLocation.ID > 0) { objCustomerLocation.IsActive = Status; db.CustomerLocationRepository.Update(objCustomerLocation); } objTResponse.Status = ResponseStaus.ok; objTResponse.Message = ResponseMessage.success; } catch (Exception ex) { ErrorLogBusiness objerrorlog = new ErrorLogBusiness(); objerrorlog.AddErrorLog(new ErrorLogModel { MethodName = "DeleteCustomerLocation", Id = 0, ClassName = "CustomerLocationBusiness", Error = ex.Message }); return(objTResponse); } return(objTResponse); } }
//Create Customer public void CreateCustomer(Customer customer) { _logger.LogInformation($"Creating new customer"); _dbContext.Customer.Add(customer); if (customer.Member.MemberEmail.Any() && customer.Member.MemberPassword.Any()) { MemberDTO memberDTO = new MemberDTO() { CustomerEmail = customer.Member.MemberEmail, CustomerPassword = customer.Member.MemberPassword }; _dbContext.SaveChanges(); } if (customer.Location.Any()) { foreach (var location in customer.Location) { CustomerLocation customerLocation = new CustomerLocation { City = location.CityName, Address = location.AddressName }; _dbContext.SaveChanges(); } } }
public ActionResult DeleteConfirmed(int id) { CustomerLocation customerLocation = db.CustomerLocations.Find(id); db.CustomerLocations.Remove(customerLocation); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// </summary> /// <param name="customerId"></param> /// <returns></returns> public CustomerLocationDTO GetHeadOffice(int customerId) { var customerLocation = new CustomerLocation(); customerLocation = _unitOfWork.CustomerLocations.GetHeadOffice(customerId); var customerLocationDTO = AutoMapper.Mapper.Map <CustomerLocationDTO>(customerLocation); return(customerLocationDTO); }
public ActionResult Edit([Bind(Include = "Id,City,ZipCode,State,CountryID,Latitude,Longitude,IntervensionZone,Radius")] CustomerLocation customerLocation) { if (ModelState.IsValid) { db.Entry(customerLocation).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(customerLocation)); }
public void Save(CustomerLocation location) { using var tx = _db.CreateTransaction(); _db.Insert("CustomerLocations", tx, new Dictionary <string, object> { { nameof(CustomerLocation.Id), location.Id }, { nameof(CustomerLocation.Latitude), location.Latitude }, { nameof(CustomerLocation.Longitude), location.Longitude }, { "CustomerId", location.Customer.Id } }); tx.Commit(); }
// GET: CustomerLocations/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CustomerLocation customerLocation = db.CustomerLocations.Find(id); if (customerLocation == null) { return(HttpNotFound()); } return(View(customerLocation)); }
public static void GenerateProductionManifestDetail(Order order, IEnumerable <Label> labels, string fileName, CustomerLocation location, string reportType, UnitsType unitsType = UnitsType.Boxes, bool suppressWeight = false) { var items = labels.Where(c => (int)c.TypeId == (int)unitsType).GroupBy(x => x.SerialNumber) .Select(x => new ProductDetailItem { ProductDescription = x.First().Description, SpeciesName = x.First().Species, ProductCode = x.First().ItemCode, Date = x.First().ProcessDate, WeightKg = suppressWeight ? 0 : Convert.ToDecimal(LbsToKg(GetNetWeight(x.First()))), WeightLbs = suppressWeight ? 0 : Convert.ToDecimal(GetNetWeight(x.First())) }) .ToList(); var model = new ProductionManifestDetailModel { SlaughterDate = order.SlaughterDate, Company = order.Customer.Name, PoNumber = order.Id.ToString(CultureInfo.InvariantCulture), ShipTo = location.Name, FileName = fileName, }; Action <Telerik.Reporting.Report> fill = rep => { rep.DataSource = items; rep.ReportParameters["Logo"].Value = GetLogo(order); rep.ReportParameters["PONumber"].Value = model.PoNumber; rep.ReportParameters["SubCaption"].Value = model.SubCaption; rep.ReportParameters["CustomerPO"].Value = GetCustomerPO(order); }; Telerik.Reporting.Report report; if (suppressWeight) { report = new ProductionManifestDetailSuppressWeight(); } else { report = new ProductionManifestDetail(); } fill(report); report.CreateReport(model.FileName, reportType); }
//The CustomerLocationValidator method checks if there is a CustomerLocation that already exists in the CustomerLocation Table //to prevent duplicate CustomerLocations from being added to the Table. As well, this server side validation ensures that an //address is being updated in the Edit CustomerLocation View. private void CustomerLocationValidator(CustomerLocation customerLocation) { //Check if there are any ModelState errors for the Address or CustomerId fields. if (ModelState.IsValidField("CustomerLocation.Address") && ModelState.IsValidField("CustomerLocation.CustomerId")) { //Check to see if there is a Combination of an Address and CustomerId in the CustomerLocation Table. if (Context.CustomerLocations .Any(cl => cl.CustomerId == customerLocation.CustomerId && cl.Address == customerLocation.Address)) { //Add a ModelState Error to the Name field so that it can be displayed in the ValidationSummary //in the Add CustomerLocation or Edit View. ModelState.AddModelError("CustomerLocation.Address", "This address already exists for this customer," + " or you have tried to edit an address and have not made any changes!"); } } }
public CustomerLocationViewModel(CustomerLocation customerLocation) { Address1 = customerLocation.Address1; Address2 = customerLocation.Address2; City = customerLocation.City; Fax = customerLocation.Fax; IsBillTo = customerLocation.IsBillTo; IsShipTo = customerLocation.IsShipTo; Name = customerLocation.Name; ShortName = customerLocation.ShortName; Phone = customerLocation.Phone; StateCode = customerLocation.StateCode; ZipCode = customerLocation.ZipCode; CustomerId = customerLocation.CustomerId; LocationId = customerLocation.Id; Email = customerLocation.Email; }
private CustomerLocation ApplyChanges(CustomerLocationModel model) { var cl = new CustomerLocation(); cl.CustomerLocationID = model.CustomerLocationID; cl.CustomerLocationName = model.CustomerLocationName; cl.CustomerID = model.CustomerID; cl.TelephoneNumber = model.Telephone; cl.FaxNumber = model.FaxNumber; cl.CreatedDate = !string.IsNullOrEmpty(model.CreatedDate) ? DateTime.Parse(model.CreatedDate) : DateTime.Now; cl.CreatedBy = _principal.Id; cl.UpdatedDate = DateTime.Now; cl.UpdatedBy = _principal.Id; cl.IsActive = true; return(cl); }
public TResponse GetByID(long Id) { using (var db = new UnitOfWork()) { try { CustomerLocationModel objCustomerLocationModel = new CustomerLocationModel(); CustomerLocation objCustomerLocation = db.CustomerLocationRepository.Get(x => x.ID == Id).FirstOrDefault(); if (objCustomerLocation != null) { objCustomerLocationModel.ID = objCustomerLocation.ID; objCustomerLocationModel.CustomerID = Convert.ToInt64(objCustomerLocation.CustomerID); objCustomerLocationModel.CustomerName = objCustomerLocation.UserProfile.FName + " " + objCustomerLocation.UserProfile.FName; objCustomerLocationModel.Location = objCustomerLocation.Location; objCustomerLocationModel.LocationName = objCustomerLocation.LocationName; objCustomerLocationModel.IsActive = Convert.ToBoolean(objCustomerLocation.IsActive); objCustomerLocationModel.IsDeleted = Convert.ToBoolean(objCustomerLocation.IsDeleted); objCustomerLocationModel.CreatedOn = Convert.ToDateTime(objCustomerLocation.CreatedOn); objCustomerLocationModel.UpdatedOn = Convert.ToDateTime(objCustomerLocation.UpdatedOn); objTResponse.Status = ResponseStaus.ok; objTResponse.Message = ResponseMessage.success; objTResponse.ResponsePacket = objCustomerLocationModel; } else { objTResponse.Status = ResponseStaus.error; objTResponse.Message = ResponseMessage.ItemNotFound; objTResponse.ResponsePacket = null; } return(objTResponse); } catch (DbEntityValidationException dbEx) { ErrorLogBusiness objerrorlog = new ErrorLogBusiness(); objerrorlog.AddErrorLog(new ErrorLogModel { MethodName = "GetByID", Id = Id, ClassName = "CustomerLocationBusiness", Error = dbEx.Message }); return(objTResponse); } } }
public static void GenerateShippingManifest(Order order, IEnumerable <OrderDetail> details, string fileName, CustomerLocation location, string reportType, UnitsType unitsType = UnitsType.Boxes, bool suppressWeight = false) { var items = GetProductItems(details, unitsType, suppressWeight); var model = new ShippingManifestModel { SlaughterDate = order.SlaughterDate, OrderNumber = order.Id.ToString(CultureInfo.InvariantCulture), SubCaption = order.Customer.GetFormattedAddress(), FileName = fileName, Company = order.Customer.Name, ShipTo = location.Name, }; Action <Telerik.Reporting.Report> fill = rep => { rep.DataSource = items; rep.ReportParameters["Date"].Value = model.Date; rep.ReportParameters["OrderNumber"].Value = model.OrderNumber; rep.ReportParameters["SubCaption"].Value = model.SubCaption; rep.ReportParameters["TopCaption"].Value = model.TopCaption; rep.ReportParameters["Logo"].Value = GetLogo(order); rep.ReportParameters["CustomerPO"].Value = GetCustomerPO(order); }; Telerik.Reporting.Report report; if (suppressWeight) { report = new ShippingManifestSuppressWeight(); } else { report = new ShippingManifest(); } fill(report); report.CreateReport(model.FileName, reportType); }
protected override void Seed(LawnPaynesContext context) { var customer1 = new Customer() { CustomerId = 1, Name = "John Doe", IsNew = false, PhoneNumber = "(345) 678-1234", Email = "*****@*****.**", Comments = "Test a comment!" }; var customer2 = new Customer() { CustomerId = 2, Name = "Jane Doe", IsNew = true, PhoneNumber = "(800) 123-4567", Email = "*****@*****.**", Comments = "Test a comment again!" }; var customer3 = new Customer() { CustomerId = 3, Name = "Ryan Sallee", IsNew = false, PhoneNumber = "(502) 111-2222", Email = "*****@*****.**", Comments = "Visit weekly." }; context.Customers.AddOrUpdate(customer1, customer2, customer3); var customerLocation1 = new CustomerLocation() { CustomerLocationId = 1, Address = "1333 Jones St, Louisville, KY 40218", CustomerId = 1 }; var customerLocation2 = new CustomerLocation() { CustomerLocationId = 2, Address = "5200 Indian Trl, Louisville, KY 40218", CustomerId = 3 }; context.CustomerLocations.AddOrUpdate(customerLocation1, customerLocation2); var service1 = new Service() { ServiceId = 1, ServiceName = "Cut" }; var service2 = new Service() { ServiceId = 2, ServiceName = "Trim" }; var service3 = new Service() { ServiceId = 3, ServiceName = "Landscaping" }; context.Services.AddOrUpdate(service1, service2, service3); var serviceCustomerLocation1 = new ServiceCustomerLocation() { CustomerLocationId = 2, ServiceId = 1 }; var serviceCustomerLocation2 = new ServiceCustomerLocation() { CustomerLocationId = 2, ServiceId = 2 }; var serviceCustomerLocation3 = new ServiceCustomerLocation() { CustomerLocationId = 1, ServiceId = 2 }; context.ServiceCustomerLocations.AddOrUpdate(serviceCustomerLocation1, serviceCustomerLocation2, serviceCustomerLocation3); }
public BookStoreB(CustomerLocation location) { this.location = location; }
public List <Tuple <Guid, IList <CustomerLocation> > > AddNewLocation(CustomerLocation item) { return(repository.AddNewLocation(item)); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var customer = await _context.Customers.FindAsync(request.Customer.CustomerId); if (customer == null) { if (await _context.Customers.AnyAsync(x => x.Email == request.Customer.Email)) { throw new CustomerExistsWithEmailException(); } if (!request.AcceptedTermsAndConditions) { throw new CustomerFailedToAcceptTermsAndConditionsException(); } customer = new Customer(); customer.CustomerTermsAndConditions.Add(new CustomerTermsAndConditions { Accepted = DateTime.UtcNow }); customer.RaiseDomainEvent(new CustomerCreated(customer)); _context.Customers.Add(customer); } customer.FirstName = request.Customer.FirstName; customer.LastName = request.Customer.LastName; customer.PhoneNumber = request.Customer.PhoneNumber; customer.Email = request.Customer.Email; if (request.Customer.Address != null) { customer.Address = new Address( request.Customer.Address.Street, request.Customer.Address.City, request.Customer.Address.Province, request.Customer.Address.PostalCode); } customer.CustomerLocations.Clear(); foreach (var customerLocationDto in request.Customer.CustomerLocations) { var customerLocation = await _context.CustomerLocations.FindAsync(customerLocationDto.CustomerLocationId); if (customerLocation == null) { customerLocation = new CustomerLocation(); } customerLocation.Location = await _context.Locations.FindAsync(customerLocationDto.LocationId); if (customerLocation.Location == null) { customerLocation.Location = new Location(); } customerLocation.Name = customerLocationDto.Name; customerLocation.Location = new Location(); customerLocation.LocationId = customerLocationDto.LocationId; customerLocation.Location.Type = customerLocationDto.Location.Type; customerLocation.Location.Adddress = new Address( customerLocationDto.Location.Address.Street, customerLocationDto.Location.Address.City, customerLocationDto.Location.Address.Province, customerLocationDto.Location.Address.PostalCode); customer.CustomerLocations.Add(customerLocation); } await _context.SaveChangesAsync(cancellationToken); var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == customer.Email); if (user == null) { user = new User { Username = customer.Email }; //TODO: Make random passwords user.Password = _passwordHasher.HashPassword(user.Salt, "P@ssw0rd"); await _context.Users.AddAsync(user); } user.Profiles.Add(new Profile { Name = $"{customer.FirstName} {customer.LastName}", Type = ProfileType.Customer }); await _context.SaveChangesAsync(cancellationToken); return(new Response() { CustomerId = customer.CustomerId, Version = customer.Version, AccessToken = _securityTokenFactory.Create(user.Username, new List <Claim>() { new Claim("UserId", $"{user.UserId}"), new Claim("PartitionKey", $"{user.TenantId}"), new Claim($"{nameof(customer.CustomerId)}", $"{customer.CustomerId}"), new Claim(ClaimTypes.Role, nameof(ProfileType.Customer)), new Claim("CurrentUserName", $"{user.Username}") }) }); }
public async Task DeleteCustomerLocation(CustomerLocation customerLocation) { CustomerLocations.Remove(customerLocation); await _context.SaveChangesAsync(); }
public async Task AddNewCustomerLocation(CustomerLocation customerLocation) { await CustomerLocations.AddAsync(customerLocation); await _context.SaveChangesAsync(); }
public BookStoreA(CustomerLocation location) { this._location = location; }
public dynamic MassLoad(HttpPostedFileBase dealers) { PartStates state = new PartStates(); List<string> errors = new List<string>(); try { CurtDevDataContext db = new CurtDevDataContext(); string dir_path = Server.MapPath("/Content/locator_csv"); GoogleMaps map = new GoogleMaps(System.Configuration.ConfigurationManager.AppSettings["GoogleMapsKey"]); DirectoryInfo dir_info = new DirectoryInfo(dir_path); int file_count = dir_info.GetFiles().Count(); string file_path = Server.MapPath("/Content/locator_csv/" + (file_count + 1) + ".xlsx"); dealers.SaveAs(file_path); FileInfo existingFile = new FileInfo(file_path); using (ExcelPackage package = new ExcelPackage(existingFile)) { // get the first worksheet in the workbook ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; int row = 2; //The first row with data while (worksheet.Cells[row, 2].Value != null) { // col 1 = Customer ID Code // col 2 = Customer Name // col 3 = Website // col 4 = Location Name // col 5 = Contact First Name // col 6 = Contact Last Name // col 7 = phone // col 8 = street // col 9 = city // col 10 = state // col 11 = zip // col 12 = sales rep // col 13 = Dealer Tier // col 14 = Dealer Type // col 15 = Parent curt acct # (meaning a third party client) try { int acctnum = (worksheet.Cells[row, 1].Value != null) ? Convert.ToInt32(worksheet.Cells[row, 1].Value) : 0; string rep = (worksheet.Cells[row, 12].Value != null) ? worksheet.Cells[row, 12].Value.ToString() : ""; string dtier = worksheet.Cells[row, 13].Value.ToString().Trim().ToLower(); string dtype = worksheet.Cells[row, 14].Value.ToString().Trim().ToLower(); string customername = (worksheet.Cells[row, 2].Value != null) ? worksheet.Cells[row, 2].Value.ToString() : ""; string locationname = (worksheet.Cells[row, 4].Value != null) ? worksheet.Cells[row, 4].Value.ToString() : ""; string contact = ((worksheet.Cells[row, 5].Value != null) ? worksheet.Cells[row, 5].Value.ToString() : "") + ((worksheet.Cells[row, 6].Value != null) ? " " + worksheet.Cells[row, 6].Value.ToString() : ""); string website = (worksheet.Cells[row, 3].Value != null) ? worksheet.Cells[row, 3].Value.ToString().Trim() : null; string statestr = (worksheet.Cells[row, 10].Value != null) ? worksheet.Cells[row, 10].Value.ToString() : ""; string postalCode = (worksheet.Cells[row, 11].Value != null) ? worksheet.Cells[row, 11].Value.ToString() : ""; string address = (worksheet.Cells[row, 8].Value != null) ? worksheet.Cells[row, 8].Value.ToString() : ""; string city = (worksheet.Cells[row, 9].Value != null) ? worksheet.Cells[row, 9].Value.ToString() : ""; string phone = (worksheet.Cells[row, 7].Value != null) ? worksheet.Cells[row, 7].Value.ToString() : ""; string parentacct = (worksheet.Cells[row, 15].Value != null) ? worksheet.Cells[row, 15].Value.ToString() : ""; int stateid = db.PartStates.Where(x => x.abbr.ToLower().Trim() == statestr.ToLower().Trim()).Select(x => x.stateID).FirstOrDefault(); LatLng geo = map.GetLatLng(address, city, stateid); double latitude = Convert.ToDouble(geo.latitude); double longitude = Convert.ToDouble(geo.longitude); SalesRepresentative salesrep = db.SalesRepresentatives.Where(x => x.name.ToLower().Trim().Equals(rep.Trim().ToLower())).FirstOrDefault<SalesRepresentative>(); DealerType type = db.DealerTypes.Where(x => x.type.Trim().ToLower() == dtype).First(); DealerTier tier = db.DealerTiers.Where(x => x.tier.Trim().ToLower() == dtier).First(); Customer customer = new Customer(); if (acctnum != 0) { customer = (from c in db.Customers join d in db.DealerTypes on c.dealer_type equals d.dealer_type where c.customerID.Equals(acctnum) && d.online.Equals(type.online) select c).FirstOrDefault<Customer>(); } else { customer = (from c in db.Customers join d in db.DealerTypes on c.dealer_type equals d.dealer_type where c.name.ToLower().Equals(customername.Trim().ToLower()) && d.online.Equals(type.online) && c.parentID.Equals(Convert.ToInt32(parentacct)) select c).FirstOrDefault<Customer>(); } if (customer == null) { // new customer Customer new_customer = new Customer { name = customername, contact_person = contact, tier = tier.ID, dealer_type = type.dealer_type, }; if (salesrep != null && salesrep.salesRepID != 0) { new_customer.salesRepID = salesrep.salesRepID; } if (acctnum != 0) { new_customer.customerID = acctnum; } if (parentacct.Trim() != "") { new_customer.parentID = Convert.ToInt32(parentacct); } if (website != "") { new_customer.website = website; } db.Customers.InsertOnSubmit(new_customer); db.SubmitChanges(); if (address != "" && city != "" && postalCode != "") { CustomerLocation location = new CustomerLocation { cust_id = new_customer.cust_id, name = locationname, address = address, city = city, postalCode = postalCode, phone = phone, contact_person = contact, latitude = latitude, longitude = longitude, isprimary = true }; if (stateid != 0) { location.stateID = stateid; } db.CustomerLocations.InsertOnSubmit(location); } db.SubmitChanges(); } else { if (parentacct.Trim() != "") { customer.parentID = Convert.ToInt32(parentacct); } // prior customer // check for location customer.dealer_type = type.dealer_type; customer.tier = tier.ID; if (salesrep != null && salesrep.salesRepID != 0) { customer.salesRepID = salesrep.salesRepID; } CustomerLocation location = db.CustomerLocations.Where(x => x.address.ToLower() == address.ToLower() && x.postalCode.Trim() == postalCode.Trim() && x.cust_id.Equals(customer.cust_id)).FirstOrDefault<CustomerLocation>(); if (location == null) { CustomerLocation new_location = new CustomerLocation { cust_id = customer.cust_id, name = locationname, address = address, city = city, postalCode = postalCode, phone = phone, latitude = latitude, longitude = longitude, contact_person = contact }; if (stateid != 0) { new_location.stateID = stateid; } db.CustomerLocations.InsertOnSubmit(new_location); db.SubmitChanges(); } else { // update location location.contact_person = contact; location.name = locationname; location.city = city; location.phone = phone; location.postalCode = postalCode; location.latitude = latitude; location.longitude = longitude; db.SubmitChanges(); } } } catch (Exception e) { errors.Add(row + ": " + e.Message); } row++; } } if (errors.Count == 0) { return RedirectToAction("Index", new { msg = "Customer Import Successful" }); } else { return RedirectToAction("MassUpload", new { msg = "There were some errors", errors = errors }); } } catch (Exception e) { return RedirectToAction("MassUpload", new { msg = e.Message }); } }
private void SeedCustomers(ApplicationDbContext context, string createdByUserId) { _clientCustomers.Add(new List <int>()); //empty, just to have 1 based indexes _clientCustomers.Add(new List <int>()); //clientId 1 _clientCustomers.Add(new List <int>()); //clientId 2 for (int i = 0; i < 10; i++) { var customer = new Customer() { Name = $"Customer {i}", MemberNumber = $"ABC-123-{i}", CreatedByUserId = createdByUserId, CreatedDate = DateTime.UtcNow, Status = Status.Active, }; context.Customers.AddOrUpdate(customer); context.SaveChanges(); var customerHistory = new CustomerHistory() { CustomerId = customer.Id, Name = $"Customer {i}", MemberNumber = $"ABC-123-{i}", ModifiedByUserId = createdByUserId, ModifiedDate = customer.CreatedDate, Status = Status.Active, }; context.CustomersHistory.AddOrUpdate(customerHistory); var customerLocation = new CustomerLocation() { CustomerId = customer.Id, Name = "Head Office Location " + customer.Id, Type = LocationType.HeadOffice, CreatedByUserId = createdByUserId, CreatedDate = customer.CreatedDate, Province = "AB", Country = "Canada", Status = Status.Active, }; context.CustomerLocations.AddOrUpdate(customerLocation); context.SaveChanges(); _customerHeadOffice.Add(customer.Id, customerLocation.Id); var customerLocationHistory = new CustomerLocationHistory() { CustomerLocationId = customerLocation.Id, CustomerId = customer.Id, Name = customerLocation.Name, Type = LocationType.HeadOffice, ModifiedByUserId = createdByUserId, ModifiedDate = customer.CreatedDate, Province = "AB", Country = "Canada", Status = Status.Active, }; context.CustomerLocationsHistory.AddOrUpdate(customerLocationHistory); Random rnd = new Random(); var clientCustomer = new ClientCustomer() { ClientId = rnd.Next(1, 3), CustomerId = customer.Id, CreatedByUserId = createdByUserId, CreatedDate = customer.CreatedDate, Status = Status.Active, }; context.ClientCustomers.AddOrUpdate(clientCustomer); var clientCustomerHistory = new ClientCustomerHistory() { ClientId = rnd.Next(1, 3), CustomerId = customer.Id, ModifiedByUserId = createdByUserId, ModifiedDate = customer.CreatedDate, Status = Status.Active, }; context.ClientCustomersHistory.AddOrUpdate(clientCustomerHistory); context.SaveChanges(); _clientCustomers[clientCustomer.ClientId].Add(customer.Id); } }
public static CustomerLocation GetLocation(int locationID) { CustomerLocation location = new CustomerLocation(); CurtDevDataContext db = new CurtDevDataContext(); location = (from cl in db.CustomerLocations where cl.locationID.Equals(locationID) select cl).FirstOrDefault<CustomerLocation>(); return location; }
public static string DeleteLocation(int id) { try { CurtDevDataContext db = new CurtDevDataContext(); CustomerLocation loc = new CustomerLocation(); loc = (from cl in db.CustomerLocations where cl.locationID.Equals(id) select cl).FirstOrDefault<CustomerLocation>(); db.CustomerLocations.DeleteOnSubmit(loc); db.SubmitChanges(); return ""; } catch (Exception e) { return e.Message; } }
/// <summary> /// /// </summary> /// <param name="locationId"></param> /// <returns></returns> public decimal GetTaxRateForLocation(int locationId) { CustomerLocation currentLocation = Context.CustomerLocations.FirstOrDefault(cl => cl.Id == locationId); return(GetStateTaxRate(currentLocation.AddressId)); }
/// <summary> /// Add a new customer location /// </summary> /// <param name="id">ID of the customer we're adding the location for.</param> /// <returns>View</returns> public ActionResult AddLocation(int id = 0) { string error = ""; #region Form Submission try { if (Request.Form["btnSubmit"] != null) { CurtDevDataContext db = new CurtDevDataContext(); // Save form values string name = (Request.Form["name"] != null) ? Request.Form["name"] : ""; string email = (Request.Form["email"] != null) ? Request.Form["email"] : ""; string phone = (Request.Form["phone"] != null) ? Request.Form["phone"] : ""; string fax = (Request.Form["fax"] != null) ? Request.Form["fax"] : ""; string address = (Request.Form["address"] != null) ? Request.Form["address"] : ""; string city = (Request.Form["city"] != null) ? Request.Form["city"] : ""; string postalCode = (Request.Form["postalCode"] != null) ? Request.Form["postalCode"] : ""; int stateID = (Request.Form["state"] != null) ? Convert.ToInt32(Request.Form["state"]) : 0; // Validate the form fields if (name.Length == 0) throw new Exception("Name is required."); if (phone.Length == 0) throw new Exception("Phone is required."); if (address.Length == 0) throw new Exception("Address is required."); if (city.Length == 0) throw new Exception("City is required."); if (stateID == 0) throw new Exception("State is required."); if (postalCode.Length == 0) throw new Exception("Postal Code is required."); GoogleMaps map = new GoogleMaps(System.Configuration.ConfigurationManager.AppSettings["GoogleMapsKey"]); LatLng location = map.GetLatLng(address, city, stateID); // Create the new customer and save CustomerLocation new_location = new CustomerLocation { name = name, email = email, phone = phone, fax = fax, address = address, city = city, stateID = stateID, postalCode = postalCode, latitude = Convert.ToDouble(location.latitude), longitude = Convert.ToDouble(location.longitude), cust_id = id }; db.CustomerLocations.InsertOnSubmit(new_location); db.SubmitChanges(); return RedirectToAction("Locations", new { id = id }); } } catch (Exception e) { error = e.Message; } #endregion // Get the customer that we're adding the location to Customer customer = CustomerModel.Get(id); ViewBag.customer = customer; // Get the states List<FullCountry> countries = CustomerModel.GetCountries(); ViewBag.countries = countries; ViewBag.error = error; return View(); }