public void AddMaintainMarketVertical_Successfully(int ID, string descriptionAdd) { var solutionApplicationDto = new SolutionApplicationDto { ID = ID, Description = descriptionAdd, }; var addedSolutionApplication = new SolutionApplication { ID = 1, Description = descriptionAdd }; _solutionApplicationRepository.GetAll().ReturnsForAnyArgs(LoadMarketVerticalList()); _solutionApplicationRepository.Add(Arg.Any <SolutionApplication>()).Returns(addedSolutionApplication); var actualResult = _adminProcessor.SaveMaintainMarketVertical(solutionApplicationDto); Assert.AreEqual(addedSolutionApplication.ID, actualResult.ID); }
public void AddProductFamilyDetail_Successfully(int ID, string descriptionAdd) { var productFamilyDto = new ProductFamilyDto { Id = ID, Description = descriptionAdd, }; var addedProductFamily = new ProductFamily { ID = 1, Description = descriptionAdd }; _productFamilyRepository.GetAll().ReturnsForAnyArgs(LoadProductFamilyList()); _productFamilyRepository.Add(Arg.Any <ProductFamily>()).Returns(addedProductFamily); var actualResult = _adminProcessor.SaveProductFamily(productFamilyDto); Assert.AreEqual(addedProductFamily.ID, actualResult.ID); }
public HttpResponseMessage Add(HttpRequestMessage request, DummyData designItems) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { //var designItems = request.DeserializeObject<DummyData>("dummy"); var existingItems = _dummyPagePlacementRepository.GetAll().Where(x => x.dummy_page_id == designItems.page_id); foreach (var item in existingItems) { _dummyPagePlacementRepository.Delete(item); } _unitOfWork.Commit(); var currentPage = _dummyPageRepository.GetSingle(designItems.page_id); if (designItems.dummy != null) { foreach (var item in designItems.dummy) { var PagePlacementEntity = item.ToEntity(); PagePlacementEntity.tbl_dummy_page = currentPage; _dummyPagePlacementRepository.Add(PagePlacementEntity); var mediaPage = _mediaPageNumberRepository.GetSingle(PagePlacementEntity.media_page_number_id); mediaPage.page_desc = currentPage.page_name; mediaPage.page_number = currentPage.page_number; } _unitOfWork.Commit(); } response = request.CreateResponse(HttpStatusCode.Created, true); } return response; })); }
public HttpResponseMessage Add(HttpRequestMessage request, CustomerViewModel customer) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { //if (_customersRepository.UserExists(customer.Email, customer.IdentityCard)) //{ // ModelState.AddModelError("Invalid user", "Email or Identity Card number already exists"); // response = request.CreateResponse(HttpStatusCode.BadRequest, // ModelState.Keys.SelectMany(k => ModelState[k].Errors) // .Select(m => m.ErrorMessage).ToArray()); //} //else //{ //} Customer newCustomer = new Customer(); newCustomer.UpdateCustomer(customer); _customersRepository.Add(newCustomer); _unitOfWork.Commit(); // Update view model customer = Mapper.Map <Customer, CustomerViewModel>(newCustomer); response = request.CreateResponse <CustomerViewModel>(HttpStatusCode.Created, customer); } return response; })); }
public HttpResponseMessage AddOrdersToEmployee(HttpRequestMessage request, JObject objData) { //**** SOURCE URL SAMPLE: http://www.dotnetcurry.com/aspnet/1278/aspnet-webapi-pass-multiple-parameters-action-method return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { dynamic jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject(objData.ToString()); var employeeIdJson = jsonData.jsonObj.employeeId; var ordersJson = jsonData.jsonObj.orders; List <EmployeeOrder> EmployeeOrderobj = new List <EmployeeOrder>(); foreach (var orderid in ordersJson) { EmployeeOrderViewModel employeeorderVM = new EmployeeOrderViewModel(); EmployeeOrder newemployeeorder = new EmployeeOrder(); newemployeeorder.OrderId = orderid.Id; newemployeeorder.CommissionedEmployeeId = employeeIdJson; _employeeordersRepository.Add(newemployeeorder); _unitOfWork.Commit(); EmployeeOrderobj.Add(newemployeeorder); } IEnumerable <EmployeeOrderViewModel> EmployeeordersVM = Mapper.Map <IEnumerable <EmployeeOrder>, IEnumerable <EmployeeOrderViewModel> >(EmployeeOrderobj); response = request.CreateResponse <IEnumerable <EmployeeOrderViewModel> >(HttpStatusCode.OK, EmployeeordersVM); } return response; })); }
public HttpResponseMessage Register(HttpRequestMessage request, ProjectViewModel project) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (_projectsRepository.UserExists(project.Email)) { ModelState.AddModelError("Invalid user", "Email already exists"); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Project newProject = new Project(); newProject.UpdateProject(project); _projectsRepository.Add(newProject); _unitOfWork.Commit(); // Update view model project = Mapper.Map <Project, ProjectViewModel>(newProject); response = request.CreateResponse <ProjectViewModel>(HttpStatusCode.Created, project); } } return response; })); }
public HttpResponseMessage Add(HttpRequestMessage request, MovieViewModel movie) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { Movie newMovie = new Movie(); newMovie.UpdateMovie(movie); for (int i = 0; i < movie.NumberOfStocks; i++) { Stock stock = new Stock() { IsAvailable = true, Movie = newMovie, UniqueKey = Guid.NewGuid() }; newMovie.Stocks.Add(stock); } _moviesRepository.Add(newMovie); _unitOfWork.Commit(); // Update view model movie = Mapper.Map <Movie, MovieViewModel>(newMovie); response = request.CreateResponse <MovieViewModel>(HttpStatusCode.Created, movie); } return response; })); }
public Category SaveCategory(CategoryViewModel data, ref string errorMessage) { try { Category DBData = Mapper.Map <CategoryViewModel, Category>(data); if (DBData.ID == 0) { _categoryInfoRepo.Add(DBData, ref errorMessage); } else { Category SavedData = _categoryInfoRepo.Get(x => x.ID == DBData.ID, ref errorMessage).FirstOrDefault(); _categoryInfoRepo.Update(SavedData, DBData, ref errorMessage); } _unitOfWork.Commit(); return(DBData); } catch (Exception Ex) { errorMessage = Ex.Message; } return(null); }
public FamilyHistory SaveFamilyHistoryDetails(FamilyHistoryViewModel data, ref string errorMessage) { try { FamilyHistory DBData = Mapper.Map <FamilyHistoryViewModel, FamilyHistory>(data); if (DBData.ID == 0 && DBData.RecordID.ToString() == "00000000-0000-0000-0000-000000000000") { DBData.CreatedOn = DateTime.UtcNow; DBData.RecordID = Guid.NewGuid(); familyHistoryInfoRepo.Add(DBData, ref errorMessage); } else { FamilyHistory savedData = familyHistoryInfoRepo.Get(x => x.RecordID == DBData.RecordID, ref errorMessage).FirstOrDefault(); DBData.ID = savedData.ID; DBData.Modifiedon = DateTime.UtcNow; familyHistoryInfoRepo.Update(savedData, DBData, ref errorMessage); } unitOfWork.Commit(); return(DBData); } catch (Exception Ex) { errorMessage = Ex.Message; } return(null); }
public CareCoordinator SaveCareCoordinatorDetails(CareCoordinatorViewModel data, ref string errorMessage) { try { CareCoordinator DBData = Mapper.Map <CareCoordinatorViewModel, CareCoordinator>(data); if (DBData.ID == 0 && DBData.RecordID.ToString() == "00000000-0000-0000-0000-000000000000") { DBData.CreatedOn = DateTime.UtcNow; DBData.RecordID = Guid.NewGuid(); careCoordinatorInfoRepo.Add(DBData, ref errorMessage); } else { CareCoordinator savedData = careCoordinatorInfoRepo.Get(x => x.RecordID == DBData.RecordID, ref errorMessage).FirstOrDefault(); DBData.ID = savedData.ID; DBData.Modifiedon = DateTime.UtcNow; careCoordinatorInfoRepo.Update(savedData, DBData, ref errorMessage); } unitOfWork.Commit(); return(DBData); } catch (Exception Ex) { errorMessage = Ex.Message; } return(null); }
/// <summary> /// Save User Default Solution Setup details /// </summary> /// <param name="userDefaultSolutionSetupDto"></param> /// <param name="userID"></param> /// <param name="userName"></param> /// <returns></returns> public Boolean SaveUserDefaultSolutionSetup(UserDefaultSolutionSetupDto userDefaultSolutionSetupDto, string userID, string userName) { var userDefaultSetupCount = _userDefaultSolutionSetupRepository.GetAll(u => !u.IsGlobalDefaults && u.UserID == userID).Count(); if (userDefaultSetupCount == 0) { var newUserDefaultSolutionSetup = _userDefaultSolutionSetupDtoToUserDefaultSolutionSetupEntityMapper.AddMap(userDefaultSolutionSetupDto); newUserDefaultSolutionSetup.UserID = userID; newUserDefaultSolutionSetup.CreatedDateTime = DateTime.UtcNow; newUserDefaultSolutionSetup.CreatedBy = userName; newUserDefaultSolutionSetup.ModifiedDateTime = DateTime.UtcNow; newUserDefaultSolutionSetup.ModifiedBy = userName; newUserDefaultSolutionSetup.RegulatoryFilter = string.Join(";", userDefaultSolutionSetupDto.SelectedRegulatoryFilterList.Select(x => x.Id + ":" + x.ItemName + ":" + x.LanguageKey).ToArray()); var newAddResult = _userDefaultSolutionSetupRepository.Add(newUserDefaultSolutionSetup); _userDefaultSolutionSetupRepository.Commit(); return(true); } var userDefaultSolutionSetup = _userDefaultSolutionSetupRepository.GetSingle(u => !u.IsGlobalDefaults && u.UserID == userID); _userDefaultSolutionSetupDtoToUserDefaultSolutionSetupEntityMapper.UpdateMap(userDefaultSolutionSetupDto, userDefaultSolutionSetup); userDefaultSolutionSetup.ModifiedDateTime = DateTime.UtcNow; userDefaultSolutionSetup.ModifiedBy = userName; userDefaultSolutionSetup.RegulatoryFilter = string.Join(";", userDefaultSolutionSetupDto.SelectedRegulatoryFilterList.Select(x => x.Id + ":" + x.ItemName + ":" + x.LanguageKey).ToArray()); var result = _userDefaultSolutionSetupRepository.Update(userDefaultSolutionSetup); _userDefaultSolutionSetupRepository.Commit(); return(true); }
public HttpResponseMessage Register(HttpRequestMessage request, UserRestaurantViewModel user) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, new { success = false }); } else { if (!string.IsNullOrEmpty(user.UserDetails.Username)) { var existingUserDb = _userRepository.GetSingleByUsername(user.UserDetails.Username); if (existingUserDb != null)// && existingUserDb.RestaurantId == restaurantdetail.ID) { ModelState.AddModelError("Invalid User", "User name already exists"); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Entities.User _user = _membershipService.CreateUser(user.UserDetails.Username, user.UserDetails.Username, user.UserDetails.Password, new int[] { 1 }); UserRestaurant newuserestaurant = new UserRestaurant(); newuserestaurant.RestaurantId = user.ID; newuserestaurant.UserId = _user.ID; _userrestaurant.Add(newuserestaurant); _unitOfWork.Commit(); response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } } } return response; })); }
public HttpResponseMessage Register(HttpRequestMessage request, CustomerViewModel customer) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (customerRepository.CustomerExists(customer.Email, customer.IdentityCard)) { ModelState.AddModelError("Invalid user", "Email or identity card already exists"); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Customer newCustomer = new Customer(); newCustomer.UpdateCustomer(customer); customerRepository.Add(newCustomer); _unitOfWork.Commit(); // Update view model by re-mapping the just-committed newCustomer customer = Mapper.Map <Customer, CustomerViewModel>(newCustomer); response = request.CreateResponse(HttpStatusCode.Created, customer); } } return response; })); }
public User CreateUser(string username, string email, string password, int[] roles) { var existingUser = _userRepository.GetSingleByUsername(username); if (existingUser != null) { throw new Exception("Username is already in use"); } var passwordSalt = _encryptionService.CreateSalt(); var user = new User() { Username = username, Salt = passwordSalt, Email = email, IsLocked = false, HashedPassword = _encryptionService.EncryptPassword(password, passwordSalt), DateCreated = DateTime.Now }; _userRepository.Add(user); _unitOfWork.Commit(); if (roles != null || roles.Length > 0) { foreach (var role in roles) { addUserToRole(user, role); } } _unitOfWork.Commit(); return(user); }
public Direccion Guardar(Direccion direccion) { var direccionRepo = new Direccion(); if (direccion.Id == 0) { direccion.CiudadId = direccion.Ciudad.Id; direccion.Ciudad = null; direccionRepo = _direccionRepositorio.Add(direccion); } else { direccionRepo = _direccionRepositorio.FindBy(d => d.Id == direccion.Id).FirstOrDefault(); direccionRepo.Descripcion = direccion.Descripcion; direccionRepo.CiudadId = direccion.Ciudad.Id; direccionRepo.Barrio = direccion.Barrio; _direccionRepositorio.Edit(direccionRepo); } _unitOfWork.Commit(); return(direccionRepo); }
public IHttpActionResult Register(HttpRequestMessage request, CustomerViewModel customer) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys .SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (_customersRepository.UserExists(customer.Email, customer.IdentityCard)) { ModelState.AddModelError("Invalid User", "Email or Identity Card have existed"); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys .SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Customer newCustomer = new Customer(); newCustomer.UpdateCustomer(customer); _customersRepository.Add(newCustomer); _unitOfWork.Commit(); customer = Mapper.Map <Customer, CustomerViewModel>(newCustomer); response = request.CreateResponse(HttpStatusCode.Created, customer); } } return response; })); }
private void addUserToProjectRole(User user, int projectId, int projectRoleId) { var project = _projectRepository.GetSingle(projectId); var role = _projectRoleRepository.GetSingle(projectRoleId); if (project == null) { throw new ApplicationException("Project doesn't exist."); } if (role == null) { throw new ApplicationException("Role doesn't exist."); } var userProjectRole = new UserProjectRole() { UserId = user.ID, ProjectId = project.ID, ProjectRoleId = role.ID }; _userProjectRoleRepository.Add(userProjectRole); }
public void Create(T vm) { if (vm == null) { Warning("La Entidad esta vacia"); return; } var result = Db.Add(vm); if (!result.Success) { Warning(result.ResultMessageToString()); return; } if (!Db.Save()) { Error("La base de datos ha arrojado un error"); return; } Info("Datos guardados exitosamente"); Close(); }
public async Task <ActionResult <PostDTO> > UpdatePost(int id, PostDTO postDTO) { try { if (id != postDTO.Id) { return(BadRequest()); } Post post = await GetPost(id); PostDTO tmpPostDTO = post.ToDTO(); if (post == null) { return(NotFound()); } post.Title = postDTO.Title; post.Body = postDTO.Body; post.EditTimeStamp = DateTime.Now; bool isNewAcceptedAnswer = post.AcceptedAnswerId != postDTO.AcceptedAnswerId; if (isNewAcceptedAnswer && postDTO.AcceptedAnswerId.HasValue && postDTO.AcceptedAnswerId != 0) { var postOwner = post.Author; var actor = (from r in post.Replies where r.Id == postDTO.AcceptedAnswerId select r.Author).FirstOrDefault(); var action = ReputationAction.AcceptedAnswer; if (actor != null) { ReputationManagementExtension.ReputationUpdate(postOwner, actor, action); } } post.AcceptedAnswerId = postDTO.AcceptedAnswerId; Console.WriteLine("\n " + tmpPostDTO.Tags + " \n - " + postDTO.Tags); if ((post.ParentId == 0 || post.ParentId == null) && CollectionMethodExtension.IsDifferentCollection <PostTagDTO>(tmpPostDTO.Tags, postDTO.Tags)) { //On pourrait utiliser une method generic - To Do si on a le temps - Bad Practice d'avoir une method aussi longue foreach (PostTagDTO tag in postDTO.Tags) { if (!tmpPostDTO.Tags.Contains(tag)) { PostTag pt = new PostTag(); pt.PostId = post.Id; pt.TagId = tag.Id; await _postTagRepository.Add(pt).ConfigureAwait(true); } } foreach (PostTagDTO tag in tmpPostDTO.Tags) { if (!postDTO.Tags.Contains(tag)) { PostTag pt = new PostTag(); pt.PostId = post.Id; pt.TagId = tag.Id; await _postTagRepository.Delete(pt).ConfigureAwait(true); } } } await _postRepository.Edit(post); } catch (Exception ex) { return(StatusCode(500, ex)); throw; } return(Ok((await GetPost(id)).ToDTO())); }
public HttpResponseMessage SaveJunction(HttpRequestMessage request, JunctionViewModel junction) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { tbl_junction newJunction = new tbl_junction(); newJunction.AddJunction(junction); for (var i = 0; i < junction.junComponents.Count; i++) { var newJunComponent = new tbl_junctionComponents(); newJunComponent.tenant_id = junction.tenant_id; newJunComponent.project_id = newJunction.project_id; newJunComponent.junction_id = newJunction.id; newJunComponent.component = junction.junComponents[i].component; newJunComponent.quantity = junction.junComponents[i].quantity; newJunction.junComponents.Add(newJunComponent); } _junctionRepository.Add(newJunction); _unitOfWork.Commit(); for (var i = 0; i < junction.junComponents.Count; i++) { tbl_workprogress newworkprogress = new tbl_workprogress(); newworkprogress.tenant_id = junction.tenant_id; newworkprogress.junction_id = newJunction.id; newworkprogress.AddWorkprogress(junction); newworkprogress.jun_component = junction.junComponents[i].component; newworkprogress.total = junction.junComponents[i].quantity; newworkprogress.completed = 0; newworkprogress.pending = 0; newworkprogress.progress = 0; _workprogressRepository.Add(newworkprogress); tbl_workverification newworkverification = new tbl_workverification(); newworkverification.tenant_id = junction.tenant_id; newworkverification.project_id = junction.project_id; newworkverification.ps_id = junction.ps_id; newworkverification.junction_id = newJunction.id; newworkverification.subcontractor_id = 0; newworkverification.assigned_date = DateTime.Now; newworkverification.jun_component = junction.junComponents[i].component; newworkverification.total = junction.junComponents[i].quantity; newworkverification.completed = 0; newworkverification.verified_by = 0; newworkverification.verification_status = 0; newworkverification.verified_quantity = 0; newworkverification.nc_quantity = 0; newworkverification.created_date = DateTime.Now; _workverificationRepository.Add(newworkverification); _unitOfWork.Commit(); } response = request.CreateResponse <JunctionViewModel>(HttpStatusCode.Created, junction); } return response; })); }
public HttpResponseMessage Register(HttpRequestMessage request, RestaurantUserAddressViewModel restaurantuseraddressvm) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; UserViewModel uservm = new UserViewModel(); if (!ModelState.IsValid) { // response = request.CreateResponse(HttpStatusCode.BadRequest, new { success = false }); response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { if (restaurantuseraddressvm.RestaurantUserVM != null) { var existingUser = _userRepository.GetSingleByUsername(restaurantuseraddressvm.RestaurantUserVM.Username); if (existingUser != null) { //throw new Exception("Username is already in use"); // ModelState.AddModelError("Invalid user", "Email or User number already exists"); //response = request.CreateResponse(HttpStatusCode.BadRequest, //ModelState.Keys.SelectMany(k => ModelState[k].Errors) // .Select(m => m.ErrorMessage).ToArray()); response = request.CreateErrorResponse(HttpStatusCode.Ambiguous, "Email or User number already exists"); } else { //Add Address details Address newaddress = new Address(); Restaurant newRestaurant = new Restaurant(); RestaurantAddress newrestaurantAddress = new RestaurantAddress(); UserRestaurant newuserestaurant = new UserRestaurant(); //Note : - //Username --> Email Entities.User _user = _membershipService.CreateUser(restaurantuseraddressvm.RestaurantUserVM.Username, restaurantuseraddressvm.RestaurantUserVM.Username, restaurantuseraddressvm.RestaurantUserVM.Password, new int[] { 1 }); newRestaurant.UpdateRestaurant(restaurantuseraddressvm, _user.ID); _restaurant.Add(newRestaurant); _unitOfWork.Commit(); newuserestaurant.RestaurantId = newRestaurant.ID; newuserestaurant.UserId = _user.ID; _userrestaurant.Add(newuserestaurant); _unitOfWork.Commit(); //// Update view model //customer = Mapper.Map<Customer, CustomerViewModel>(newCustomer); //response = request.CreateResponse<CustomerViewModel>(HttpStatusCode.Created, customer); foreach (var restaurantAddress in restaurantuseraddressvm.RestaurantAddressVM) { newaddress.UpdateAddress(restaurantAddress, restaurantuseraddressvm.RestaurantUserVM.Username, _user.ID); _address.Add(newaddress); _unitOfWork.Commit(); newrestaurantAddress.RestaurantId = newRestaurant.ID; newrestaurantAddress.AddressId = newaddress.ID; _restaurantaddress.Add(newrestaurantAddress); _unitOfWork.Commit(); //int i = restaurantuseraddressvm.PlanID; foreach (var resturantsubscription in restaurantuseraddressvm.SubcriptionVM) { Subscription newsubscription = new Subscription(); newsubscription.SubscriptionPlanId = resturantsubscription.ID; newsubscription.StartDate = DateTime.UtcNow; newsubscription.TrialStartDate = DateTime.UtcNow; newsubscription.EndDate = GetPlanIntervalEnddate(resturantsubscription.IntervalId); newsubscription.EndDate = GetPlanIntervalEnddate(resturantsubscription.IntervalId); newsubscription.RestaurantId = newRestaurant.ID; newsubscription.TransId = ""; newsubscription.Status = true; _subscriptionRepository.Add(newsubscription); _unitOfWork.Commit(); } } if (_user != null) { uservm = Mapper.Map <User, UserViewModel>(_user); response = request.CreateResponse <UserViewModel>(HttpStatusCode.OK, uservm); // response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } else { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Registration failed. Try again."); } } } //restaurantuseraddressvm.RestaurantUserVM.Add(uservm); // response = request.CreateResponse<RestaurantUserAddressViewModel>(HttpStatusCode.OK, restaurantuseraddressvm); // response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } return response; })); }
public string RegisterOrUpdate(RegisterTeam validRegisterTeam) { try { string msg = null; var alreadyRegisteredTeam = _teamBaseRepo.GetSingle(team => team.TeamId == validRegisterTeam.TeamId, team => team.Users); if (alreadyRegisteredTeam == null) { // Register New Team var newTeam = new Team { TeamId = validRegisterTeam.TeamId, Location = validRegisterTeam.Location, RegisteredAt = validRegisterTeam.RequestTime, LastUpdatedAt = validRegisterTeam.RequestTime, SecretToken = Guid.NewGuid().ToString("N"), }; var Users = new List <User>(); foreach (var user in validRegisterTeam.TeamMembers) { Users.Add(new User { UserId = user, AddedAt = validRegisterTeam.RequestTime }); } newTeam.Users = Users; _teamBaseRepo.Add(newTeam); _teamBaseRepo.Commit(); msg = "Registration Success"; } else { // Update Already Registered Team // Delete all current users foreach (var user in alreadyRegisteredTeam.Users) { _userBaseRepo.Delete(user); } // Add all new users foreach (var user in validRegisterTeam.TeamMembers) { _userBaseRepo.Add(new User { UserId = user, AddedAt = validRegisterTeam.RequestTime, TeamId = alreadyRegisteredTeam.TeamId }); } alreadyRegisteredTeam.LastUpdatedAt = validRegisterTeam.RequestTime; _teamBaseRepo.Commit(); msg = "Team Updated"; } return(msg); } catch (Exception ex) { _logger.LogError($"Registration Failed | {validRegisterTeam.TeamId} | {validRegisterTeam.Location}"); _logger.LogError($"{ex}"); return(null); } }
private SharedProjectsDto AddSharedProjects(SharedProjectsDto sharedProjectsDto, string userID, string userName) { try { SharedProject sharedProjectDetails; SharedProject sharedProject = _sharedProjectsRepository.GetSingle(s => s.ProjectID == sharedProjectsDto.ProjectID && s.RecipientEmail.Equals(sharedProjectsDto.RecipientEmail, StringComparison.InvariantCultureIgnoreCase)); if (sharedProject != null) { foreach (var sharedSolutionID in sharedProjectsDto.SelectedSolutionList) { if (sharedProject.SharedProjectSolution.Where(s => s.SharedProjectID == sharedProject.ID && s.SolutionID == sharedSolutionID).Count() <= 0) { sharedProject.SharedProjectSolution.Add(new SharedProjectSolution { SharedProjectID = sharedProject.ID, SolutionID = sharedSolutionID, CreatedDateTime = DateTime.UtcNow, SharedDateTime = DateTime.UtcNow, ModifiedDateTime = DateTime.UtcNow, CreatedBy = userName, ModifiedBy = userName, Active = true }); } //else //{ // sharedProject.SharedProjectSolution.Remove(_sharedProjectSolutionRespository.GetSingle(s => s.SolutionID == sharedSolutionID)); //} } _sharedProjectsEntityToSharedProjectsDtoMapper.UpdateMap(sharedProjectsDto, sharedProject, userID); sharedProject.ModifiedDateTime = DateTime.UtcNow; sharedProject.ModifiedBy = userName; sharedProject.Active = true; sharedProjectDetails = _sharedProjectsRepository.Update(sharedProject); _sharedProjectsRepository.Commit(); } else { sharedProject = _sharedProjectsEntityToSharedProjectsDtoMapper.AddMap(sharedProjectsDto, userID); sharedProject.CreatedDateTime = DateTime.UtcNow; sharedProject.CreatedBy = userName; sharedProject.SharedDateTime = DateTime.UtcNow; sharedProject.ModifiedDateTime = DateTime.UtcNow; sharedProject.ModifiedBy = userName; sharedProject.Active = true; sharedProject.SharedProjectSolution = sharedProjectsDto.SelectedSolutionList.Select(solutionID => new SharedProjectSolution { SolutionID = solutionID, CreatedDateTime = DateTime.UtcNow, SharedDateTime = DateTime.UtcNow, ModifiedDateTime = DateTime.UtcNow, CreatedBy = userName, ModifiedBy = userName, Active = true }).ToList(); sharedProjectDetails = _sharedProjectsRepository.Add(sharedProject); _sharedProjectsRepository.Commit(); } Project sharedProjectRow = _projectRepository.GetSingle(p => p.ID == sharedProjectsDto.ProjectID); var sharedProjectName = sharedProjectRow.ProjectName; var sharerUserName = sharedProjectRow.User.FirstName + " " + sharedProjectRow.User.LastName; return(new SharedProjectsDto { SharedProjectID = sharedProjectDetails.ID, SharedProjectName = sharedProjectName, SharerUserName = sharerUserName }); } catch (Exception ex) { throw ex; } }
public void CreateDevice(Device device) { _deviceRepository.Add(device); _unitOfWork.Commit(); }
public HttpResponseMessage UpdateWorkVerification(HttpRequestMessage request, WorkVerification wrkvrfcn) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { var existrecord = _workverificationRepository.GetSingle(wrkvrfcn.id); existrecord.comments = wrkvrfcn.comments; existrecord.verification_status = wrkvrfcn.verification_status; existrecord.nc_quantity = wrkvrfcn.nc_quantity; existrecord.verified_quantity = existrecord.total - wrkvrfcn.nc_quantity; existrecord.created_date = DateTime.Now; _workverificationRepository.Edit(existrecord); tbl_workverification_history exitwvh = new tbl_workverification_history(); exitwvh.tenant_id = existrecord.tenant_id; exitwvh.project_id = existrecord.project_id; exitwvh.ps_id = existrecord.ps_id; exitwvh.junction_id = existrecord.junction_id; exitwvh.subcontractor_id = existrecord.subcontractor_id; exitwvh.junction_component = existrecord.jun_component; exitwvh.total = existrecord.total; exitwvh.completed = existrecord.completed; exitwvh.verified_quantity = existrecord.verified_quantity; exitwvh.nc_quantity = existrecord.nc_quantity; exitwvh.comments = existrecord.comments; exitwvh.verification_status = existrecord.verification_status; exitwvh.verified_by = existrecord.verified_by; exitwvh.created_date = DateTime.Now; _workverificationhistoryRepository.Add(exitwvh); if (wrkvrfcn.verification_status == 57) { var NCList = _nonconfirmityworksRepository.GetAll().Where(x => x.work_verification_id == wrkvrfcn.id).FirstOrDefault(); if (NCList != null) { var existingNCRecord = _nonconfirmityworksRepository.GetSingle(NCList.id); existingNCRecord.verification_status = wrkvrfcn.verification_status; existingNCRecord.comments = wrkvrfcn.comments; existingNCRecord.created_date = DateTime.Now; _nonconfirmityworksRepository.Edit(existingNCRecord); } else { tbl_nonconfirmity_works newwvhistory = new tbl_nonconfirmity_works(); var existwv = _workverificationRepository.GetSingle(wrkvrfcn.id); newwvhistory.tenant_id = existwv.tenant_id; newwvhistory.project_id = existwv.project_id; newwvhistory.ps_id = existwv.ps_id; newwvhistory.junction_id = existwv.junction_id; newwvhistory.subcontractor_id = existwv.subcontractor_id; newwvhistory.work_verification_id = existwv.id; newwvhistory.junction_component = existwv.jun_component; newwvhistory.total = existwv.total; newwvhistory.completed = existwv.completed; newwvhistory.verified_quantity = existwv.verified_quantity; newwvhistory.nc_quantity = existwv.nc_quantity; newwvhistory.comments = existwv.comments; newwvhistory.verification_status = existwv.verification_status; newwvhistory.created_date = DateTime.Now; _nonconfirmityworksRepository.Add(newwvhistory); } } _unitOfWork.Commit(); response = request.CreateResponse(HttpStatusCode.OK); } return response; })); }
public HttpResponseMessage SaveSubContractor(HttpRequestMessage request, SubContractorViewModel subcontractor) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { var newSubContractor = new tbl_subcontractor() { tenant_id = subcontractor.tenant_id, project_id = subcontractor.project_id, company_name = subcontractor.company_name, reg_No = subcontractor.reg_No, subcontractor_name = subcontractor.subcontractor_name, current_street = subcontractor.current_street, current_country = subcontractor.current_country, current_state = subcontractor.current_state, current_city = subcontractor.current_city, current_zip = subcontractor.current_zip, current_contact_number = subcontractor.current_contact_number, alternative_contactNumber = subcontractor.alternative_contactNumber, contractor_photo_file_name = subcontractor.contractor_photo_file_name, service_tax_no = subcontractor.service_tax_no, pan = subcontractor.pan, bank_account_no = subcontractor.bank_account_no, bank_name = subcontractor.bank_name, bank_branch = subcontractor.bank_branch, ifsc = subcontractor.ifsc, contractor_photo = subcontractor.contractor_photo, contractor_photo_file_type = subcontractor.contractor_photo_file_type, agreement = subcontractor.agreement, agreement_file_type = subcontractor.agreement_file_type, contractor_agreement_file_name = subcontractor.contractor_agreement_file_name, created_date = DateTime.Now, created_by = subcontractor.created_by, modified_date = DateTime.Now, modified_by = subcontractor.modified_by, email_id = subcontractor.email_id }; for (int i = 0; i < subcontractor.scomponentslist.Count; i++) { var newscComponents = new tbl_subcontractor_components(); newscComponents.tenant_id = subcontractor.tenant_id; newscComponents.project_id = subcontractor.project_id; newscComponents.subcontractor_id = newSubContractor.id; newscComponents.subcontractor_name = subcontractor.subcontractor_name; newscComponents.component_id = subcontractor.scomponentslist[i].component_id; newscComponents.component_name = subcontractor.scomponentslist[i].component_name; _subcontractorRepository.Add(newSubContractor); _scComponentsRepository.Add(newscComponents); } _unitOfWork.Commit(); response = request.CreateResponse <SubContractorViewModel>(HttpStatusCode.Created, subcontractor); } return response; })); }
public HttpResponseMessage Get(HttpRequestMessage request) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; var Data = GenerateData.GenerateKey_Sys_Units(); try { foreach (Key_Sys_Unit key_sys_unit in Data) { Sys_Unit newsys_unit = new Sys_Unit(); newsys_unit.Website = key_sys_unit.Key.ToMD5() + ".netschool.vn"; newsys_unit.ParentUnitID = 40; newsys_unit.Note = key_sys_unit.Encodedomain; newsys_unit.CreatedDate = DateTime.Now; newsys_unit.ModifiedDate = DateTime.Now; newsys_unit.ModifiedBy = 1; newsys_unit.CreatedBy = 1; newsys_unit.Infor = "Generate Data"; //add sys_unit _sys_unitsRepository.Add(newsys_unit); _unitOfWork.Commit(); key_sys_unit.UnitID = newsys_unit.UnitID; //add key_sys_unit _key_sys_unitsRepository.Add(key_sys_unit); WebSecurity.CreateUserAndAccount(key_sys_unit.Encodedomain, "12345678"); //Get UserByName int UserId = WebSecurity.GetUserId(key_sys_unit.Encodedomain); if (UserId > 0) { Sys_User newsys_user = new Sys_User(); newsys_user.DateOfBirth = DateTime.Now; newsys_user.iType = key_sys_unit.UnitID; newsys_user.CreatedDate = DateTime.Now; newsys_user.ModifiedDate = DateTime.Now; newsys_user.ModifiedBy = 1; newsys_user.CreatedBy = 1; newsys_user.Infor = "Generate Data"; newsys_user.Role = 7; newsys_user.UserID = UserId.ToString(); newsys_user.UserName = key_sys_unit.Encodedomain; newsys_user.LoginName = key_sys_unit.Encodedomain; newsys_user.LastIPAddress = null; newsys_user.LastLoginDate = DateTime.Now; newsys_user.Year = DateTime.Now.AddYears(1); _sys_userRepository.Add(newsys_user); } _unitOfWork.Commit(); } response = request.CreateResponse(HttpStatusCode.OK, "Successful"); } catch (Exception ex) { response = request.CreateResponse(HttpStatusCode.ExpectationFailed, ex); } return response; })); }
public ResponseViewModel SaveUpdateStreetData(StreetVM streetVM) { try { if (streetVM.Id == 0) { //add if (streetVM != null) { Street data = new Street(); if (streetVM.UserType == UserType.Supervisor) { data.StreetName = streetVM.StreetName; data.CreatedBy = streetVM.CreatedBy; if (data != null) { streetRepository.Add(data); unitOfWork.Commit(); } if (data != null && data.Id > 0) { AssignStreet assginstreet = new AssignStreet(); assginstreet.StreetId = data.Id; assginstreet.SupervisorId = streetVM.CreatedBy; assignStreetRepository.Add(assginstreet); unitOfWork.Commit(); } } else { //data = Mapper.Map<Street>(streetVM); data.StreetName = streetVM.StreetName; data.CreatedBy = streetVM.CreatedBy; if (data != null) { streetRepository.Add(data); unitOfWork.Commit(); } } response.Status = "SUCCESS"; response.IsSuccess = true; response.Message = "Record Saved successfully..."; response.Content = null; } } else { //update } } catch (Exception ex) { response.IsSuccess = false; response.Status = "FAILED"; response.Content = null; if (response.ReturnMessage == null) { response.ReturnMessage = new List <string>(); } response.ReturnMessage.Add(ex.Message); } return(response); }
public Servicio Guardar(Servicio servicio) { var servicioRepo = new Servicio(); bool EsEdicion = servicio.Id != 0; if (EsEdicion) { if (!string.IsNullOrEmpty(servicio.Radicado) && _servicioRepositorio.FindBy(s => s.Radicado == servicio.Radicado && s.Id != servicio.Id).Count() > 0) { if (servicio.TipoServicio.Id != 6 && servicio.TipoServicio.Id != 3) { throw new Exception("El consecutivo ingresado ya se encuentra registrado."); } } servicioRepo = _servicioRepositorio.FindByIncluding(s => s.Id == servicio.Id, s => s.Movimientos).FirstOrDefault(); servicioRepo.FechaModificacion = DateTime.Now; servicioRepo.UsuarioModificacionId = servicio.UsuarioModificacionId; } else { if (_servicioRepositorio.FindBy(s => s.Radicado == servicio.Radicado).Count() > 0 && !string.IsNullOrEmpty(servicio.Radicado)) { if (servicio.TipoServicio.Id != 6) { throw new Exception("El consecutivo ingresado ya se encuentra registrado."); } } servicioRepo.FechaModificacion = DateTime.Now; servicioRepo.UsuarioModificacionId = servicio.UsuarioModificacionId; servicioRepo.FechaRegistro = DateTime.Now; servicioRepo.UsuarioRegistroId = servicio.UsuarioRegistroId; servicioRepo.SucursalId = servicio.SucursalId; if (!servicio.TipoServicio.RequiereSeguimiento) { servicio.EstadoCodigo = "TE"; servicio.Fecha = servicio.Fecha.AddHours(18); servicio.Hora = new TimeSpan(18, 0, 0); } else { servicio.EstadoCodigo = "RG"; } } servicioRepo.EstadoCodigo = servicio.EstadoCodigo; servicioRepo.TipoServicioId = servicio.TipoServicio.Id; servicioRepo.Hora = servicio.Hora; servicioRepo.Fecha = servicio.Fecha; servicioRepo.Radicado = servicio.Radicado; servicioRepo.AsignadoPor = servicio.AsignadoPor; servicioRepo.Observacion = servicio.Observacion; servicioRepo.Notificado = false; if (servicio.Aseguradora != null) { servicioRepo.AseguradoraId = servicio.Aseguradora.Id; } if (servicio.Asegurado != null) { _aseguradoService.Guardar(servicio.Asegurado); servicioRepo.AseguradoId = servicio.Asegurado.Id; } if (servicio.Vehiculo != null) { _vehiculoService.Guardar(servicio.Vehiculo); servicioRepo.VehiculoId = servicio.Vehiculo.Id; } if (servicio.DireccionInicio != null) { _direccionService.Guardar(servicio.DireccionInicio); servicioRepo.DireccionInicioId = servicio.DireccionInicio.Id; } if (servicio.DireccionDestino != null) { _direccionService.Guardar(servicio.DireccionDestino); servicioRepo.DireccionDestinoId = servicio.DireccionDestino.Id; } if (servicio.Conductor == null) { servicioRepo.ConductorId = null; } else { servicioRepo.ConductorId = servicio.Conductor.Id; } if (servicio.Ruta == null) { servicioRepo.RutaId = null; } else { servicioRepo.RutaId = servicio.Ruta.Id; } if (servicioRepo.Movimientos != null) { servicioRepo.Movimientos.ToList().ForEach(movimiento => { if (movimiento.Concepto.TipoConcepto == TipoConcepto.Proveedor && movimiento.Concepto.TipoProveedor == TipoProveedor.Conductor) { movimiento.ProveedorId = servicio.ConductorId; } if (movimiento.Concepto.TipoConcepto == TipoConcepto.Proveedor && movimiento.Concepto.TipoProveedor == TipoProveedor.Ruta) { movimiento.ProveedorId = servicio.RutaId; } if (movimiento.Concepto.TipoConcepto == TipoConcepto.Cliente) { movimiento.ClienteId = servicio.AseguradoraId; } }); } if (EsEdicion) { _servicioRepositorio.Edit(servicioRepo); } else { servicioRepo = _servicioRepositorio.Add(servicioRepo); } _unitOfWork.Commit(); return(servicioRepo); //if (servicio.Id == 0) //{ // if (_servicioRepositorio.FindBy(s => s.Radicado == servicio.Radicado).Count() > 0 && !string.IsNullOrEmpty(servicio.Radicado)) // { // throw new Exception("El consecutivo ingresado ya se encuentra registrado."); // } // servicioRepo.TipoServicio = servicio.TipoServicio; // servicioRepo.UsuarioRegistroId = servicio.UsuarioRegistroId; // servicioRepo.EstadoCodigo = "RG"; // servicioRepo.Fecha = servicio.Fecha; // servicioRepo.Hora = servicio.Hora; // servicioRepo.Radicado = servicio.Radicado; // servicioRepo.AsignadoPor = servicio.AsignadoPor; // if (servicio.Aseguradora != null) // { // servicioRepo.AseguradoraId = servicio.Aseguradora.Id; // } // if (servicio.Asegurado != null) // { // _aseguradoService.Guardar(servicio.Asegurado); // servicioRepo.AseguradoId = servicio.Asegurado.Id; // } // if (servicio.Vehiculo != null) // { // _vehiculoService.Guardar(servicio.Vehiculo); // servicioRepo.VehiculoId = servicio.Vehiculo.Id; // } // if (servicio.DireccionInicio != null) { // _direccionService.Guardar(servicio.DireccionInicio); // servicioRepo.DireccionInicioId = servicio.DireccionInicio.Id; // } // if (servicio.DireccionDestino != null) // { // _direccionService.Guardar(servicio.DireccionDestino); // servicioRepo.DireccionDestinoId = servicio.DireccionDestino.Id; // } // servicioRepo.FechaModificacion = DateTime.Now; // servicioRepo.FechaRegistro = DateTime.Now; // servicioRepo.Observacion = servicio.Observacion; // if (servicio.Conductor == null) // servicioRepo.ConductorId = null; // else // servicioRepo.ConductorId = servicio.Conductor.Id; // if (servicio.Ruta == null) // servicioRepo.RutaId = null; // else // servicioRepo.RutaId = servicio.Ruta.Id; // servicioRepo = _servicioRepositorio.Add(servicioRepo); //} //else //{ // if (!string.IsNullOrEmpty(servicio.Radicado) && _servicioRepositorio.FindBy(s => s.Radicado == servicio.Radicado && s.Id != servicio.Id).Count() > 0) // { // throw new Exception("El consecutivo ingresado ya se encuentra registrado."); // } // servicioRepo = _servicioRepositorio.FindBy(s => s.Id == servicio.Id).FirstOrDefault(); // servicioRepo.TipoServicio = servicio.TipoServicio; // servicioRepo.UsuarioModificacionId = servicio.UsuarioModificacionId; // servicioRepo.Fecha = servicio.Fecha; // servicioRepo.Hora = servicio.Hora; // servicioRepo.Radicado = servicio.Radicado; // servicioRepo.EstadoCodigo = servicio.EstadoCodigo; // servicioRepo.AsignadoPor = servicio.AsignadoPor; // servicioRepo.AseguradoraId = servicio.Aseguradora.Id; // _aseguradoService.Guardar(servicio.Asegurado); // servicioRepo.AseguradoId = servicio.Asegurado.Id; // _vehiculoService.Guardar(servicio.Vehiculo); // servicioRepo.VehiculoId = servicio.Vehiculo.Id; // _direccionService.Guardar(servicio.DireccionInicio); // servicioRepo.DireccionInicioId = servicio.DireccionInicio.Id; // _direccionService.Guardar(servicio.DireccionDestino); // servicioRepo.DireccionDestinoId = servicio.DireccionDestino.Id; // servicioRepo.FechaModificacion = DateTime.Now; // servicioRepo.Observacion = servicio.Observacion; // if (servicio.Conductor == null) // servicioRepo.ConductorId = null; // else // servicioRepo.ConductorId = servicio.Conductor.Id; // if (servicio.Ruta == null) // servicioRepo.RutaId = null; // else // servicioRepo.RutaId = servicio.Ruta.Id; // servicioRepo.Notificado = false; // _servicioRepositorio.Edit(servicioRepo); //} //_unitOfWork.Commit(); //return servicioRepo; }
/// <summary> /// /// </summary> /// <param name="addressInformation"></param> /// <param name="transaction"></param> /// <returns></returns> public Address ManipulateAddress(AddressModel addressInformation, out TransactionalBase transaction) { transaction = new TransactionalBase(); Address address = _addressDataService.GetAll().Where(a => a.Id == addressInformation.Id).FirstOrDefault(); try { if (address == null) { address = new Address(); address.CreatedByIp = addressInformation.IpAddress; address.CreatedOn = DateTime.Now; } else { address.UpdatedByIp = addressInformation.IpAddress; address.UpdatedOn = DateTime.Now; } address.Name = addressInformation.Name; address.AddressLine1 = addressInformation.AddressLine1; address.AddressLine2 = addressInformation.AddressLine2; address.City = addressInformation.City; address.State = addressInformation.State; address.Country = addressInformation.Country; address.ZipCode = addressInformation.ZipCode; address.MobileNumber = addressInformation.MobileNumber; address.Customer = new Customer() { Id = addressInformation.CustomerId }; AddressBusinessRules customerBusinessRules = new AddressBusinessRules(_addressDataService, address); ValidationResult results = customerBusinessRules.Validate(address); bool validationSucceeded = results.IsValid; IList <ValidationFailure> failures = results.Errors; if (validationSucceeded == false) { transaction = ValidationErrors.PopulateValidationErrors(failures); return(address); } if (address.Id == Guid.Empty) { _addressDataService.Add(address); } _addressDataService.Commit(); transaction.ReturnStatus = true; transaction.ReturnMessage.Add("Address successfully updated."); } catch (Exception ex) { string errorMessage = ex.Message; transaction.ReturnMessage.Add(errorMessage); transaction.ReturnStatus = false; } finally { } return(address); }