public async Task <IActionResult> PostValue([FromBody] Value value) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _dbContext.Values.Add(value); try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateException) { if (ValueExists(value.Id)) { return(new StatusCodeResult(StatusCodes.Status409Conflict)); } else { throw; } } return(CreatedAtAction("GetValue", new { id = value.Id }, value)); }
public async Task <IActionResult> Create([Bind("Id,Student,Curriculum,Date")] Sheet sheet) { if (ModelState.IsValid) { _context.Add(sheet); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["Curriculum"] = new SelectList( from cur in _context.Curriculum select new { cur.Id, Name = $"{cur.SpecialtyNavigation.Name}, {cur.SubjectNavigation.Name}, Course: {cur.Course}, Semester: {cur.Semester}" }, "Id", "Name", sheet.Curriculum); ViewData["Student"] = new SelectList(from student in _context.Student select new { student.Id, Name = $"{student.PersonNavigation.Surname} {student.PersonNavigation.Name} {student.PersonNavigation.Middlename}" }, "Id", "Name", sheet.Student); return(View(sheet)); }
public async Task <IActionResult> Register([ModelBinder(BinderType = typeof(PersonModelBinder))] Person person) { if (ModelState.IsValid) { Person user = await _context.Person.FirstOrDefaultAsync(u => u.Email == person.Email); if (user == null) { Role userRole = await _context.Role.FirstOrDefaultAsync(r => r.Name == "user"); if (userRole != null) { person.Role = userRole; // для аутентификации нужно добавить роль } _context.Add(person); await _context.SaveChangesAsync(); await Authenticate(person); // аутентификация return(RedirectToAction("Details", new { id = UserId() })); } else { ModelState.AddModelError("", "Некорректные логин и(или) пароль"); } } return(View(person)); }
public async Task <IActionResult> Create([Bind("Id,Name,Surname,Middlename")] Person person) { if (ModelState.IsValid) { _context.Add(person); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(person)); }
public async Task <IActionResult> Create([Bind("Id,Name")] Subject subject) { if (ModelState.IsValid) { _context.Add(subject); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(subject)); }
public async Task <Todo> Create(TodoCreateDto data) { var result = await _dbContext.Todos.AddAsync(new Todo { Name = data.Name, Completed = data.Completed }); await _dbContext.SaveChangesAsync(); return(result.Entity); }
public async Task <IActionResult> Create([Bind("Id,Person,StudentsGroup")] Student student) { if (ModelState.IsValid) { _context.Add(student); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["Person"] = new SelectList(_context.Person, "Id", "Name", student.Person); ViewData["StudentsGroup"] = new SelectList(_context.Studentsgroup, "Id", "Name", student.StudentsGroup); return(View(student)); }
public async Task <IActionResult> Create( [Bind("Id,Name,DateStart,DateFinish,Specialty,Course")] StudentsGroup studentsGroup) { if (ModelState.IsValid) { _context.Add(studentsGroup); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["Specialty"] = new SelectList(_context.Specialty, "Id", "Name", studentsGroup.Specialty); return(View(studentsGroup)); }
public async Task <IActionResult> Create([Bind("Id,Person,Department")] Professor professor) { if (ModelState.IsValid) { _context.Add(professor); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["Department"] = new SelectList(_context.Department, "Id", "Name", professor.Department); ViewData["Person"] = new SelectList(_context.Person, "Id", "Name", professor.Person); return(View(professor)); }
public async Task <IActionResult> Create( [Bind("Id,Subject,Semester,Course,Specialty,HoursAmount,ProfessorId,HasExam")] Curriculum curriculum) { if (ModelState.IsValid) { _context.Add(curriculum); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["ProfessorId"] = new SelectList(_context.Professor, "Id", "Id", curriculum.ProfessorId); ViewData["Specialty"] = new SelectList(_context.Specialty, "Id", "Name", curriculum.Specialty); ViewData["Subject"] = new SelectList(_context.Subject, "Id", "Name", curriculum.Subject); return(View(curriculum)); }
public async Task GetPagedTodos() { var options = new DbContextOptionsBuilder <PostgresContext>() .UseInMemoryDatabase("GetPagedTodos") .Options; // Insert seed data into the database using one instance of the context await using (var context = new PostgresContext(options)) { await context.Todos.AddAsync(new Todo { Id = 1, Name = "Milk" }); await context.Todos.AddAsync(new Todo { Id = 2, Name = "Chocolate" }); await context.Todos.AddAsync(new Todo { Id = 3, Name = "Gym" }); await context.Todos.AddAsync(new Todo { Id = 4, Name = "Pickup" }); await context.SaveChangesAsync(); } // Use a clean instance of the context to run the test await using (var context = new PostgresContext(options)) { var repository = new TodoRepository(context); var todos = await new TodoController().Get(repository, 1, 2) as OkObjectResult; Assert.NotNull(todos); Assert.Equal(2, ((PagedData <Todo>)todos.Value).Value.Count()); } }
public async Task <IActionResult> Post([FromBody] SupplierCreate command) { try { var createTask = await _db.Suppliers.AddAsync(new Supplier() { Title = command.Name, Phone = command.Phone, Email = command.Email, Debt = 0 }); await _db.SaveChangesAsync(); await _postgresContext.Suppliers.AddAsync( new Domain.Entities.Supplies.Supplier(command.Name, command.Phone, command.Email)); await _postgresContext.SaveChangesAsync(); return(Ok(new { Id = createTask.Entity.Id, Name = createTask.Entity.Title })); } catch (Exception e) { return(BadRequest(e.Message)); } }
public async Task GetOneTodo() { var options = new DbContextOptionsBuilder <PostgresContext>() .UseInMemoryDatabase("GetOneTodo") .Options; // Insert seed data into the database using one instance of the context await using (var context = new PostgresContext(options)) { await context.Todos.AddAsync(new Todo { Id = 1, Name = "Milk" }); await context.Todos.AddAsync(new Todo { Id = 2, Name = "Chocolate" }); await context.Todos.AddAsync(new Todo { Id = 3, Name = "Gym" }); await context.SaveChangesAsync(); } // Use a clean instance of the context to run the test await using (var context = new PostgresContext(options)) { var repository = new TodoRepository(context); var todo = await new TodoController().GetFromId(repository, 2) as OkObjectResult; Assert.NotNull(todo); Assert.Equal("Chocolate", ((Todo)todo.Value).Name); } }
public static async Task <int> Handler(this ShopCreate command, PostgresContext db) { var createTask = await db.Shops.AddAsync(new Shop(command.Title)); await db.SaveChangesAsync(); return(createTask.Entity.Id); }
public async Task <int> Update(T entity) { using (var db = new PostgresContext()) { db.Set <T>(); db.Update(entity); return(await db.SaveChangesAsync()); } }
public static async Task <User> Execute(PostgresContext db, UserCreate command) { var id = Guid.NewGuid(); var userCreate = await db.Users.AddAsync( new User(id, command.Login, command.Password, command.Role)); await db.SaveChangesAsync(); return(userCreate.Entity); }
public async Task <ActionResult <TicketModel> > PostTicketModel([FromBody] TicketModelView ticketModelView) { if (ticketModelView.CountTickets == null || ticketModelView.CountTickets <= 0 || ticketModelView.SessionId == null) { return(StatusCode(400)); } SessionModel session = await _context.Sessions.Include(a => a.Tickets).FirstOrDefaultAsync(a => a.Id.Equals(ticketModelView.SessionId)); if (session == null) { return(StatusCode(400)); } int countNowSeats = 0; foreach (var ticketSeat in session.Tickets) { countNowSeats += ticketSeat.CountTickets; } if (countNowSeats + ticketModelView.CountTickets > session.NumberSeats) { return(StatusCode(406)); } TicketModel ticket = new TicketModel { Id = Guid.NewGuid().ToString(), DateBuy = DateTime.Now, Price = session.PriceTicket * ticketModelView.CountTickets, SessionId = ticketModelView.SessionId, CountTickets = ticketModelView.CountTickets, }; _context.Tickets.Add(ticket); await _context.SaveChangesAsync(); return(Ok(ticket)); }
public async Task <ActionResult <SessionModel> > PutSessionModel(string id, [FromBody] SessionModel sessionModel) { if (id != sessionModel.Id) { return(BadRequest()); } SessionModel oldModel = await _context.Sessions.FirstOrDefaultAsync(a => a.Id.Equals(id)); oldModel.Img = sessionModel.Img; oldModel.PriceTicket = sessionModel.PriceTicket; oldModel.Room = sessionModel.Room; oldModel.NumberSeats = sessionModel.NumberSeats; oldModel.StartFilm = sessionModel.StartFilm; oldModel.NameFilm = sessionModel.NameFilm; _context.Sessions.Update(oldModel); //_context.Entry(sessionModel).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SessionModelExists(id)) { return(NotFound()); } else { throw; } } return(sessionModel); }
public async Task <IActionResult> SaveClick([FromForm] string idPage) { LikeVkModel model = new LikeVkModel { Id = Guid.NewGuid().ToString(), IdPage = idPage, DateTime = DateTime.Now }; await _context.LikeVkModels.AddAsync(model); try { await _context.SaveChangesAsync(); return(StatusCode(200)); }catch (Exception e) { return(StatusCode(500)); } }
public async Task <ActionResult <object> > GeneratePlanner(GeneratePlannerInput reqBody) { string userId = ParseUserId.GetUserId(Request.Headers); /* the client will select a list of mealtypes that they want in their planner */ List <string> mealTypes = reqBody.input.mealTypes.ToList(); List <Recipe> allRecipes = (from recipe in _context.Recipes where recipe.Owner == userId where mealTypes.Contains(recipe.MealType) select recipe).ToList(); // this will shuffle the recipes List <Recipe> shuffledRecipes = allRecipes.OrderBy(r => Guid.NewGuid()).ToList(); DateTime startDate = DateTime.Parse(reqBody.input._gte); DateTime endDate = DateTime.Parse(reqBody.input._lte).AddDays(-1); /* delete existing planners for the given time because we are over writing it */ _context.RemoveRange( _context.Planners .Where(p => DateTime.Compare(p.Date, startDate) > 0) .Where(p => DateTime.Compare(p.Date, endDate) < 0) ); List <Planner> newPlanners = BuildPlannerForTheWeek( mealTypes, shuffledRecipes, userId, startDate ); await _context.Planners.AddRangeAsync(newPlanners); await _context.SaveChangesAsync(); var returningIds = newPlanners.Select(p => new { id = p.RecipeId }).ToList(); return(Ok(returningIds)); }
public async Task <ActionResult <object> > ScrapeRecipe(ScraperInput scraperInput) { string url = scraperInput.input.url; try { Recipe recipe = await Scraper.RunScraper(url); string userId = ParseUserId.GetUserId(Request.Headers); recipe.Owner = userId; // insert ot db _context.Recipes.Add(recipe); await _context.SaveChangesAsync(); return(Ok(new { id = recipe.Id })); } catch (System.OperationCanceledException e) { return(BadRequest(e.Message)); } }
public async Task <object> PostRecipe(InsertRecipeInput recipeInputRaw) { var userId = ParseUserId.GetUserId(Request.Headers); var recipeInput = recipeInputRaw.input; // parse the ingredient text and map it List <RecipeIngredient> recipeIngredients = new(); if (recipeInput.ingredients is not null) { recipeIngredients = (await Task.WhenAll(recipeInput.ingredients .Select(Parser.RunParser))) .ToList(); } // map everything to their proper location for db write Recipe recipe = new() { Directions = recipeInput.directions, Owner = userId, Img = recipeInput.img, TotalTime = recipeInput.total_time, Yields = recipeInput.yields, Cuisine = recipeInput.cuisine, MealType = recipeInput.meal_type, Title = recipeInput.title, RecipeIngredients = recipeIngredients }; _context.Recipes.Add(recipe); await _context.SaveChangesAsync(); return(new { id = recipe.Id }); } }
public async Task <ActionResult <object> > PostRecipeIngredient(OverWriteIngredientsInput reqBody) { string recipe_id = reqBody.input.recipe_id; ICollection <string> ingredientsStrings = reqBody.input.ingredientsStrings; // ensure recipe exists if (!RecipeExists(recipe_id)) { return(NotFound()); } if (ingredientsStrings.Count == 0) { return(Ok(Array.Empty <object>())); } // delete everything related to recipe id _context.RecipeIngredients.RemoveRange(_context.RecipeIngredients .Where(ingredient => ingredient.RecipeId.ToString() == recipe_id)); // parse the new ingredients ICollection <RecipeIngredient> recipeIngredients = (await Task.WhenAll(ingredientsStrings. Select(Parser.RunParser))).ToList(); // insert in foreach (var ingredient in recipeIngredients) { ingredient.RecipeId = new Guid(recipe_id); } _context.RecipeIngredients.AddRange(recipeIngredients); await _context.SaveChangesAsync(); // return all ids var response = recipeIngredients .Select(ing => new { id = ing.Id }) .ToList(); return(Ok(response)); }
public async Task DeleteTodo() { var options = new DbContextOptionsBuilder <PostgresContext>() .UseInMemoryDatabase("DeleteTodo") .Options; // Insert seed data into the database using one instance of the context await using (var context = new PostgresContext(options)) { await context.Todos.AddAsync(new Todo { Id = 1, Name = "Milk" }); await context.SaveChangesAsync(); } // Use a clean instance of the context to run the test await using (var context = new PostgresContext(options)) { var repository = new TodoRepository(context); _ = await new TodoController().Delete(repository, 1) as OkObjectResult; var todos = await context.Todos.FindAsync(1); Assert.Null(todos); } }
public void AddCounterAsync(List <Counter> counters) { _postgresContext.Counters.AddRange(counters); _postgresContext.SaveChangesAsync(); }