public ActionResult Create(UserInputModel userInputModel) { _repository = new InMemoryRepository(); _authenticator = new CookieAuthenticator(); if (_repository.GetAll<User>().Any(x => x.Username == userInputModel.Username)) { ModelState.AddModelError("Username", "Username is already in use"); } if (ModelState.IsValid) { var user = new User { Id = Guid.NewGuid(), Username = userInputModel.Username, Password = HashPassword(userInputModel.Password), }; _repository.SaveOrUpdate(user); _authenticator.SetCookie("72201781859E67D4F633C34381EFE4BC928656AEE324A4B00CADA968ACD6CF33047E47479B0B68050FF4A0DB13688B5C78DAFDF53252A94E7F1D7B58A6FFD95D747F3D3AA761DECA7B6358A2E78B85D868833A9420316BDA8A5A0425D543AC1148CB69B902195C20065446A5E5F7A8E4C94A04A22304680E1211F00A12DF5E8777A343D08D0F8C0A3BFC471381E9B070E0F0608ADAEBCA8E233A21251BF57A03B52C1F03B7169CFC7C98216E7217EA649C4EDBD35E07F11A2444D40BE303BFFA28BAA921CDCC298D09A6E0297ED7D6E8"); return RedirectToAction("Index", "Home"); } return View("New", userInputModel); }
public void EditCategory(Category category) { try { categoryRepository.SaveOrUpdate(category); } catch { throw; } }
/// <summary> /// Register te entity for save or update in the database when the unit of work /// is completed. (INSERT or UPDATE) /// </summary> /// <param name="repository"></param> /// <param name="entities">the entities to save</param> public static void SaveOrUpdate <TEntity>(this IRepository <TEntity> repository, params TEntity[] entities) { using (var tx = repository.BeginTransaction()) { foreach (var entity in entities) { repository.SaveOrUpdate(entity); } tx.Commit(); } }
public IActionResult Save(int id, [FromBody] Product.Edit model) { if (ModelState.IsValid) { var item = GetProduct(id); if (item == null) { return(NotFound()); } mapper.Map(model, item); repository.SaveOrUpdate(item); return(Ok(mapper.Map <Product.Edit>(item))); } return(BadRequest(ModelState)); }
public void EditSize(Size size) { try { sizeRepository.SaveOrUpdate(size); } catch { throw; } }
public void EditColor(Color color) { try { colorRepository.SaveOrUpdate(color); } catch { throw; } }
/// <summary>Creates a container.</summary> /// <param name="containerContainer"></param> /// <param name="setupCreatedItem"></param> /// <param name="name">optional name</param> /// <returns></returns> protected virtual T Create(ContentItem containerContainer, Action <T> setupCreatedItem, string name = null) { var container = activator.CreateInstance <T>(containerContainer); container.Name = name; container.AddTo(containerContainer); setupCreatedItem(container); repository.SaveOrUpdate(container); return(container); }
public ActionResult Start(StartRegistrationModel startRegistrationModel) { if (_repository.GetAll <User>().Any(x => x.Username == startRegistrationModel.Username)) { ModelState.AddModelError("Username", "Username is already in use"); } if (_repository.GetAll <User>().Any(x => x.EmailAddress == startRegistrationModel.EmailAddress)) { ModelState.AddModelError("EmailAddress", "Email address is already in use"); } if (ModelState.IsValid) { var verificationCode = Cryptography.RandomString(12); var user = new Registration { Id = Guid.NewGuid(), Username = startRegistrationModel.Username, EmailAddress = startRegistrationModel.EmailAddress, Password = Cryptography.Hash(startRegistrationModel.Password), Expires = DateTime.UtcNow.AddDays(3), VerificationCode = Cryptography.Hash(verificationCode) }; var registrationConfirmation = new RegistrationConfirmation { Username = startRegistrationModel.Username, EmailAddress = startRegistrationModel.EmailAddress, VerificationCode = verificationCode }; _confirmationEmailer.Send(registrationConfirmation); _repository.SaveOrUpdate(user); return(RedirectToAction( "Complete", "Registration", new { startRegistrationModel.Username, startRegistrationModel.EmailAddress })); } return(View(startRegistrationModel)); }
public ActionResult New(ProductViewData productViewData) { var product = productBuilder.ProductFromProductViewData(productViewData, ModelState, Request); if (ModelState.IsValid) { productRepository.SaveOrUpdate(product); uow.Commit(); //Need explicit commit in order to get the product id. return(this.RedirectToAction(x => x.Edit(product.Id))); } return(View("Edit", productViewData.WithErrorMessage("There were errors, please correct them and resubmit."))); }
private static async Task <int> GetOrCreateValue <T, TValue>(T entity, TValue value, IUnitOfWork uow, string column, IRepository <T, int> repository) where T : class, IEntity <int> { return(await Task.Run(() => { var actual = uow.Find <T>(statement => { statement.Where($"{column:C} = @p1") .WithParameters(new { p1 = value }); }).FirstOrDefault(); return actual?.Id ?? repository.SaveOrUpdate(entity, uow); })); }
public ActionResult Create(Game game) { if (ViewData.ModelState.IsValid && game.IsValid()) { gameRepository.SaveOrUpdate(game); Message = "Игра успешно создана."; return(this.RedirectToAction(c => c.Index())); } return(View(game)); }
public ActionResult Create(ProductCreateModel model) { try { Store store = StoreRepository.Get(s => s.Id.Equals(model.StoreID)).SingleOrDefault(); var htmlBanner = string.Format(_productTemplate, model.ImagePath, model.Name, model.Price); store.AddProduct(new Product() { Name = model.Name, Price = model.Price, HtmlBanner = Server.HtmlEncode(htmlBanner) }); StoreRepository.SaveOrUpdate(store); StoreRepository.SaveOrUpdate(store); return(RedirectToAction("Index", "Store")); } catch { return(View(model)); } }
public ActionResult New([EntityBind(Fetch = false)] Menu content) { CheckForDuplicateName(content); if (ModelState.IsValid) { menuRepository.SaveOrUpdate(content); Message = "New menu has been successfully added."; return(this.RedirectToAction(c => c.List(content.ParentContent.Id))); } return(View("Edit", CmsView.Data.WithContent(content))); }
public ActionResult SaveWebTemplate(string html, string name) { WebTemplate item = new WebTemplate(); item.Html = html; item.Name = name; WebTemplateRepository.SaveOrUpdate(item); var model = new TinymceInitSettingsModel(); model.templates = GetTemplatesList(); return(Json(model, JsonRequestBehavior.AllowGet)); }
public ActionResult Add([EntityBind(Fetch = false)] TextContent content) { CheckForDuplicateName(content); if (ModelState.IsValid) { contentRepository.SaveOrUpdate(content); Message = "Changes have been saved."; return(this.RedirectToAction <MenuController>(c => c.List(content.ParentContent.Id))); } return(View("Edit", CmsView.Data.WithContent(content))); }
private void SaveAction(ContentItem item) { if (item is IActiveContent) { (item as IActiveContent).Save(); } else { if (!item.VersionOf.HasValue) { item.Updated = Utility.CurrentTime(); } if (string.IsNullOrEmpty(item.Name)) { item.Name = null; } itemRepository.SaveOrUpdate(item); EnsureName(item); } }
public virtual void CreateRole(String roleName) { if (!RoleExists(roleName)) { roleRepository.SaveOrUpdate( new Role(roleName)); } else { new RoleExistsException(roleName); } }
public virtual TModel SaveOrUpdate(TModel entity) { TModel retValue = default(TModel); ExecuteInTransaction(() => { OnUpdating(entity); retValue = repository.SaveOrUpdate(entity); OnUpdated(retValue); }); return(retValue); }
private static void SaveOrUpdateChildrenRecursive(IRepository <ContentItem> repository, ContentItem parent) { repository.SaveOrUpdate(parent); if (parent.ChildState == Collections.CollectionState.IsEmpty) { return; } foreach (var child in parent.Children) { SaveOrUpdateChildrenRecursive(repository, child); } }
public User CreateNewCustomer() { // TODO: Will Role.Customer get saved correctly by NH? var user = new User { Email = Guid.NewGuid().ToString(), Password = "", Role = Role.Customer }; userRepository.SaveOrUpdate(user); return(user); }
public override MigrationResult Migrate(DatabaseStatus preSchemaUpdateStatus) { var root = repository.Get(preSchemaUpdateStatus.RootItemID); root[InstallationManager.InstallationAppPath] = N2.Web.Url.ToAbsolute("~/"); repository.SaveOrUpdate(root); repository.Flush(); return(new MigrationResult(this) { UpdatedItems = 1 }); }
/// <summary> /// Method which computes the Balance points of an account /// //TODO: Modify this to work only over certain time period /// </summary> /// <param name="account"></param> /// <returns></returns> private Dictionary <DateTime, BalancePoint> ComputeBalancePoints(Account account) { Dictionary <DateTime, BalancePoint> result = new Dictionary <DateTime, BalancePoint>(); if (account.Operations.Count > 0) { var parDate = account.Operations .OrderBy(x => x.Date.Date) .GroupBy(x => x.Date.Date) .ToDictionary(x => x.Key, x => x.ToList()); decimal previousDate = 0; for (DateTime date = parDate.Keys.First(); date.CompareTo(DateTime.Now) <= 0; date = date.AddDays(1)) { BalancePoint point = null; if (parDate.ContainsKey(date)) { List <Operation> operationsToAdd = parDate[date]; point = new BalancePoint() { Date = date.Date, Balance = previousDate + operationsToAdd.Sum(x => x.SignedAmount) }; } else { point = new BalancePoint() { Date = date, Balance = previousDate }; } result.Add(date.Date, point); previousDate = result[date].Balance; _repository.SaveOrUpdate(point); } } return(result); }
public virtual IValidationContainer <T> SaveOrUpdate(T entity) { var validation = entity.GetValidationContainer(); if (!validation.IsValid) { return(validation); } Repository.SaveOrUpdate(entity); UnitOfWork.Commit(); return(validation); }
public ActionResult Create(CustomerFormViewModel viewModel) { if (!ViewData.ModelState.IsValid) { TempData.SafeAdd(viewModel); return(this.RedirectToAction(c => c.Create())); } try { var customer = new Customer { Code = viewModel.Code, Name = viewModel.Name }; _customerRepository.SaveOrUpdate(customer); TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = string.Format("Successfully created customer '{0}'", customer.Name); } catch (Exception ex) { TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = string.Format("An error occurred creating the customer: {0}", ex.Message); return(this.RedirectToAction(c => c.Create())); } return(this.RedirectToAction(c => c.Index(null))); }
public ActionResult Create(TenantFormViewModel viewModel) { if (!ViewData.ModelState.IsValid) { TempData.SafeAdd(viewModel); return(this.RedirectToAction(c => c.Create())); } try { var tenant = new Tenant { Name = viewModel.Name, Domain = viewModel.Domain, ConnectionString = viewModel.ConnectionString }; _tenantRepository.SaveOrUpdate(tenant); TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = string.Format("Successfully created tenant '{0}'", tenant.Name); } catch (Exception ex) { TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = string.Format("An error occurred creating the tenant: {0}", ex.Message); return(this.RedirectToAction(c => c.Create())); } return(this.RedirectToAction(c => c.Index(null))); }
public void Handle(SizeCreatedEvent sizeCreatedEvent) { var productName = sizeCreatedEvent.ProductName; var sizeName = sizeCreatedEvent.SizeName; var stockItem = StockItem.Create(productName, sizeName, now(), currentUser()); if (!sizeCreatedEvent.IsActive) { stockItem.Deactivate(now(), currentUser()); } stockItemRepository.SaveOrUpdate(stockItem); }
public void AddTemplate(ContentItem templateItem) { TemplateContainer templates = container.GetOrCreateBelowRoot((c) => { c.Title = "Templates"; c.Name = "Templates"; c.Visible = false; c.SortOrder = int.MaxValue - 1001000; }); templateItem.Name = null; templateItem.AddTo(templates); repository.SaveOrUpdate(templateItem); }
public ActionResult Index(CheckoutViewData checkoutViewData) { var order = checkoutService.OrderFromCheckoutViewData(checkoutViewData, ModelState); if (ModelState.IsValid) { orderRepository.SaveOrUpdate(order); //we need an explicit Commit in order to obtain the db-generated Order Id unitOfWork.Commit(); return(this.RedirectToAction(c => c.Confirm(order.Id))); } return(View("Index", checkoutViewData)); }
internal void Save() { Product newProduct = new Product { Name = Name, Color = ColorSelectListItems.FirstOrDefault(x => x.Value.Equals(SelectedColor, StringComparison.InvariantCultureIgnoreCase)).Text, ListPrice = ListPrice.Value, ReorderPoint = ReorderPoint.Value, SafetyStockLevel = SafetyStockLevel.Value, StandardCost = StandardCost.Value }; repository.SaveOrUpdate(newProduct); }
public ActionResult Create(Product book) { //try //{ _productRepository.SaveOrUpdate(book); return(RedirectToAction("Index")); //} //catch (Exception exception) //{ // TempData["warning"] = exception.Message; // return View(); //} }
/// <summary> /// Inicia la acceso de un usuario al sistema /// </summary> /// <param name="usuario">usuario con el inicio la sesion </param> /// <param name="rol">rol con el que inicio la sesion</param> /// <param name="ipAddress">direccion Ip del usuario que inicio la sesion</param> public void InitializeUserAccess(IInitializeUserAccess iInitializeUserAccess) { //Usuario usuario, Rol rol, string ipAddress //TOD: JSA, ESTO ES UN FLUJO DE AUTENTIFICACION DEL SISTEMA //1. APLICAR LAS REGLAS DE ACCESO //2. INICIALIZA PRINCIPAL //3. Iniciar sesion var initializeUserAccessWeb = iInitializeUserAccess as InitializeUserAccessWeb; if (initializeUserAccessWeb == null) { throw new ArgumentNullException("initializeUserAccessWeb"); } var usuario = initializeUserAccessWeb.usuario; var rol = initializeUserAccessWeb.rol; var ipAddress = initializeUserAccessWeb.ipAddress; _accessAuthorizer.CheckRules(usuario.Cuenta); Sesion sesion = new Sesion(); sesion.Cuenta = usuario.Cuenta; sesion.Inicio = DateTime.Now; sesion.EstadoId = EstadoSesion.Iniciada; sesion.RolId = rol.Id; sesion.IpAddress = ipAddress; sesion = _repositorySesion.SaveOrUpdate(sesion); //Establecer objetos de acceso _application.SetCurrentUser(usuario); _application.SetCurrentRol(rol); _application.SetCurrentSession(sesion); }
public static IImmaginiModel ImportImages(IRepository<Immagine> repository, IImageBlobManager azureBlobManager, IImmaginiModel father, List<string> imageIdList) { if (father == null) return null; var immagini = repository.GetAll().Where(el => imageIdList.Contains(el.Id)).ToList(); foreach (var immagine in immagini) { var clone = immagine.Clone(); clone.Id = null; clone.IDPadre = father.Id; repository.SaveOrUpdate(clone); // non importa perchè sfrutto il riferimento contenuto in IDFileImmagine // ImportImagesAzure(azureBlobManager, BuildFileName(immagine), BuildFileName(clone)); father.Immagini.Add(clone); } return father; }
private static PlaylistSongRating SaveSong(IRepository repository, Playlist playlist, FbUser votingUser, string artistName, string songName, double duration, string videoId, short rating, string imageUrl) { var song = new Song { Name = songName, ArtistName = artistName, Duration = duration, VideoID = videoId, ImageUrl = imageUrl }; repository.Save(song); var playlistRating = playlist.AddSong(song, votingUser, playlist.IsOwner(votingUser.Id)); repository.SaveOrUpdate(playlistRating); return playlistRating; }