//[ValidateAntiForgeryToken] public async Task <JsonResult> CreateMainCourse([FromBody] MainCourseInfo mainCourseInfo) { string emailAddress = HttpContext.User.Identity.Name; var restaurant = await _context.Restaurant .Where(rest => rest.EmailAddress.Equals(emailAddress)) .FirstOrDefaultAsync(); if (checkMainCourseNameInSameRestaurant(mainCourseInfo.Name, restaurant.Id)) { HttpContext.Response.StatusCode = 400; return(new JsonResult("MainCourse " + mainCourseInfo.Name + " already exists in restaurant")); } MainCourse newMainCourse = new MainCourse { Name = mainCourseInfo.Name, Description = mainCourseInfo.Description, Price = mainCourseInfo.Price, HouseSpecial = mainCourseInfo.HouseSpecial }; if (ModelState.IsValid) { newMainCourse.RestaurantId = restaurant.Id; _context.Add(newMainCourse); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index), new { id = id }); } HttpContext.Response.StatusCode = 200; return(new JsonResult("MainCourse successfully created")); }
public async Task <T> Create(T entity) { var result = await postgreSqlContext.Set <T>() .AddAsync(entity); await postgreSqlContext.SaveChangesAsync(); return(result.Entity); }
public async Task <JsonResult> Create([FromBody] Restaurant restaurant) { if (ModelState.IsValid) { _context.Add(restaurant); await _context.SaveChangesAsync(); } //return View(restaurant); HttpContext.Response.StatusCode = 201; return(new JsonResult("Restaurant successfully created")); }
protected async Task <T> CreateModelAsync(T model) { await Context.AddAsync(model); var result = await Context.SaveChangesAsync(); if (result == 0) { throw new Exception("Db error. Not Create any model"); } return(model); }
private async Task PostgreSql(int count) { var maskCount = count.ToString("n"); var countTipoPedidos = await _postgreSqlContext.TipoPedidos.CountAsync(); await SendAsync($"<b>PostgreSql - {maskCount}</b>"); await SendAsync($"TipoPedido: {countTipoPedidos}"); var tipoPedidos = new List <Models.PostgreSql.TipoPedido>(); for (int i = 0; i < count; i++) { tipoPedidos.Add(CreatePostgreSql(i)); } await SendAsync($"{maskCount} tipos de pedidos criados"); await _postgreSqlContext.TipoPedidos.AddRangeAsync(tipoPedidos); await SendAsync($"{maskCount} tipos de pedido adicionado ao context"); await _postgreSqlContext.SaveChangesAsync(); await SendAsync($"{maskCount} tipos de pedido persistido no banco de dados"); tipoPedidos.Clear(); await SendAsync($"Limpando memória"); tipoPedidos = await _postgreSqlContext.TipoPedidos.ToListAsync(); await SendAsync($"{tipoPedidos.Count} carregados"); foreach (var tipoPedido in tipoPedidos) { tipoPedido.Update(); tipoPedido.UpdatePoc(nome: "Updated " + tipoPedido.Nome, grupo: tipoPedido.Grupo == Models.PostgreSql.TipoPedido.EGrupo.RevendaCD ? Models.PostgreSql.TipoPedido.EGrupo.NaoRevendaCD : Models.PostgreSql.TipoPedido.EGrupo.NaoRevendaEDL); } await SendAsync($"{maskCount} tipos de pedidos atualizados na memória"); await _postgreSqlContext.SaveChangesAsync(); await SendAsync($"{maskCount} tipos de pedido atualizados no banco de dados"); _postgreSqlContext.TipoPedidos.RemoveRange(tipoPedidos); await SendAsync($"{maskCount} tipos de pedido removidos"); await _postgreSqlContext.SaveChangesAsync(); await SendAsync($"{maskCount} tipos de pedido removido banco de dados"); }
public async Task <ActionResult <TodoDto> > EditTodo([FromRoute] int id, [FromBody] TodoDto todoDto) { var CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); var CurrentUser = await _userManager.Users .Include(u => u.Todos) .SingleAsync(u => u.Id == CurrentUserId); if (id != todoDto.Id) { return(BadRequest()); } Todo todo = CurrentUser.Todos.Single(t => t.Id == id); if (todo == null) { return(NotFound());; } todo.TodoNote = todoDto.TodoNote; _context.Entry(todo).State = EntityState.Modified; await _context.SaveChangesAsync(); return(Ok(_mapper.Map <TodoDto>(todo))); }
//[ValidateAntiForgeryToken] public async Task <JsonResult> Create([FromBody] TableInfo tableInfo) { string emailAddress = HttpContext.User.Identity.Name; var restaurant = await _context.Restaurant .Where(rest => rest.EmailAddress.Equals(emailAddress)) .FirstOrDefaultAsync(); Table newTable = new Table(); long NbrOfRestaurantTables = _context.Table .Where(t => t.RestaurantId == restaurant.Id).Count(); // set RestName with restaurant name and number of tables in it +1 int number = (int)NbrOfRestaurantTables + 1; string restName = restaurant.Name + " " + number.ToString(); if (tableInfo.Description == null) { HttpContext.Response.StatusCode = 400; return(new JsonResult("Table description must be given")); } newTable.Description = tableInfo.Description; newTable.RestName_Number = restName; newTable.NumberOfSeats = tableInfo.NumberOfSeats; if (ModelState.IsValid) { newTable.RestaurantId = restaurant.Id; _context.Add(newTable); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(AllTables), new { id = id }); } HttpContext.Response.StatusCode = 200; return(new JsonResult("Table successfully created")); }
//[ValidateAntiForgeryToken] public async Task <JsonResult> CreateDrink([FromBody] DrinkInfo drinkInfo) { string emailAddress = HttpContext.User.Identity.Name; var restaurant = await _context.Restaurant .Where(rest => rest.EmailAddress.Equals(emailAddress)) .FirstOrDefaultAsync(); if (checkDrinkNameInSameRestaurant(drinkInfo.Name, restaurant.Id)) { HttpContext.Response.StatusCode = 400; return(new JsonResult("Drink " + drinkInfo.Name + " already exists in restaurant")); } Drink newDrink = new Drink { Name = drinkInfo.Name, Description = drinkInfo.Description, Price = drinkInfo.Price, HouseSpecial = drinkInfo.HouseSpecial, AgeRestricted = drinkInfo.AgeRestricted }; if (ModelState.IsValid) { newDrink.RestaurantId = restaurant.Id; _context.Add(newDrink); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index), new { id = id }); } HttpContext.Response.StatusCode = 200; return(new JsonResult("Drink successfully created")); }
//[ValidateAntiForgeryToken] public async Task <JsonResult> CreateSalad([FromBody] SaladInfo saladInfo) { string emailAddress = HttpContext.User.Identity.Name; var restaurant = await _context.Restaurant .Where(rest => rest.EmailAddress.Equals(emailAddress)) .FirstOrDefaultAsync(); if (checkSaladNameInSameRestaurant(saladInfo.Name, restaurant.Id)) { HttpContext.Response.StatusCode = 400; return(new JsonResult("Salad " + saladInfo.Name + " already exists in restaurant")); } Salad newSalad = new Salad { Name = saladInfo.Name, Description = saladInfo.Description, Price = saladInfo.Price, HouseSpecial = saladInfo.HouseSpecial, Topping = saladInfo.Topping }; if (ModelState.IsValid) { newSalad.RestaurantId = restaurant.Id; _context.Add(newSalad); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index), new { id = id }); } HttpContext.Response.StatusCode = 200; return(new JsonResult("Salad successfully created")); }
private async Task ProcessAllWaitingWebsites() { var allTasks = new List <Task>(); var websites = _waitingWebsites.ToList(); foreach (var waitingWebsite in websites) { _emptyRunsCounter = 0; await SemaphoreDownload.WaitAsync(); waitingWebsite.Crawled = true; waitingWebsite.CrawledTimestamp = DateTime.Now; await _context.SaveChangesAsync(); allTasks.Add( Task.Run(async() => { try { _logger.LogInformation($"Processing webpage: {waitingWebsite.Url}"); _downloadStrategy.Download(waitingWebsite); await _entityManager.Persist(waitingWebsite); await _entityManager.Flush(); } catch (Exception e) { _logger.LogError(e.Message); } finally { SemaphoreDownload.Release(); } }) ); } try { await Task.WhenAll(allTasks.ToArray()); } catch (Exception e) { _logger.LogError(e.Message); } }
public async Task CreateAuthorAsync(Author author) { await context.Authors.AddAsync(author); await context.SaveChangesAsync(); }
public async Task CreateAsync(Book book) { await context.Books.AddAsync(book); await context.SaveChangesAsync(); }
public async Task <IActionResult> Create(long id, [FromForm] ReservationPeriod reservationPeriod) { // provjeri je li datum u prošlosti CultureInfo us = new CultureInfo("en-US"); string format = "yyyy-MM-dd"; DateTime dt1 = DateTime.ParseExact(reservationPeriod.Date, format, us); if (dt1 < DateTime.Now) { //date is in the past, return bad date request return(RedirectToAction(nameof(DateInPastRequest), new { id = id, date = reservationPeriod.Date })); } string pom; pom = reservationPeriod.Date; int year = int.Parse(pom.Substring(0, 4)); int month = int.Parse(pom.Substring(5, 2)); int day = int.Parse(pom.Substring(8, 2)); string str_day = day.ToString("D2"); string str_month = month.ToString("D2"); string str_year = year.ToString("D4"); // formatiraj datum dd/MM/yyyy reservationPeriod.Date = str_day + "/" + str_month + "/" + str_year; // provjeri je li start time veci od end time-a pom = reservationPeriod.StartTime.ToString("HH:mm"); int NewPeriodMinuteStart = int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); pom = reservationPeriod.EndTime.ToString("HH:mm"); int NewPeriodMinuteEnd = int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); string description = reservationPeriod.TableDescription; if (NewPeriodMinuteStart > NewPeriodMinuteEnd) { // odi na bad time request view i posalji potrebne parametre return(RedirectToAction(nameof(InvalidStartEndTimeRequest), new { id = id, startTime = reservationPeriod.StartTime, endTime = reservationPeriod.EndTime })); } // zahtjev ispravan, provjeri postoji li u bazi rezervacija za taj datum i vrijeme int counter = 0; var restaurant = await _context.Restaurant .FirstOrDefaultAsync(m => m.Id == id); List <Table> tables = _context.Table .Where(t => t.RestaurantId == id) .Where(t => t.Description.Equals(description)) .ToList(); int[] reservedTables = new int[tables.Count]; List <ReservationPeriod> reservationPeriods = _context.ReservationPeriod .Where(rp => rp.RestaurantId == id) .Where(rp => rp.TableDescription.Equals(reservationPeriod.TableDescription)) .Where(rp => rp.Date.Equals(reservationPeriod.Date)) .ToList(); foreach (ReservationPeriod period in reservationPeriods) { string reservationPeriodDate = reservationPeriod.Date; // get database reservation Period info string dbReservatinPeriodDate = period.Date; int dbYear = int.Parse(dbReservatinPeriodDate.Substring(6, 4)); int dbMonth = int.Parse(dbReservatinPeriodDate.Substring(3, 2)); int dbDay = int.Parse(dbReservatinPeriodDate.Substring(0, 2)); int rpYear = int.Parse(reservationPeriodDate.Substring(6, 4)); int rpMonth = int.Parse(reservationPeriodDate.Substring(3, 2)); int rpDay = int.Parse(reservationPeriodDate.Substring(0, 2)); bool sameDay = (dbYear == rpYear && dbMonth == rpMonth && dbDay == rpDay); //if (NewPeriodMinuteStart >= NewPeriodMinuteEnd) break; // datum su jednaki, usporedi vremena if (sameDay) { pom = period.StartTime.ToString("HH:mm"); int DbPeriodMinuteStart = int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); pom = period.EndTime.ToString("HH:mm"); int DbPeriodMinuteEnd = int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); if ((NewPeriodMinuteStart >= DbPeriodMinuteStart && NewPeriodMinuteStart <= DbPeriodMinuteEnd) || (NewPeriodMinuteEnd >= DbPeriodMinuteStart && NewPeriodMinuteEnd <= DbPeriodMinuteEnd) || (NewPeriodMinuteStart <= DbPeriodMinuteStart && NewPeriodMinuteEnd >= DbPeriodMinuteEnd) || (NewPeriodMinuteStart >= DbPeriodMinuteStart && NewPeriodMinuteEnd <= DbPeriodMinuteEnd)) { // preklapa se sa postojecim terminom reservedTables[counter++] = (int)period.TableId; continue; } else { // termin se ne preklapa za novu rezervaciju continue; } } // rezervacija u bazi nije na taj datum, nastavi } if (counter >= tables.Count) { // odi na bad request view i posalji potrebne paramtre return(RedirectToAction(nameof(BadTimeRequest), new { id = id, date = reservationPeriod.Date, startTime = reservationPeriod.StartTime, endTime = reservationPeriod.EndTime })); } foreach (Table table in tables) { if (reservedTables.Contains((int)table.Id)) { continue; } // found table that is free, reserve it reservationPeriod.TableId = table.Id; break; } /* * List<Table> tables = _context.Table * .Where(t => t.RestaurantId == id) * .Where(t => t.Description.Equals(description)) * .ToList(); * * List<long> tableIds = tables.Select(t => t.Id).ToList(); * * List<long> reservationPeriodTablesIds = _context.ReservationPeriod * .Where(rp => rp.RestaurantId == id) * .Where(rp => rp.TableDescription.Equals(reservationPeriod.TableDescription)) * .Select(rp => rp.TableId) * .Distinct() * .ToList();*/ /* // TODO : implement reservation logic * bool found = false; * foreach (var table in tables) { * if (reservationPeriodTablesIds.Contains(table.Id)) * { * // vec postoji rezervacija za stol sa id-om table.Id, provjeri jel se moze napraviti nova rez. * List<ReservationPeriod> reservationPeriods = _context.ReservationPeriod * .Where(rp => rp.RestaurantId == id) * .Where(rp => rp.TableId == table.Id) * .ToList(); * * foreach (ReservationPeriod period in reservationPeriods) * { * * string reservationPeriodDate = reservationPeriod.Date; * // get database reservation Period info * string dbReservatinPeriodDate = period.Date; * int dbYear = int.Parse(dbReservatinPeriodDate.Substring(6, 4)); * int dbMonth = int.Parse(dbReservatinPeriodDate.Substring(3, 2)); * int dbDay = int.Parse(dbReservatinPeriodDate.Substring(0, 2)); * * int rpYear = int.Parse(reservationPeriodDate.Substring(6, 4)); * int rpMonth = int.Parse(reservationPeriodDate.Substring(3, 2)); * int rpDay = int.Parse(reservationPeriodDate.Substring(0, 2)); * * bool sameDay = (dbYear == rpYear && dbMonth == rpMonth && dbDay == rpDay); * //if (NewPeriodMinuteStart >= NewPeriodMinuteEnd) break; * * // datum su jednaki, usporedi vremena * if (sameDay) * { * pom = period.StartTime.ToString("HH:mm"); * int DbPeriodMinuteStart= int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); * pom = period.EndTime.ToString("HH:mm"); * int DbPeriodMinuteEnd= int.Parse(pom.Substring(0, 2)) * 60 + int.Parse(pom.Substring(3, 2)); * * if ((NewPeriodMinuteStart >= DbPeriodMinuteStart && NewPeriodMinuteStart <= DbPeriodMinuteEnd) || * (NewPeriodMinuteEnd >= DbPeriodMinuteStart && NewPeriodMinuteEnd <= DbPeriodMinuteEnd) || * (NewPeriodMinuteStart <= DbPeriodMinuteStart && NewPeriodMinuteEnd >= DbPeriodMinuteEnd) || * (NewPeriodMinuteStart >= DbPeriodMinuteStart && NewPeriodMinuteEnd <= DbPeriodMinuteEnd)) * { * // preklapa se sa postojecim terminom * continue; * } else * { * // termin je slobodan za stol * found = true; * reservationPeriod.TableId = table.Id; * break; * } * } * * // rezervacija u bazi nije na taj datum, nastavi * * * } * // ako si rezervirao termin , izadi * if (found == true) * { * break; * } * } else * { * // uopce ne postoji rezervation period za ovaj stol, odmah rezerviraj stol * * pom = reservationPeriod.Date; * * int yearToSave = int.Parse(reservationPeriod.Date.Substring(6, 4)); * int monthToSave = int.Parse(reservationPeriod.Date.Substring(3, 2)); * int dayToSave = int.Parse(reservationPeriod.Date.Substring(0, 2)); * * string str_dayToSave = day.ToString("D2"); * string str_monthToSave = month.ToString("D2"); * string str_yearToSave = year.ToString("D4"); * * // formatiraj datum dd/MM/yyyy * * reservationPeriod.Date = str_day + "/" + str_month + "/" + str_year; * * reservationPeriod.TableId = table.Id; * found = true; * break; * } * }*/ reservationPeriod.RestaurantId = id; if (ModelState.IsValid) { _context.Add(reservationPeriod); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index), new { id = id })); } return(View(reservationPeriod)); }
public async Task <int> SaveChangesAsync() { return(await _context.SaveChangesAsync()); }