public IActionResult AddLocation(AddLocationToCompanyViewModel addLocationToCompanyViewModel) { if (ModelState.IsValid) { var locationId = addLocationToCompanyViewModel.LocationId; var companyId = addLocationToCompanyViewModel.CompanyId; var existingItems = _companyLocationRepository.GetQueryable() .Where(cm => cm.LocationId == locationId) .Where(cm => cm.CompanyId == companyId) .ToList(); if (existingItems.Count == 0) { var companyLocation = new CompanyLocation { LocationId = locationId, CompanyId = companyId }; _companyLocationRepository.Add(companyLocation); return(Redirect("/Companies/Details?id=" + companyId)); } else { return(Redirect("/Characters/Details?id=" + companyId)); } } else { return(View(addLocationToCompanyViewModel)); } }
public IHttpActionResult PutCompanyLocation(long id, CompanyLocation companyLocation) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != companyLocation.ID) { return(BadRequest()); } db.Entry(companyLocation).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CompanyLocationExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public bool CreateCompanyLocation(CompanyLocationCreate model) { var entity = new CompanyLocation() { CompanyID = model.CompanyID, Street = model.Street, City = model.City, State = model.State, Zip = model.Zip, }; var profile = (new CompanyProfileServices(_userId).GetCompanyByCompanyId(model.CompanyID)); //profile. using (var ctx = new ApplicationDbContext()) { ctx.CompanyLocations.Add(entity); ctx.SaveChanges(); DataTable table = new DataTable("Companies"); foreach (DataRow dr in table.Rows) { if ((int)dr["CompanyID"] == model.CompanyID) { dr["CompanyLocation_ComapnyID"] = model.CompanyID; } } ctx.SaveChanges(); return(true); } }
public bool RegisterUser(RegisterModel registerModel) { string email = registerModel.Email; if (this.Repository.Single <UserProfile>(x => x.UserName == email) != null) { this.Success = false; this.Message = "Sorry, this username already exists. Please select another username."; return(false); } Company company = new Company(); company.Name = registerModel.CompanyName; CompanyLocation companyLocation = new CompanyLocation(); companyLocation.CompanyLocation1 = "Primary"; company.CompanyLocations.Add(companyLocation); this.Repository.Add(company); this.Repository.CommitAndDispose(); MembershipProvider.CreateAccount(registerModel.Email, registerModel.Password, new { FirstName = registerModel.FirstName, LastName = registerModel.LastName, created_on = DateTime.Now, updated_on = DateTime.Now, fk_company_location = companyLocation.id_company_locations }, true); return(true); }
public ActionResult DeleteConfirmed(int id) { CompanyLocation companyLocation = db.CompanyLocations.Find(id); db.CompanyLocations.Remove(companyLocation); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Edit([Bind(Include = "Id,CompanyId,Street,Town,Postcode,Lat,Lon,ImageFilename")] CompanyLocation companyLocation) { if (ModelState.IsValid) { db.Entry(companyLocation).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", companyLocation.CompanyId); return(View(companyLocation)); }
public int AddLocation(CompanyLocation companyLocation) { using (var context = DataObjectFactory.CreateContext()) { companyLocation.CompanyLocationGuid = Guid.NewGuid(); var entity = Mapper.Map(companyLocation); context.CompanyLocations.Add(entity); context.SaveChanges(); return(entity.CompanyLocationId); } }
public IHttpActionResult GetCompanyLocation(long id) { CompanyLocation companyLocation = db.CompanyLocations.Find(id); if (companyLocation == null) { return(NotFound()); } return(Ok(companyLocation)); }
public IHttpActionResult PostCompanyLocation(CompanyLocation companyLocation) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.CompanyLocations.Add(companyLocation); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = companyLocation.ID }, companyLocation)); }
public ActionResult Create(int companyLocationId) { CompanyLocation companyLocation = db.CompanyLocations.Find(companyLocationId); if (companyLocation == null) { return(HttpNotFound()); } ViewBag.BikeId = new SelectList(db.Bikes, "Id", "BikeModel"); var bike = new CompanyBike(); bike.CompanyLocationId = companyLocationId; return(View(bike)); }
// GET: CompanyLocations/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CompanyLocation companyLocation = db.CompanyLocations.Find(id); if (companyLocation == null) { return(HttpNotFound()); } return(View(companyLocation)); }
public IHttpActionResult DeleteCompanyLocation(long id) { CompanyLocation companyLocation = db.CompanyLocations.Find(id); if (companyLocation == null) { return(NotFound()); } db.CompanyLocations.Remove(companyLocation); db.SaveChanges(); return(Ok(companyLocation)); }
// GET: CompanyLocations/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CompanyLocation companyLocation = db.CompanyLocations.Find(id); if (companyLocation == null) { return(HttpNotFound()); } ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", companyLocation.CompanyId); return(View(companyLocation)); }
internal static EntityCompanyLocation Map(CompanyLocation entity) { return(new EntityCompanyLocation { CompanyLocationId = entity.CompanyLocationId, CompanyLocationGuid = entity.CompanyLocationGuid, Name = entity.Name, StratDate = entity.StratDate, AddressNo = entity.AddressNo, AddressStreet = entity.AddressStreet, City = entity.City, Province = entity.Province, CountryId = entity.CountryId, Timezone = entity.Timezone, WorkingHrs = entity.WorkingHrs, CompanyId = entity.CompanyId, CurrencyTypeId = entity.CurrencyTypeId, CompanyLogo = entity.CompanyLogo, CreatedOn = entity.CreatedOn, CreatedBy = entity.CreatedBy }); }
public ActionResult Edit([Bind(Include = "CustomerId,FirstName,EmailID,CompanyName,CompanyAddress,AboutCompany,OtherInformation,SelectedEquiments,LocationLists,VisionMission,LogoPath,BusinessBrochureUrl,CompanyID,UserId,CompanyLocationList")] CustomerModel CustomerModel, FormCollection form, HttpPostedFileBase file1, HttpPostedFileBase file2) { UserPermissionAction("vendor", RoleAction.edit.ToString()); CheckPermission(); //string CustomerID = "-1"; //int UserID = 0; //int CompanyID = 0; CustomerModel.CompanyAddress = "qq"; try { TempData["ShowMessage"] = "error"; TempData["MessageBody"] = "Please fill the required field with valid data"; if (ModelState.IsValid) { //var Location = form["LocationLists"].ToString(); Customer customerFound = _CustomerService.GetCustomers().Where(x => x.EmailId == CustomerModel.EmailID && x.CustomerId != CustomerModel.CustomerId).FirstOrDefault(); Mapper.CreateMap <Onlo.Models.CustomerModel, Onlo.Entity.Customer>(); Onlo.Entity.Customer Customer = Mapper.Map <Onlo.Models.CustomerModel, Onlo.Entity.Customer>(CustomerModel); Company Company = _CompanyService.GetCompanies().Where(x => x.CompanyID == CustomerModel.CompanyID).FirstOrDefault(); if (customerFound == null) { User User = _UserService.GetUsers().Where(x => x.UserEmailAddress == CustomerModel.EmailID && x.UserId != CustomerModel.UserId).FirstOrDefault(); if (User == null) { Customer Customers = _CustomerService.GetCustomers().Where(x => x.CustomerId == CustomerModel.CustomerId).FirstOrDefault(); Customers.FirstName = CustomerModel.FirstName; _CustomerService.UpdateCustomer(Customers); User user = _UserService.GetUsers().Where(x => x.UserId == CustomerModel.UserId).FirstOrDefault(); user.FirstName = CustomerModel.FirstName; _UserService.UpdateUser(user); Company.CompanyName = CustomerModel.CompanyName; Company.AboutCompany = CustomerModel.AboutCompany; Company.VisionMission = CustomerModel.VisionMission; Company.OtherInformation = CustomerModel.OtherInformation; _CompanyService.UpdateCompany(Company); } var shortPath1 = Company.LogoPath; if (file1 != null) { if (Company.LogoPath != null) { string pathDel = Server.MapPath("~/CompanyLogo"); //string pathDel = Server.MapPath(Company.LogoPath); FileInfo objfile = new FileInfo(pathDel); if (objfile.Exists) //check file exsit or not { objfile.Delete(); } } var fileExt = Path.GetExtension(file1.FileName); string fileName = Guid.NewGuid() + fileExt; var subPath = Server.MapPath("~/CompanyLogo"); //Check SubPath Exist or Not if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } //End : Check SubPath Exist or Not var path = Path.Combine(subPath, fileName); var shortPath = "~/CompanyLogo/" + fileName; file1.SaveAs(path); CommonClass.CreateThumbnail(shortPath, 218, 84, false); string URL = CommonClass.GetURL() + "/CompanyLogo/" + fileName; //driver.PhotoPath = CommonClass.GetURL() + "/DriverPhoto/" + fileName; Company.LogoPath = URL; _CompanyService.UpdateCompany(Company); } var shortPathBrochure = Company.BusinessBrochureUrl; if (file2 != null) { if (Company.LogoPath != null) { string pathDel = Server.MapPath("~/BusinessBrochure"); //string pathDel = Server.MapPath(Company.LogoPath); FileInfo objfile = new FileInfo(pathDel); if (objfile.Exists) //check file exsit or not { objfile.Delete(); } } var fileExt = Path.GetExtension(file2.FileName); string fileName = Guid.NewGuid() + fileExt; var subPath = Server.MapPath("~/BusinessBrochure"); //Check SubPath Exist or Not if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } //End : Check SubPath Exist or Not var path = Path.Combine(subPath, fileName); var shortPath = "~/BusinessBrochure/" + fileName; file2.SaveAs(path); CommonClass.CreateThumbnail(shortPath, 218, 84, false); string URL = CommonClass.GetURL() + "/BusinessBrochure/" + fileName; //driver.PhotoPath = CommonClass.GetURL() + "/DriverPhoto/" + fileName; Company.BusinessBrochureUrl = URL; _CompanyService.UpdateCompany(Company); } // Update CompanyEquipments //var CompanyEquipment = _CompanyEquipmentService.GetCompanyEquipments().Where(x => x.CompanyID == CustomerModel.CompanyID).AsEnumerable(); //if (CompanyEquipment != null) //{ // foreach (var CompanyEquipments in CompanyEquipment) // { // _CompanyEquipmentService.DeleteCompanyEquipment(CompanyEquipments); // } //} if (CustomerModel.SelectedEquiments != null) { //foreach (var ItemId in CustomerModel.SelectedEquiments) //{ // CompanyEquipment CompanyEquipments = new CompanyEquipment(); // CompanyEquipments.ItemId = Convert.ToInt32(ItemId); // CompanyEquipments.CompanyID = CustomerModel.CompanyID; // _CompanyEquipmentService.InsertCompanyEquipment(CompanyEquipments); //} } var _companyLocation = _CompanyLocationService.GetCompanyLocations().Where(x => x.CompanyID == CustomerModel.CompanyID).AsEnumerable(); if (_companyLocation != null) { foreach (var companyLocations in _companyLocation) { _CompanyLocationService.DeleteCompanyLocation(companyLocations); } } if (CustomerModel.CompanyLocationList != null) { foreach (var Locationlist in CustomerModel.CompanyLocationList) { CompanyLocation companyLocation = new CompanyLocation(); var _location = GoogleOperation.GetLatLong(Locationlist); var lat = _location[0]; var log = _location[1]; var address = Locationlist; //latlong1[2]; companyLocation.CompanyID = CustomerModel.CompanyID; companyLocation.Location = address.ToString(); //"Latitude":30.71000000,"Longitude":76.69000000 companyLocation.Latitude = Convert.ToDecimal(lat); companyLocation.Longitude = Convert.ToDecimal(log); _CompanyLocationService.InsertCompanyLocation(companyLocation); } } TempData["ShowMessage"] = "success"; TempData["MessageBody"] = " Manufacturer update successfully."; return(RedirectToAction("Index")); // end Update CompanyEquipments } else { TempData["ShowMessage"] = "error"; if (customerFound.EmailId.Trim().ToLower() == CustomerModel.EmailID.Trim().ToLower()) //Check User Name { TempData["MessageBody"] = customerFound.EmailId + " already exist."; } else { TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on "; } } } } catch (Exception ex) { string ErrorMsg = ex.Message.ToString();// ErrorLogging.LogError(ex); } //var companyEquiment = _CompanyEquipmentService.GetCompanyEquipments(); //var item = _IItemService.GetItems(); //var Equiment = _IItemService.GetItems(); //var selected = _CompanyEquipmentService.GetCompanyEquipments().Where(x => x.CompanyID == CustomerModel.CompanyID).Select(x => x.ItemId); //CustomerModel.EquimentList = _IItemService.GetItems().AsEnumerable().Select(c => new SelectListItem { Value = c.ItemId.ToString(), Text = c.ItemName, Selected = selected.Contains(c.ItemId) }).ToList(); return(View(CustomerModel)); }
public int Add(CompanyLocation companyLocation) { return(LocationDao.AddLocation(companyLocation)); }
public async Task <IActionResult> OnPostCompany() { if (ModelState.IsValid) { try { var FormData = Request.Form; Company_Dto company = JsonSerializer.Deserialize <Company_Dto>(FormData["info"]); //List<CompanyLocation_Dto> addresses = JsonSerializer.Deserialize<List<CompanyLocation_Dto>>(Request.Form["locations"]); //company.SetProperty("addresses", addresses); bool logoChanged = false; if (FormData.Files.Count > 0 && FormData.Files.Any(x => x.Name == "CompanyPic")) { IFormFile formFile = FormData.Files.First(x => x.Name == "CompanyPic"); string uploadedFileName = UploadedFile(formFile); company.CompanyLogo = uploadedFileName; logoChanged = true; } bool IsEditing = company.Id != Guid.Empty; if (IsEditing) { Company curCompany = await CompanyAppService.Repository.GetAsync(company.Id); if (curCompany.CompanyLogo != null && curCompany.CompanyLogo != "noimage.jpg" && logoChanged) { string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads"); string filePath = Path.Combine(uploadsFolder, curCompany.CompanyLogo); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } if (logoChanged) { curCompany.CompanyLogo = company.CompanyLogo; } else { company.CompanyLogo = curCompany.CompanyLogo; } if (AuditingManager.Current != null) { EntityChangeInfo entityChangeInfo = new EntityChangeInfo(); entityChangeInfo.EntityId = company.Id.ToString(); entityChangeInfo.EntityTenantId = company.TenantId; entityChangeInfo.ChangeTime = DateTime.Now; entityChangeInfo.ChangeType = EntityChangeType.Updated; entityChangeInfo.EntityTypeFullName = typeof(Company).FullName; entityChangeInfo.PropertyChanges = new List <EntityPropertyChangeInfo>(); List <EntityPropertyChangeInfo> entityPropertyChanges = new List <EntityPropertyChangeInfo>(); var auditProps = typeof(Company).GetProperties().Where(x => Attribute.IsDefined(x, typeof(CustomAuditedAttribute))).ToList(); Company mappedInput = ObjectMapper.Map <Company_Dto, Company>(company); foreach (var prop in auditProps) { EntityPropertyChangeInfo propertyChange = new EntityPropertyChangeInfo(); object origVal = prop.GetValue(curCompany); propertyChange.OriginalValue = origVal == null ? "" : origVal.ToString(); object newVal = prop.GetValue(mappedInput); propertyChange.NewValue = newVal == null ? "" : newVal.ToString(); if (propertyChange.OriginalValue == propertyChange.NewValue) { continue; } propertyChange.PropertyName = prop.Name; if (prop.Name.EndsWith("Id")) { try { string valuePropName = prop.Name.TrimEnd('d', 'I'); propertyChange.PropertyName = valuePropName; var valueProp = typeof(Company).GetProperty(valuePropName); DictionaryValue _origValObj = (DictionaryValue)valueProp.GetValue(company); if (_origValObj == null) { _origValObj = await DictionaryValuesRepo.GetAsync((Guid)origVal); } string _origVal = _origValObj.Value; propertyChange.OriginalValue = origVal == null ? "" : _origVal; DictionaryValue _newValObj = (DictionaryValue)valueProp.GetValue(mappedInput); if (_newValObj == null) { _newValObj = await DictionaryValuesRepo.GetAsync((Guid)newVal); } string _newVal = _newValObj.Value; propertyChange.NewValue = _newValObj == null ? "" : _newVal; } catch (Exception ex) { } } propertyChange.PropertyTypeFullName = prop.Name.GetType().FullName; entityChangeInfo.PropertyChanges.Add(propertyChange); } #region ExtraProperties List <EmployeeExtraPropertyHistory> allExtraPropertyHistories = new List <EmployeeExtraPropertyHistory>(); if (company.ExtraProperties != curCompany.ExtraProperties) { //GeneralInfo oldGeneralInfo = company.GetProperty<GeneralInfo>("generalInfo"); //List<EmployeeExtraPropertyHistory> physicalIdsHistory = new List<EmployeeExtraPropertyHistory>(); //var generalInfoPhysicalIdAuditProps = typeof(PhysicalID).GetProperties().Where(x => Attribute.IsDefined(x, typeof(CustomAuditedAttribute))).ToList(); //List<PhysicalId<Guid>> NewPhysicalIds = generalInfo.PhysicalIds.Where(x => !oldGeneralInfo.PhysicalIds.Any(y => y.Id == x.Id)).ToList(); //List<PhysicalId<Guid>> UpdatedPhysicalIds = generalInfo.PhysicalIds.Where(x => oldGeneralInfo.PhysicalIds.Any(y => y.Id == x.Id)).ToList(); //List<PhysicalId<Guid>> DeletedPhysicalIds = oldGeneralInfo.PhysicalIds.Where(x => !generalInfo.PhysicalIds.Any(y => y.Id == x.Id)).ToList(); //for (int i = 0; i < NewPhysicalIds.Count; i++) //{ // PhysicalId<Guid> curPhId = generalInfo.PhysicalIds[i]; // EmployeeExtraPropertyHistory newPhIdHistory = new EmployeeExtraPropertyHistory(2, "Physical Id", curPhId.IDNumber, "Created"); // physicalIdsHistory.Add(newPhIdHistory); //} //for (int i = 0; i < UpdatedPhysicalIds.Count; i++) //{ // PhysicalId<Guid> curPhId = generalInfo.PhysicalIds[i]; // PhysicalId<Guid> oldPhId = oldGeneralInfo.PhysicalIds.First(x => x.Id == curPhId.Id); // EmployeeExtraPropertyHistory updatedPhIdHistory = new EmployeeExtraPropertyHistory(2, "Physical Id", curPhId.IDNumber, "Updated"); // foreach (var prop in generalInfoPhysicalIdAuditProps) // { // updatedPhIdHistory.PropertyChanges = new List<EmployeeTypePropertyChange>(); // EmployeeTypePropertyChange propertyChange = new EmployeeTypePropertyChange(); // object origVal = prop.GetValue(oldPhId); // propertyChange.OriginalValue = origVal == null ? "" : origVal.ToString(); // object newVal = prop.GetValue(curPhId); // propertyChange.NewValue = newVal == null ? "" : newVal.ToString(); // if (propertyChange.OriginalValue == propertyChange.NewValue) continue; // propertyChange.PropertyName = prop.Name; // if (prop.Name.EndsWith("Id")) // { // try // { // string valuePropName = prop.Name.TrimEnd('d', 'I'); // propertyChange.PropertyName = valuePropName; // var valueProp = typeof(PhysicalID).GetProperty(valuePropName); // DictionaryValue _origValObj = (DictionaryValue)valueProp.GetValue(oldPhId); // if (_origValObj == null) _origValObj = await DictionaryValuesRepo.GetAsync((Guid)origVal); // string _origVal = _origValObj.Value; // propertyChange.OriginalValue = origVal == null ? "" : _origVal; // DictionaryValue _newValObj = (DictionaryValue)valueProp.GetValue(curPhId); // if (_newValObj == null) _newValObj = await DictionaryValuesRepo.GetAsync((Guid)newVal); // string _newVal = _newValObj.Value; // propertyChange.NewValue = _newValObj == null ? "" : _newVal; // } // catch (Exception ex) // { // } // } // propertyChange.PropertyTypeFullName = prop.Name.GetType().FullName; // updatedPhIdHistory.PropertyChanges.Add(propertyChange); // } // physicalIdsHistory.Add(updatedPhIdHistory); //} //for (int i = 0; i < DeletedPhysicalIds.Count; i++) //{ // PhysicalId<Guid> curPhId = generalInfo.PhysicalIds[i]; // EmployeeExtraPropertyHistory deletedPhIdHistory = new EmployeeExtraPropertyHistory(2, "Physical Id", curPhId.IDNumber, "Deleted"); // physicalIdsHistory.Add(deletedPhIdHistory); //} entityChangeInfo.SetProperty("extraPropertiesHistory", allExtraPropertyHistories); } #endregion AuditingManager.Current.Log.EntityChanges.Add(entityChangeInfo); } curCompany.CompanyName = company.CompanyName; curCompany.CompanyNameLocalized = company.CompanyNameLocalized; curCompany.CompanyLogo = company.CompanyLogo; curCompany.CompanyCode = company.CompanyCode; curCompany.Status = company.Status; curCompany.TaxID = company.TaxID; curCompany.SocialInsuranceID = company.SocialInsuranceID; curCompany.VATID = company.VATID; curCompany.RegistrationID = company.RegistrationID; curCompany.LabourOfficeId = company.LabourOfficeId; curCompany.Language = company.Language; CompanyLocation_Dto[] compLocs = company.CompanyLocations.ToArray(); Guid[] curCompLocsIds = curCompany.CompanyLocations.Select(x => x.Location.Id).ToArray(); List <Guid> toDeleteLocs = new List <Guid>(); for (int i = 0; i < curCompLocsIds.Length; i++) { CompanyLocation curCompanyLocation = curCompany.CompanyLocations.First(x => x.Location.Id == curCompLocsIds[i]); if (!compLocs.Any(x => x.LocationId == curCompLocsIds[i] && x.CreationTime == curCompanyLocation.CreationTime)) { curCompany.CompanyLocations.Remove(curCompany.CompanyLocations.First(x => x.Location.Id == curCompLocsIds[i])); toDeleteLocs.Add(curCompLocsIds[i]); } } for (int i = 0; i < compLocs.Length; i++) { if (!curCompany.CompanyLocations.Any(x => x.LocationId == compLocs[i].Location.Id && x.CreationTime == compLocs[i].CreationTime)) { curCompany.CompanyLocations.Add(new CompanyLocation() { Name = compLocs[i].Name, LocationValidityStart = compLocs[i].LocationValidityStart, LocationValidityEnd = compLocs[i].LocationValidityEnd, LocationId = compLocs[i].Location.Id, LocationType = compLocs[i].LocationType }); } else { var _companyLoc = curCompany.CompanyLocations.First(x => x.LocationId == compLocs[i].Location.Id); _companyLoc.LocationValidityStart = compLocs[i].LocationValidityStart; _companyLoc.LocationValidityEnd = compLocs[i].LocationValidityEnd; _companyLoc.Name = compLocs[i].Name; //curCompany.CompanyLocations.Remove(curCompany.CompanyLocations.First(x => x.LocationId == _companyLoc.LocationId)); await CompanyAppService.LocationsRepository.UpdateAsync(_companyLoc); } } CompanyCurrency_Dto[] compCurrencies = company.CompanyCurrencies.ToArray(); int[] curCompCurrenciesIds = curCompany.CompanyCurrencies.Select(x => x.Currency.Id).ToArray(); for (int i = 0; i < compCurrencies.Length; i++) { if (!curCompCurrenciesIds.Contains(compCurrencies[i].Currency.Id)) { curCompany.CompanyCurrencies.Add(new CompanyCurrency() { ExchangeRate = compCurrencies[i].ExchangeRate, CurrencyId = compCurrencies[i].Currency.Id, Status = compCurrencies[i].Status }); } else { var _companyCurrency = curCompany.CompanyCurrencies.First(x => x.CurrencyId == compCurrencies[i].Currency.Id); _companyCurrency.ExchangeRate = compCurrencies[i].ExchangeRate; _companyCurrency.Status = compCurrencies[i].Status; //curCompany.CompanyLocations.Remove(curCompany.CompanyLocations.First(x => x.LocationId == _companyLoc.LocationId)); await CompanyAppService.CurrenciesRepository.UpdateAsync(_companyCurrency); } } List <int> toDeleteCurrencies = new List <int>(); for (int i = 0; i < curCompCurrenciesIds.Length; i++) { if (!compCurrencies.Any(x => x.Currency.Id == curCompCurrenciesIds[i])) { curCompany.CompanyCurrencies.Remove(curCompany.CompanyCurrencies.First(x => x.CurrencyId == curCompCurrenciesIds[i])); toDeleteCurrencies.Add(curCompCurrenciesIds[i]); } } CompanyPrintSize_Dto[] compPrintSizes = company.CompanyPrintSizes.ToArray(); int[] curCompPrintSizesIds = curCompany.CompanyPrintSizes.Select(x => x.Id).ToArray(); for (int i = 0; i < compPrintSizes.Length; i++) { if (!curCompPrintSizesIds.Contains(compPrintSizes[i].Id)) { curCompany.CompanyPrintSizes.Add(new CompanyPrintSize() { PrintSize = compPrintSizes[i].PrintSize }); } } List <int> toDeletePrintSizes = new List <int>(); for (int i = 0; i < curCompPrintSizesIds.Length; i++) { if (!compPrintSizes.Any(x => x.Id == curCompPrintSizesIds[i])) { curCompany.CompanyPrintSizes.Remove(curCompany.CompanyPrintSizes.First(x => x.Id == curCompPrintSizesIds[i])); toDeletePrintSizes.Add(curCompPrintSizesIds[i]); } } CompanyDocument_Dto[] compDocuments = company.CompanyDocuments.ToArray(); int[] curCompDocumentsIds = curCompany.CompanyDocuments.Select(x => x.Id).ToArray(); for (int i = 0; i < compDocuments.Length; i++) { if (!curCompDocumentsIds.Contains(compDocuments[i].Id)) { string curFileName = compDocuments[i].Document.Name; if (FormData.Files.Any(x => x.Name == curFileName)) { var curDoc = compDocuments[i].Document; if (curDoc.Id == Guid.Empty) { IFormFile document = FormData.Files.First(x => x.Name == curFileName); string uploadedFileName = UploadedFile(document); Document_Dto doc = new Document_Dto(GuidGenerator.Create()); doc.ReferenceNo = (new Random()).Next(10, 90) * (new Random()).Next(10000, 90000); doc.Name = company.CompanyName + "_" + compDocuments[i].DocumentType.Value + "_" + compDocuments[i].Id; doc.NameLocalized = company.CompanyNameLocalized + "_" + compDocuments[i].DocumentType.Value + "_" + compDocuments[i].Id; doc.Description = $"Soft copy of {compDocuments[i].DocumentType.Value}"; doc.OwnerId = company.Id; doc.OwnerTypeId = DictionaryValuesRepo.WithDetails().Where(x => x.Value == "Company").First(x => x.ValueType.ValueTypeFor == ValueTypeModules.OwnerType).Id; doc.DocumentTypeId = compDocuments[i].DocumentType.Id; doc.IssuedFromId = doc.OwnerTypeId; doc.IssueDate = compDocuments[i].IssueDate; doc.ExpiryDate = compDocuments[i].EndDate; doc.FileName = uploadedFileName; Document_Dto created = await documentAppService.CreateAsync(doc); compDocuments[i].DocumentId = created.Id; } } curCompany.CompanyDocuments.Add(new CompanyDocument() { DocumentTitle = compDocuments[i].DocumentTitle, DocumentTitleLocalized = compDocuments[i].DocumentTitleLocalized, DocumentTypeId = compDocuments[i].DocumentType.Id, DocumentId = compDocuments[i].DocumentId, IssueDate = compDocuments[i].IssueDate, EndDate = compDocuments[i].EndDate }); } } List <CompanyDocument> toDeleteDocuments = new List <CompanyDocument>(); for (int i = 0; i < curCompDocumentsIds.Length; i++) { if (!compDocuments.Any(x => x.Id == curCompDocumentsIds[i])) { var doc = curCompany.CompanyDocuments.First(x => x.Id == curCompDocumentsIds[i]); toDeleteDocuments.Add(doc); curCompany.CompanyDocuments.Remove(doc); } } for (int i = 0; i < toDeletePrintSizes.Count; i++) { await CompanyAppService.PrintSizesRepository.DeleteAsync(x => x.Id == toDeletePrintSizes[i]); } for (int i = 0; i < toDeleteLocs.Count; i++) { await CompanyAppService.LocationsRepository.DeleteAsync(x => x.LocationId == toDeleteLocs[i]); } for (int i = 0; i < toDeleteCurrencies.Count; i++) { await CompanyAppService.CurrenciesRepository.DeleteAsync(x => x.CurrencyId == toDeleteCurrencies[i]); } for (int i = 0; i < toDeleteDocuments.Count; i++) { await documentAppService.Repository.DeleteAsync(toDeleteDocuments[i].DocumentId); await CompanyAppService.DocumentsRepository.DeleteAsync(x => x.Id == toDeleteDocuments[i].Id); } Company_Dto updated = ObjectMapper.Map <Company, Company_Dto>(await CompanyAppService.Repository.UpdateAsync(curCompany)); return(StatusCode(200, updated)); } else { List <Document_Dto> documentsToAdd = new List <Document_Dto>(); List <CompanyDocument_Dto> companyDocuments = company.CompanyDocuments; if (FormData.Files.Count > 0) { for (int i = 0; i < companyDocuments.Count; i++) { CompanyDocument_Dto compDoc = companyDocuments[i]; string curFileName = compDoc.Document.Name; if (FormData.Files.Any(x => x.Name == curFileName)) { var curDoc = compDoc.Document; if (curDoc.Id == Guid.Empty) { IFormFile document = FormData.Files.First(x => x.Name == curFileName); string uploadedFileName = UploadedFile(document); Document_Dto doc = new Document_Dto(GuidGenerator.Create()); doc.ReferenceNo = (new Random()).Next(10, 90) * (new Random()).Next(10000, 90000); doc.Name = company.CompanyName + "_" + compDoc.DocumentType.Value + "_" + compDoc.Id; doc.NameLocalized = company.CompanyNameLocalized + "_" + compDoc.DocumentType.Value + "_" + compDoc.Id; doc.Description = $"Soft copy of {compDoc.DocumentType.Value}"; doc.OwnerId = company.Id; doc.OwnerTypeId = DictionaryValuesRepo.WithDetails().Where(x => x.Value == "Company").First(x => x.ValueType.ValueTypeFor == ValueTypeModules.OwnerType).Id; doc.DocumentTypeId = compDoc.DocumentTypeId; doc.IssuedFromId = compDoc.Document.IssuedFromId; doc.IssueDate = compDoc.IssueDate; doc.ExpiryDate = compDoc.EndDate; doc.FileName = uploadedFileName; Document_Dto created = await documentAppService.CreateAsync(doc); compDoc.DocumentId = created.Id; } } } if (company.CompanyLogo == null) { company.CompanyLogo = "noimage.jpg"; } } for (int i = 0; i < documentsToAdd.Count; i++) { Document_Dto curDoc = documentsToAdd[i]; } company.Id = Guid.Empty; company.CompanyCurrencies.ForEach(x => { x.Id = 0; x.CurrencyId = x.Currency.Id; x.Currency = null; }); company.CompanyLocations.ForEach(x => { x.Id = 0; x.LocationId = x.Location.Id; x.Location = null; }); company.CompanyPrintSizes.ForEach(x => { x.Id = 0; }); Company_Dto added = await CompanyAppService.CreateAsync(company); if (AuditingManager.Current != null) { EntityChangeInfo entityChangeInfo = new EntityChangeInfo(); entityChangeInfo.EntityId = added.Id.ToString(); entityChangeInfo.EntityTenantId = added.TenantId; entityChangeInfo.ChangeTime = DateTime.Now; entityChangeInfo.ChangeType = EntityChangeType.Created; entityChangeInfo.EntityTypeFullName = typeof(Company).FullName; AuditingManager.Current.Log.EntityChanges.Add(entityChangeInfo); } return(StatusCode(200, added)); } } catch (Exception ex) { } } return(StatusCode(500)); }
public ActionResult Create([Bind(Include = "CustomerId,FirstName,EmailID,CompanyName,CompanyAddress,AboutCompany,OtherInformation,SelectedEquiments,LocationLists,VisionMission,LogoPath,BusinessBrochureUrl")] CustomerModel CustomerModel, FormCollection form, HttpPostedFileBase file1, HttpPostedFileBase file2) { UserPermissionAction("vendor", RoleAction.create.ToString()); CheckPermission(); string CustomerID = "-1"; int UserID = 0; int CompanyID = 0; CustomerModel.CompanyAddress = "qq"; try { if (ModelState.IsValid) { //var Location = form["LocationLists"].ToString(); Mapper.CreateMap <Onlo.Models.CustomerModel, Onlo.Entity.Customer>(); Onlo.Entity.Customer Customer = Mapper.Map <Onlo.Models.CustomerModel, Onlo.Entity.Customer>(CustomerModel); Customer customerFound = _CustomerService.GetCustomers().Where(x => x.EmailId == Customer.EmailId).FirstOrDefault(); if (customerFound == null) { string EmailId = Customer.EmailId; string FirstName = CustomerModel.FirstName; string Password = CustomerModel.Password; if (CustomerModel.FirstName == "" || CustomerModel.FirstName == null) { FirstName = Customer.EmailId.Split('@')[0].Trim(); } Customer.CompanyID = 1; //There is no session in API Controller. So we will find solution in future Customer.Address = ""; Customer.MobileNo = ""; Customer.ZipCode = ""; Customer.PhotoPath = ""; //Insert User first Onlo.Entity.User user = new Onlo.Entity.User(); //user.UserId =0; //New Case user.FirstName = CustomerModel.FirstName; user.LastName = Customer.LastName; user.UserName = CustomerModel.FirstName;; user.Password = SecurityFunction.EncryptString(FirstName + "@123"); //user.Password = SecurityFunction.EncryptString(Password); user.UserEmailAddress = EmailId; user.CompanyID = Customer.CompanyID; user.CreatedOn = DateTime.Now; user.LastUpdatedOn = DateTime.Now; user.IsActive = true; _UserService.InsertUser(user); //End : Insert User firstss UserID = user.UserId; if (user.UserId > 0) { //Insert User Role Onlo.Entity.UserRole userRole = new Onlo.Entity.UserRole(); userRole.UserId = user.UserId; userRole.RoleId = 3; //By Default set new Customer/user role id=3 _UserRoleService.InsertUserRole(userRole); //End : Insert User Role //Insert the Customer Customer.FirstName = FirstName; Customer.UserId = user.UserId; Customer.MobileVerifyCode = CommonClass.GetNumericCode(); Customer.EmailVerifyCode = CommonClass.GetNumericCode(); if (CustomerModel.IsEmailVerified != null) { Customer.IsEmailVerified = CustomerModel.IsEmailVerified; } else { Customer.IsEmailVerified = false; } if ((CustomerModel.PhotoPath != null) && (CustomerModel.PhotoPath != "")) { if (!CustomerModel.PhotoPath.Contains('.')) { Customer.PhotoPath = CommonClass.SaveImage(CustomerModel.PhotoPath, "CustomerPhoto", ".png");//SaveImage(CustomerModel.PhotoPath); } } // Customer.RoleType = EnumValue.GetEnumDescription(EnumValue.RoleType.Manufacturer); Customer.IsActive = true; Customer.SubscriptionStartDate = DateTime.Now; Customer.SubscriptionEndDate = DateTime.UtcNow.AddMonths(1); _CustomerService.InsertCustomer(Customer); CustomerID = Convert.ToString(Customer.CustomerId); if (CustomerID != null) { var Customers = _CustomerService.GetCustomers().Where(x => x.CustomerId == Convert.ToInt32(CustomerID)); if (Customers != null) { Company Company = new Company(); Company.CompanyName = CustomerModel.CompanyName; Company.AboutCompany = CustomerModel.AboutCompany; Company.CompanyAddress = "aa"; Company.CityID = 0; Company.StateID = 0; Company.CountryID = 39; Company.OtherInformation = CustomerModel.OtherInformation; Company.VisionMission = CustomerModel.VisionMission; if (file1 != null) { var fileExt = Path.GetExtension(file1.FileName); string fileName = Guid.NewGuid() + fileExt; var subPath = Server.MapPath("~/CompanyLogo"); //Check SubPath Exist or Not if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } //End : Check SubPath Exist or Not var path = Path.Combine(subPath, fileName); var shortPath = "~/CompanyLogo/" + fileName; file1.SaveAs(path); CommonClass.CreateThumbnail(shortPath, 218, 84, false); string URL = CommonClass.GetURL() + "/CompanyLogo/" + fileName; Company.LogoPath = URL; //Company.LogoPath = shortPath; //_CompanyService.UpdateCompany(Company); } if (file2 != null) { var fileExt = Path.GetExtension(file2.FileName); string fileName = Guid.NewGuid() + fileExt; var subPath = Server.MapPath("~/BusinessBrochure"); //Check SubPath Exist or Not if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } //End : Check SubPath Exist or Not var path = Path.Combine(subPath, fileName); var shortPath = "~/BusinessBrochure/" + fileName; file2.SaveAs(path); CommonClass.CreateThumbnail(shortPath, 218, 84, false); string URL = CommonClass.GetURL() + "/BusinessBrochure/" + fileName; Company.BusinessBrochureUrl = URL; } Company.IsActive = true; _CompanyService.InsertCompany(Company); CompanyID = Convert.ToInt32(Company.CompanyID); //SAVE company// //Insert CompanyEquipments if (CustomerModel.SelectedEquiments != null) { //foreach (var ItemId in CustomerModel.SelectedEquiments) //{ // CompanyEquipment CompanyEquipments = new CompanyEquipment(); // CompanyEquipments.ItemId = Convert.ToInt32(ItemId); // CompanyEquipments.CompanyID = Convert.ToInt32(CompanyID); // _CompanyEquipmentService.InsertCompanyEquipment(CompanyEquipments); //} } //insert CompanyLocation if (CompanyID > 0) { if (CustomerModel.LocationLists != null) { foreach (var Locationlist in CustomerModel.LocationLists) { CompanyLocation companyLocation = new CompanyLocation(); var _location = GoogleOperation.GetLatLong(Locationlist); var lat = _location[0]; var log = _location[1]; var address = Locationlist;//latlong1[2]; companyLocation.CompanyID = CompanyID; companyLocation.Location = address.ToString();//"Latitude":30.71000000,"Longitude":76.69000000 companyLocation.Latitude = Convert.ToDecimal(lat); companyLocation.Longitude = Convert.ToDecimal(log); _CompanyLocationService.InsertCompanyLocation(companyLocation); } } } //End insert CompanyLocation //update company_id in customer table var customers = _CustomerService.GetCustomers().Where(x => x.CustomerId == Convert.ToInt32(CustomerID)); foreach (var custormer in customers) { var customer = _CustomerService.GetCustomer(custormer.CustomerId); customer.CompanyID = CompanyID; _CustomerService.UpdateCustomer(customer); } string UserPassword = SecurityFunction.DecryptString(user.Password); JobScheduler.Registration(Customer.FirstName, Customer.EmailId, UserPassword);// using Scheduler// } TempData["ShowMessage"] = "success"; TempData["MessageBody"] = "Manufacturer is saved successfully."; return(RedirectToAction("Index")); } } } else { TempData["ShowMessage"] = "error"; TempData["MessageBody"] = "vendors is already exists."; } } var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray(); var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors); } catch (Exception ex) { var UserRole = _UserRoleService.GetUserRoles().Where(x => x.UserId == UserID).FirstOrDefault(); if (UserRole != null) { _UserRoleService.DeleteUserRole(UserRole); // delete user role } var User = _UserService.GetUsers().Where(x => x.UserId == UserID).FirstOrDefault(); if (User != null) { _UserService.DeleteUser(User); // delete user } string ErrorMsg = ex.Message.ToString(); // ErrorLogging.LogError(ex); } //var Equiment = _IItemService.GetItems(); //CustomerModel.EquimentList = Equiment.Select(x => new SelectListItem { Value = x.ItemId.ToString(), Text = x.ItemName }).ToList(); return(View(CustomerModel)); }