public User CreateUser(string username, string email, string password, int[] roles) { if (_data.GetSingleByUsername(username) != 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 }; _data.Add(user); _data.Commit(); if (roles != null || roles.Length > 0) { foreach (var role in roles) { addUserToRole(user, role); } } _data.Commit(); return(user); }
public NewEntityViewModel(IDataService <TEntity> service, IDialogService dialogService) { this.Create = ReactiveCommand.CreateFromTask(() => service.Add(this.CreateEntity())); this.Create.Subscribe(entity => dialogService.Close(entity)); this.Cancel = ReactiveCommand.Create(() => dialogService.Close()); }
public string Execute() { CollectData(); string movieTitle = collectedData[0]; ICollection <string> movieGenres = collectedData[1].Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); string movieDescription = collectedData[2]; string movieDirector = collectedData[3]; ICollection <string> movieActors = collectedData[4].Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); int movieYear = int.Parse(collectedData[5]); //creating Movie object from the user's input parameters. Movie newMovie = new Movie() { Title = movieTitle, Genre = movieGenres, Description = movieDescription, Director = movieDirector, Actors = movieActors, Year = movieYear, IsNew = true }; //adding movie to in-memory collection. dataService.Add(newMovie); //saving movie to external data file. outputController.SaveMovieToFile(newMovie); return(@" ====================================================================================================================================== New Movie Is Registered! ======================================================================================================================================"); }
public async Task <IHttpActionResult> Post([FromBody] ProductDto dto) { if (ModelState.IsValid == false) { return(BadRequest("Invalid data")); } if (dto.ProductOwner != (Thread.CurrentPrincipal as UserPrincipal).Id) { return(Unauthorized()); } var product = _assembler.DtoToEntity(dto); var result = await _service.Add(product); if (result == ErrorValue.EntityExists) { return(BadRequest("Such product already exists.")); } else if (result == ErrorValue.ServerError) { return(BadRequest("Transaction error")); } dto = _assembler.EntityToDto(product); return(Ok(dto)); }
public override bool Save() { var columns = new List <PropertyInfo>(); while (Dirty.TryTake(out var e)) { columns.Add(e); } try { if (Target is IEntity <int> ei && ei.Id < 0) { var t = _data.Add <T>(e => Target.CopyPrimitivesTo(e)); ei.Id = (int)t.Id; return(true); } if (_data.Update(Target, columns.Select(e => e.Name).ToArray())) { IsDirty = false; return(true); } return(false); } catch { foreach (var p in columns) { Dirty.Add(p); } throw; } }
private void AddResult(SampleTestResult previous) { int i = 0; foreach (var r in Results.List) { var n = r.Name ?? ""; if (n.StartsWith("R")) { n = n.Substring(1); } if (int.TryParse(n, out var v)) { i = Math.Max(i, v); } } var test = _data.Add <SampleTestResult>(r => { r.Name = string.Format("R{0}", i + 1); r.SampleTest = Model; r.UserId = Model.UserId; }); if (test != null) { Results.List.UpdateAsync(); } }
private Transaction ParseOKQ8Row(string row, IDataService eventDataService, IEnumerable <Event> events) { // Example: 160104 ICA SUPERMARKET MORON, SKELLEFTEA 285,56 var firstSpaceIndex = 6; var lastSpaceIndex = row.LastIndexOf(' '); var eventText = row.Substring(firstSpaceIndex + 1, lastSpaceIndex - firstSpaceIndex - 1); var evnt = events.FirstOrDefault(e => e.Text == eventText); var eventId = 0; if (evnt == null) { eventId = eventDataService.Add(new Event() { Text = eventText }); } else { eventId = evnt.Id; } return(new Transaction() { Date = DateTime.ParseExact("20" + row.Substring(0, firstSpaceIndex), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None), EventId = eventId, Amount = double.Parse(row.Substring(lastSpaceIndex + 1, row.Length - lastSpaceIndex - 1)) }); }
public async Task <IActionResult> Create(HamperCreateViewModel vm, IFormFile file) { if (ModelState.IsValid) { var user = await _UserManager.FindByNameAsync(User.Identity.Name); Hamper h = new Hamper { Active = true, CategoryId = vm.CategoryId, HamperDescription = vm.HamperDescription, HamperName = vm.HamperName, HamperPrice = vm.HamperPrice, }; if (file != null) { var uploadPath = Path.Combine(environment.WebRootPath, "uploads/hampers/"); string extension = Path.GetExtension(file.FileName); string fileName = StringFormatHelper.ToTitleCase(h.HamperName) + "-1" + extension; using (var fileStream = new FileStream(Path.Combine(uploadPath, fileName), FileMode.Create)) { await file.CopyToAsync(fileStream); } h.Picture = fileName; } _hamperManager.Add(h); return(RedirectToAction("Index")); } IEnumerable <Category> categories = _categoryManager.GetAll(); vm.Categories = categories; return(View(vm)); }
public IActionResult Create(CategoryCreateViewModel vm) { if (ModelState.IsValid) { // check if name already exists Category existingCategory = _categoryDataService.GetSingle(c => c.Name == vm.Name); if (existingCategory == null) { // map Category category = new Category { Name = vm.Name, Details = vm.Details }; // call service _categoryDataService.Add(category); // Go to home/index return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "This name already exists"); } return(View(vm)); }
public IActionResult Create(CarCreationViewModel data) { if (m_userData.Get(m_userManager.GetUserId(User)).Type != UserType.Manager) { return(Content("Oops! Nothing to see here.")); } if (!ModelState.IsValid) { return(View(data)); } ValidateCarData(data, ModelState); if (!ModelState.IsValid) { return(View(data)); } Car created = new Car { Brand = data.Brand, Gearbox = data.Gearbox, LicensePlate = data.LicensePlate, ManufactureDate = data.ManufactureDate, Mileage = data.Mileage, Model = data.Model }; m_carData.Add(created); m_documentData.UpdateCarsDocuments(created, data.Documents); m_mileagePointData.UpdateCarsMileagePoints(created, data.MileagePoints. Select(p => p as MileagePointBase).ToList()); m_carData.SaveChanges(); m_carData.UpdateState(created.Id); m_carData.SaveChanges(); return(RedirectToAction("ViewCarList")); }
public async Task <IHttpActionResult> Post([FromBody] SellOfferDto dto) { if (ModelState.IsValid == false) { return(BadRequest("Invalid data")); } if (dto.SellerId != (Thread.CurrentPrincipal as UserPrincipal).Id) { return(Unauthorized()); } var offer = _sellAssembler.DtoToEntity(dto); var result = await _service.Add(offer); if (result == ErrorValue.ServerError) { return(BadRequest("Transaction error")); } else if (result == ErrorValue.AmountGreaterThanStock) { return(BadRequest("Amount greater than stock")); } dto = _sellAssembler.EntityToDto(offer); return(Ok(dto)); }
/// <summary> /// Method responsible for loading objects from the JSON file. /// </summary> public void LoadObjects() { using (StreamReader readJson = new StreamReader(FILEPATH)) { //reads the json file string jsonInfo = readJson.ReadToEnd(); //parsing the json file to a json Array var jsonObject = JArray.Parse(jsonInfo); //parsing JSON objects to C# classes foreach (var jsonMovie in jsonObject) { dataService.Add(new DetailedMovie() { Title = jsonMovie.Value <string>("Title"), Genre = jsonMovie.Value <string>("Genre").Split(','), Description = jsonMovie.Value <string>("Description"), Director = jsonMovie.Value <string>("Director"), Actors = jsonMovie.Value <string>("Actors").Split(','), Year = jsonMovie.Value <int>("Year") }); } //removing empty spaces from JSON file's object properties. //RemoveEmptySpaces(dataService.InitialMovieList); //initializing in-memory collection responsible for data manipulation during application execution this.dataService.ResetData(); } }
public IActionResult Index() { _data.Add(new Entity.Data() { Id = ObjectId.GenerateNewId().ToString(), Name = "sd" }); return(Ok()); }
public static int Add <T>(this IDataService service, Action <IFieldSetter <T> > setter) where T : ITable { var fieldSetter = new TableFieldSetter <T>(Access.Add); setter(fieldSetter); return(service.Add(typeof(T).Name, fieldSetter.XmlStruct)); }
public void AddItem(string item) { dataService.Add(new TodoItem { Text = item, Completed = false }); RaisePropertyChanged(() => Items); }
public IActionResult ClassCreation(ClassCreationViewModel model, string submit) { var userType = m_userData.Get(m_userManager.GetUserId(User)).Type; if (userType != UserType.Instructor || userType != UserType.Manager) { return(NotFound()); } if (submit == "Generate") { return(RedirectToAction("ScheduleClassList", "Schedule")); } if (ModelState.IsValid) { if (model.ClassType == ClassType.TheoryClasses) { if (model.NumberOfSeats == null || model.Weeks == null) { ModelState.AddModelError("", "Number of Seats and weaks to Repeat are" + " required fields for theory classes"); return(View(model)); } m_theoryClassesData.Add(new TheoryClasses { IsMain = true, Date = model.Date, StartTime = model.StartTime, EndTime = model.EndTime, Type = model.ClassType, State = ClassState.New, Seats = (int)model.NumberOfSeats, Weeks = (int)model.Weeks, Instructor = m_instructorData.Get(m_userManager.GetUserId(User)) }); } else { m_classData.Add(new Class { Date = model.Date, StartTime = model.StartTime, EndTime = model.EndTime, Type = model.ClassType, State = ClassState.New, Instructor = m_instructorData.Get(m_userManager.GetUserId(User)) }); } m_classData.SaveChanges(); return(RedirectToAction("ScheduleClassList", "Schedule")); } return(View(model)); }
public virtual T Add(T item) { var entity = item.MapToEntity(); var newCategoryEntity = _dataService.Add(entity); item.MapFromEntity(newCategoryEntity); return(item); }
public async Task <IActionResult> Create( string category, string collection, string key, [FromBody] MetadataModelContract model) { await _service.Add(category, collection, key, model.Data, model.Keywords); return(Created(Request.GetRelativeUrl($"api/v2/{category}/{collection}/{key}"), model)); }
public IActionResult Post([FromBody] Car car) { if (car == null) { return(BadRequest("Null value")); } _carService.Add(car); return(CreatedAtRoute("Get", new { Id = car.CarId }, car)); }
public async Task <IActionResult> Add(ContactForAddDto contactForAddDto) { Contact contact = _mapper.Map <Contact>(contactForAddDto); var contactData = await _contactService.Add(contact); var contactView = _mapper.Map <ContactForViewDto>(contactData); return(Ok(contactView)); }
/// <summary> /// add a new widget /// </summary> /// <param name="widget">widget</param> public void Add(Widget widget) { try { _dataService.Add(widget); } catch (Exception) { throw; } }
public async Task <bool> Handle(CustomerAddCommand command, CancellationToken cancellationToken) { _logger.LogInformation($"Handle({nameof(CustomerAddCommandHandler)}) -> {command}"); var customer = Customer.CreateNew(command.Id, command.FirstName, command.LastName, command.CustomerFrom); var result = _dataService.Add(customer); await _mediator.Publish(Apply(command)); return(result); }
/// <summary> /// Adds a new pokemon /// </summary> public void Add(Player player) { try { _dataService.Add(player); } catch (Exception e) { string message = e.Message; throw; } }
/// <summary> /// add a new widget /// </summary> /// <param name="widget">widget</param> public void Add(Episode episode) { try { _dataService.Add(episode); } catch (Exception e) { string message = e.Message; throw; } }
/// <summary> /// add a new stand /// </summary> /// <returns> </returns> public void Add(Stands stand) { try { _dataService.Add(stand); } catch (Exception e) { string message = e.Message; throw; } }
private void Add() { _dataService.Add(Document, Unites, (result, error) => { if (error != null) { MessageBox.Show(error.Message); return; } SelectedLigne = Document.Lignes.Last(); Messenger.Default.Send("ScrollBottom", "DoFocus"); }); }
public IActionResult Post([FromBody] User user) { if (user == null) { return(BadRequest("User is null.")); } _dataService.Add(user); return(CreatedAtRoute( "Get", new { Id = user.UserId }, user)); }
public IActionResult Post([FromBody] TodoList todoList) { if (todoList == null) { return(BadRequest("Todo List is null.")); } _dataService.Add(todoList); return(CreatedAtRoute( "Get", new { Id = todoList.TodoListId }, todoList)); }
public async Task <bool> Handle(AccountAddCommand command, CancellationToken cancellationToken) { _logger.LogInformation($"Handle({nameof(AccountAddCommandHandler)}) -> {command}"); var account = new Account(command.Id, command.Entity, command.Office, command.Control, command.Number); var result = _dataService.Add(account); await _mediator.Publish(Apply(command)); return(result); }
/// <summary> /// add a new widget /// </summary> /// <param name="widget">widget</param> public void Add(Widget widget) { try { _dataService.Add(widget); } catch (Exception e) { string message = e.Message; throw; } }