Esempio n. 1
0
        public async void Test_Repository_DeleteAsync(BookingModel booking)
        {
            await _connection.OpenAsync();

            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    await ctx.Bookings.AddAsync(booking);

                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new Repository <BookingModel>(ctx);

                    await bookings.DeleteAsync(1);

                    await ctx.SaveChangesAsync();

                    Assert.Empty(await ctx.Bookings.ToListAsync());
                }
            }
            finally
            {
                _connection.Close();
            }
        }
        public async Task <ActionResult <int> > Update([FromRoute] int id, [FromBody] CreateTagRequest request)
        {
            Tag oldTag = _context.Tags.FirstOrDefault(x => x.Id == id);

            if (oldTag == null)
            {
                return(NotFound());
            }

            var newTag = new Tag()
            {
                Name = request.Name,
            };
            List <CategoryTag> categoryTags = new List <CategoryTag>();

            foreach (var item in request.CategoryNames)
            {
                var categoryTag = new CategoryTag();
                categoryTag.TagId      = newTag.Id;
                categoryTag.CategoryId = _context.Categories.FirstOrDefault(category => category.Name == item).Id;
                categoryTags.Add(categoryTag);
            }
            newTag.CategoryTags = categoryTags;
            var oldData = _context.CategoryTags.Where(temp => temp.TagId == oldTag.Id);

            foreach (var item in oldData)
            {
                _context.CategoryTags.Remove(item);
            }
            oldTag.Name         = newTag.Name;
            oldTag.CategoryTags = newTag.CategoryTags;
            await _context.SaveChangesAsync();

            return(Ok(oldTag));
        }
        public async Task <IActionResult> DeleteAll([FromRoute] int id)
        {//удаление книги из БД возможно только администратором
            try
            {
                if (!ModelState.IsValid)
                {
                    Log.WriteSuccess(" PersonalController.Delete", "Валидация внутри контроллера неудачна.");
                    return(BadRequest(ModelState));
                }
                Order item = _context.Order.Find(id);
                IEnumerable <BookOrder> lines = _context.BookOrder.Where(l => l.IdOrder == id);
                if (item == null)
                {
                    Log.WriteSuccess(" PersonalController.Delete", "Order не найден.");
                    return(RedirectToAction("Basket", new { item, a = "Заказ не найден!" }));
                }
                foreach (BookOrder i in lines)
                {
                    _context.BookOrder.Remove(i);
                }
                item.Amount   = 0;
                item.SumOrder = 0;
                _context.Order.Update(item);
                await _context.SaveChangesAsync();

                OrderView j = await GetCurrentOrder();

                return(RedirectToAction("Basket", new { j }));
            } catch (Exception ex)
            {
                Log.Write(ex);
                return(RedirectToAction("Basket", new { b = new OrderView(), a = "Ошибка" + ex }));
            }
        }
        public async Task <IActionResult> Create([Bind("Idreserva,Idhotel,Idcliente,Idregime,IdtipoQuarto,CodPagamento,QuantAdultos,QuantCriancas,CheckIn,CheckOut")] Reservas reservas)
        {
            if (ModelState.IsValid)
            {
                _context.Add(reservas);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CodPagamento"] = new SelectList(_context.Pagamento, "CodPagamento", "DataValidadeCartao", reservas.CodPagamento);
            ViewData["Idcliente"]    = new SelectList(_context.Clientes, "Idcliente", "Cc", reservas.Idcliente);
            ViewData["Idhotel"]      = new SelectList(_context.Hoteis, "Idhotel", "CodPostal", reservas.Idhotel);
            ViewData["Idregime"]     = new SelectList(_context.Regimes, "Idregime", "TipoRegime", reservas.Idregime);
            ViewData["IdtipoQuarto"] = new SelectList(_context.TipoQuarto, "IdtipoQuarto", "Descricao", reservas.IdtipoQuarto);
            return(View(reservas));
        }
Esempio n. 5
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            var request = context.Request;

            using (var sr = new StreamReader(request.InputStream))
                using (var dbContext = new BookingContext())
                {
                    var body = JsonConvert.DeserializeObject <Services.Payment.Models.ResponseModel>(await sr.ReadToEndAsync());

                    //
                    var txn = dbContext.Transactions.Include(x => x.Reservation).FirstOrDefault(x => x.RefExternal == body.Data.TransactionId && x.Type == TransactionType.Charge);
                    if (txn != null)
                    {
                        if (Services.Payment.HubtelPaymentService.IsSuccessfulResponse(body.ResponseCode))
                        {
                            txn.Status = TransactionStatus.Successful;
                        }
                        else
                        {
                            txn.Status = TransactionStatus.Failed;
                        }

                        txn.Message       = body.Data.Description;
                        txn.DateCompleted = DateTime.UtcNow;
                        await dbContext.SaveChangesAsync();

                        //  Broadcast notification
                        if (txn.Status == TransactionStatus.Successful)
                        {
                            var notifService = (IPaymentNotification)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IPaymentNotification));
                            await notifService.OnPaymentSuccessul(txn.Reservation, txn);
                        }
                    }
                }
        }
Esempio n. 6
0
        public async Task <IActionResult> add([FromBody] dynamic data)
        {
            try
            {
                dynamic bookingObj = JsonConvert.DeserializeObject(data.ToString());
                //Get User
                string uuid       = bookingObj.userID;
                var    singleUser = from user in context.users
                                    where user.uuid == uuid
                                    select user;

                var userTmp = singleUser.FirstOrDefault();
                if (userTmp == null)
                {
                    throw new Exception("Local User Object not found");
                }

                //Get Location
                int locID          = bookingObj.locationID;
                var singleLocation = from location in context.locations
                                     where location.locationId == locID
                                     select location;
                Location locationTmp = singleLocation.FirstOrDefault();
                if (userTmp == null)
                {
                    throw new Exception("Location Object not found");
                }

                Bookings newBooking = new Bookings
                {
                    createdOn = bookingObj.createdOn,
                    bookedFor = bookingObj.bookedFor,
                    status    = false,
                    user      = userTmp,
                    location  = locationTmp
                };
                context.bookings.Add(newBooking);
                await context.SaveChangesAsync();

                return(NoContent());
            }
            catch (Exception e)
            {
                _logger.LogError("Add Booking error: " + e.Message);
                return(BadRequest());
            }
        }
Esempio n. 7
0
        public async void Test_Repository_Update(BookingModel booking, StayModel stay)
        {
            await _connection.OpenAsync();

            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    await ctx.Bookings.AddAsync(booking);

                    await ctx.Stays.AddAsync(stay);

                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var rentals = new List <RentalModel>();
                    var rental  = new RentalModel {
                        Id = 1
                    };
                    rentals.Add(rental);
                    booking.Rentals = rentals;
                    var bookings = new Repository <BookingModel>(ctx);
                    var expected = await ctx.Bookings.FirstAsync();

                    expected.Status = "updated";
                    bookings.Update(expected);
                    await ctx.SaveChangesAsync();

                    var actual = await ctx.Bookings.FirstAsync();

                    Assert.Equal(expected, actual);
                }


                using (var ctx = new BookingContext(_options))
                {
                    var stays    = new Repository <StayModel>(ctx);
                    var expected = await ctx.Stays.FirstAsync();

                    expected.DateModified = DateTime.Now;
                    stays.Update(expected);
                    await ctx.SaveChangesAsync();

                    var actual = await ctx.Stays.FirstAsync();

                    Assert.Equal(expected, actual);
                }
            }
            finally
            {
                _connection.Close();
            }
        }
        public async Task<IActionResult> Create([Bind("Id,PerformanceId,Name,Email,NumberFullPrice,NumberConcessionPrice,StoreEmail,TotalCost")] Booking booking)
        {
            BookingSystemDTO bookingsystemdto = new BookingSystemDTO();
            myBooking myShows = new myBooking();



            if (ModelState.IsValid)
            {
                _context.Add(booking);
                await _context.SaveChangesAsync();
                return RedirectToAction("Details", new {booking.Id });

            }

           

            return View(booking);
        }
Esempio n. 9
0
        public async Task <IActionResult> Create([FromBody] BookOrderForm item)
        {//создание новой строки заказа
            try
            {
                if (!ModelState.IsValid)
                {
                    Log.WriteSuccess("BookOrderController.Create", "Валидация внутри контроллера неудачна.");
                    return(BadRequest(ModelState));
                }

                IEnumerable <BookOrder> books = _context.BookOrder.Where(a => a.IdBook == item.IdBook);
                foreach (BookOrder book  in books)
                {
                    book.Amount++;
                    _context.BookOrder.Update(book);
                }
                BookOrder bookorder = new BookOrder()
                {
                    IdBook  = item.IdBook,
                    IdOrder = item.IdOrder,
                    Amount  = 1
                };
                if (!books.Any())
                {
                    _context.BookOrder.Add(bookorder);
                }
                Order order = _context.Order.Find(item.IdOrder);
                order.SumOrder += item.Sum;
                order.Amount++;
                _context.Order.Update(order);
                await _context.SaveChangesAsync();

                Log.WriteSuccess("BookOrderController.Create", "Добавлена новая строка заказа.");
                return(CreatedAtAction("GetBookOrder", new { id = bookorder.Id }, bookorder));
                //return View("~/Home/Index");
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                return(BadRequest(ModelState));
            }
        }
Esempio n. 10
0
        public async Task <IActionResult> Create([FromBody] Book item)
        {//создание новой книги возможно только администратором
            try
            {
                if (!ModelState.IsValid)
                {
                    Log.WriteSuccess(" BooksController.Create", "Валидация внутри контроллера неудачна.");
                    return(BadRequest(ModelState));
                }

                _context.Book.Add(item);
                await _context.SaveChangesAsync();

                return(CreatedAtAction("GetBook", new { id = item.Id }, item));
            } catch (Exception ex)
            {
                Log.Write(ex);
                return(BadRequest(ModelState));
            }
        }
        public async Task <ActionResult <SchedulerEvent> > Add([FromBody] SchedulerEvent schedulerEvent)
        {
            if (_context.Categories.Where(s => s.Id == schedulerEvent.CategoryId).FirstOrDefault() == null)
            {
                return(BadRequest("ERROR, category with Id: " + schedulerEvent.CategoryId + " doesn't exist"));
            }

            var newSchedulerEvent = new SchedulerEvent()
            {
                Title      = schedulerEvent.Title,
                Start      = schedulerEvent.Start,
                End        = schedulerEvent.End,
                IsApproved = schedulerEvent.IsApproved,
                CategoryId = schedulerEvent.CategoryId
            };

            _context.SchedulerEvent.Add(newSchedulerEvent);
            await _context.SaveChangesAsync();

            return(Ok(newSchedulerEvent));
        }
        public async Task <IActionResult> Create([Bind("ID,Title,EventColor,IsBookable,MaxOccupancy")] Rooms rooms)
        {
            if (ModelState.IsValid)
            {
                //  List<int> ListRoomID = new List<int>();
                //foreach (var room in _context.Rooms)
                //{
                //    ListRoomID.Add(Convert.ToInt16(room.ID));
                //}
                //  _context.Rooms.ToList().ForEach(r => ListRoomID.Add(Convert.ToInt16(r.ID)));

                //var NewID = _context.Rooms.Select(r => Convert.ToInt16(r.ID.Max())+1).ToString();

                //  rooms.ID = ListRoomID.Max() + 1;

                _context.Add(rooms);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(rooms));
        }
        public async Task <ActionResult <GetAllCategoriesResponse> > Add([FromBody] AddCategoryRequest request)
        {
            var newCategory = new Category()
            {
                Name        = request.Name,
                Description = request.Description,
                Color       = request.Color,
                ParentId    = request.ParentId,
            };

            newCategory.SchedulerEvents = new List <SchedulerEvent>();
            var categoryTags = new List <CategoryTag>();

            if (request.tags != null)
            {
                request.tags.ForEach(tag =>
                {
                    CategoryTag categoryTag = new CategoryTag();
                    categoryTag.CategoryId  = newCategory.Id;
                    categoryTag.TagId       = _context.Tags.First(temp => temp.Name == tag).Id;
                    categoryTags.Add(categoryTag);
                    _context.CategoryTags.Add(categoryTag);
                });
            }
            newCategory.CategoryTags = categoryTags;
            _context.Categories.Add(newCategory);
            await _context.SaveChangesAsync();

            var response = new GetAllCategoriesResponse();

            response.Id              = newCategory.Id;
            response.Name            = newCategory.Name;
            response.ParentId        = request.ParentId;
            response.SchedulerEvents = newCategory.SchedulerEvents.ToList();
            response.Tags            = request.tags;
            response.Color           = newCategory.Color;
            response.Description     = newCategory.Description;
            return(Ok(response));
        }
Esempio n. 14
0
        public async Task <bool> SaveBookingAsync(BookingModel bookingModel)
        {
            var booking = new Booking()
            {
                Date         = bookingModel.Date,
                EndingHour   = bookingModel.EndingHour,
                StartingHour = bookingModel.StartingHour,
            };

            booking.Room = await _context.Rooms.FirstAsync(r => r.Id == bookingModel.RoomId);

            booking.User = await _context.Users.FirstAsync(u => u.Id == bookingModel.UserId);

            var isBookingValid = await _service.IsBookingAvailable(booking);

            if (isBookingValid)
            {
                _context.Bookings.Add(booking);
                await _context.SaveChangesAsync();
            }
            return(isBookingValid);
        }
Esempio n. 15
0
        public async Task <int> SendEmailAsync(int bookingId)
        {
            Logs log = new Logs {
                LogMesssage = "Email delivered using SendGrid",
                Date        = DateTime.Today,
                BookingId   = bookingId
            };
            await db.Logs.AddAsync(log);

            await db.SaveChangesAsync();

            return(log.Id);
        }
        public async Task <IActionResult> Create
            ([Bind("ID,FirstName,LastName,Telephone")] Customer customer)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(customer);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(customer));
        }
Esempio n. 17
0
        public async Task <IActionResult> Create([FromBody] BookGenre item)
        {    //создание новой строки заказа
            try
            {
                if (!ModelState.IsValid)
                {
                    Log.WriteSuccess("BookGenreController.Create", "Валидация внутри контроллера неудачна.");
                    return(BadRequest(ModelState));
                }

                _context.BookGenre.Add(item);
                await _context.SaveChangesAsync();

                Log.WriteSuccess("BookGenreController.Create", "Добавлена новая строка заказа.");
                return(CreatedAtAction("GetBookGenre", new { id = item.Id }, item));
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                return(BadRequest(ModelState));
            }
        }
Esempio n. 18
0
        public async void Test_BookingRepository_Update(BookingModel booking)
        {
            await _connection.OpenAsync();

            var bookingRentals = new List <BookingRentalModel>();

            bookingRentals.Add(new BookingRentalModel {
                RentalId = 1
            });
            bookingRentals.Add(new BookingRentalModel {
                RentalId = 2
            });
            booking.BookingRentals = bookingRentals;
            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    var bookings = new BookingRepository(ctx);
                    await bookings.InsertAsync(booking);

                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new BookingRepository(ctx);
                    bookingRentals.RemoveAt(0);
                    bookingRentals.Add(new BookingRentalModel {
                        RentalId = 3
                    });
                    booking.BookingRentals = bookingRentals;
                    bookings.Update(booking);
                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new BookingRepository(ctx);
                    var actual   = await bookings.SelectAsync(1);

                    Assert.Equal(2, actual.BookingRentals.Count());
                }
            }
            finally
            {
                _connection.Close();
            }
        }
Esempio n. 19
0
        public async void Test_Repository_SelectAsync(BookingModel booking, StayModel stay)
        {
            await _connection.OpenAsync();

            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    await ctx.Bookings.AddAsync(booking);

                    await ctx.Stays.AddAsync(stay);

                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new Repository <BookingModel>(ctx);

                    var actual = await bookings.SelectAsync();

                    Assert.NotEmpty(actual);
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new BookingRepository(ctx);

                    var actual = await bookings.SelectAsync();

                    Assert.NotEmpty(actual);
                }

                using (var ctx = new BookingContext(_options))
                {
                    var stays = new StayRepository(ctx);

                    var actual = await stays.SelectAsync();

                    Assert.NotEmpty(actual);
                }
            }
            finally
            {
                _connection.Close();
            }
        }
        public async Task <IActionResult> PutEvents([FromRoute] int id, [FromBody] Events events)
        {
            //todo add in user check here

            string UserEmail = User.Identity.Name;

            if (!ModelState.IsValid || UserEmail == null || events.Email != UserEmail)
            {
                return(BadRequest(ModelState));
            }

            if (id != events.Id)
            {
                return(BadRequest());
            }

            _context.Entry(events).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                //if (!EventsExists(id))
                //{
                //    return NotFound();
                //}
                //else
                //{
                //    throw;
                //}
            }

            return(NoContent());
        }
Esempio n. 21
0
        private void DeleteOldBookingsFromGoogleCaledar(DateTime startDate)
        {
            var googleCalendarEvents = GetEventRequest(startDate);
            var localEvents          = GetEventsFromLocalBase(startDate).ToList();

            foreach (var localEvent in localEvents)
            {
                if (googleCalendarEvents
                    .Where(x => x.Start.DateTime == localEvent.TimeOfVisit && x.End.DateTime == localEvent.EndTime)
                    .IsNullOrEmpty())
                {
                    db.Bookings.Remove(localEvent);
                    db.SaveChangesAsync();
                }
            }
        }
Esempio n. 22
0
        public async void Test_Repository_GetBookingsAsync_ByDate()
        {
            using var ctx = new BookingContext(options);
            var bookings = new Repository <BookingModel>(ctx);

            ctx.Bookings.Add(
                new BookingModel()
            {
                EntityId  = 0,
                AccountId = 1,
                LodgingId = 1,
                CheckIn   = DateTime.Now.Date,
                CheckOut  = DateTime.Now.AddDays(3).Date,
                Guests    = new List <GuestModel>()
                {
                    new GuestModel()
                    {
                        EntityId       = 0,
                        BookingModelId = 0,
                        FirstName      = "First Name User",
                        LastName       = "Last Name User",
                        IsMinor        = false
                    }
                },
                Rentals = new List <RentalModel>()
                {
                    new RentalModel()
                    {
                        LodgingRentalId = 1
                    }
                }
            }
                );
            await ctx.SaveChangesAsync();

            var checkIn  = DateTime.Now.Date;
            var checkOut = DateTime.Now.AddDays(3).Date;
            var actual   = await bookings.SelectAsync(e =>
                                                      (checkIn <= e.CheckIn && checkOut >= e.CheckIn) ||
                                                      (checkIn <= e.CheckOut && checkOut >= e.CheckOut) ||
                                                      (checkIn <= e.CheckIn && checkOut >= e.CheckOut) ||
                                                      (checkIn >= e.CheckIn && checkOut <= e.CheckOut));

            Assert.NotEmpty(actual);
        }
Esempio n. 23
0
        public async void Test_Repository_Update()
        {
            using var ctx = new BookingContext(options);
            var bookings = new Repository <BookingModel>(ctx);

            ctx.Bookings.Add(
                new BookingModel()
            {
                EntityId  = 0,
                AccountId = 1,
                LodgingId = 1,
                CheckIn   = DateTime.Now.Date,
                CheckOut  = DateTime.Now.AddDays(3).Date,
                Guests    = new List <GuestModel>()
                {
                    new GuestModel()
                    {
                        EntityId       = 0,
                        BookingModelId = 0,
                        FirstName      = "First Name User",
                        LastName       = "Last Name User",
                        IsMinor        = false
                    }
                },
                Rentals = new List <RentalModel>()
                {
                    new RentalModel()
                    {
                        LodgingRentalId = 1
                    }
                }
            }
                );
            await ctx.SaveChangesAsync();

            var booking = await ctx.Bookings.FirstAsync();

            booking.CheckOut = DateTime.Now;
            bookings.Update(booking);

            var result = ctx.Bookings.Find(booking.EntityId);

            Assert.Equal(booking.CheckOut, result.CheckOut);
            Assert.Equal(EntityState.Modified, ctx.Entry(result).State);
        }
        public async Task SaveEventRequest <T>(Guid id)
        {
            // ** saving event...
            _logger.CreateLogger <EventRequestManager>().LogInformation("----- Saving event for idempotency of integration event: {IntegrationEventId} at {AppName}", id, Program.AppName);

            var request = new EventRequest()
            {
                Id   = id,
                Name = typeof(T).Name,
                Time = DateTime.UtcNow
            };

            _context.Add(request);

            await _context.SaveChangesAsync();

            //throw new Exception($"Request with {id} already exists");
        }
Esempio n. 25
0
        public async void Test_Repository_SelectAsyncById_HasRentals()
        {
            using var ctx = new BookingContext(options);
            var bookings = new Repository <BookingModel>(ctx);

            ctx.Bookings.Add(
                new BookingModel()
            {
                EntityId  = 0,
                AccountId = 1,
                LodgingId = 1,
                CheckIn   = DateTime.Now.Date,
                CheckOut  = DateTime.Now.AddDays(3).Date,
                Guests    = new List <GuestModel>()
                {
                    new GuestModel()
                    {
                        EntityId       = 0,
                        BookingModelId = 0,
                        FirstName      = "First Name User",
                        LastName       = "Last Name User",
                        IsMinor        = false
                    }
                },
                Rentals = new List <RentalModel>()
                {
                    new RentalModel()
                    {
                        LodgingRentalId = 1
                    }
                }
            }
                );
            await ctx.SaveChangesAsync();

            var actual = (await bookings.SelectAsync(e => e.EntityId == 1)).FirstOrDefault();

            Assert.NotEmpty(actual.Rentals);
        }
Esempio n. 26
0
        public async void Test_Count(BookingModel booking, StayModel stay)
        {
            await _connection.OpenAsync();

            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    await ctx.Bookings.AddAsync(booking);

                    await ctx.Stays.AddAsync(stay);

                    await ctx.SaveChangesAsync();
                }
                using (var ctx = new BookingContext(_options))
                {
                    var bookings     = new Repository <BookingModel>(ctx);
                    var bookingCount = bookings.Count();

                    Assert.Equal(1, bookingCount);
                }

                using (var ctx = new BookingContext(_options))
                {
                    var stays     = new Repository <StayModel>(ctx);
                    var stayCount = stays.Count();
                    Assert.Equal(1, stayCount);
                }
            }
            finally
            {
                _connection.Close();
            }
        }
Esempio n. 27
0
 public async Task CommitAsync()
 {
     await _context.SaveChangesAsync();
 }
        //[Route("api/Account/Register")][ FromBody ]
        public async Task <IActionResult> Register(
            RegisterViewModel model)
        {
            IEnumerable <City> d = _context.City;

            ViewBag.Cities   = d;
            ViewBag.Username = GetUserName().Result;
            try
            {
                if (ModelState.IsValid)
                {    //добавление нового пользователя при регистрации
                    User user = new User
                    {
                        Fio                  = model.Fio,
                        Email                = model.Email,
                        UserName             = model.UserName,
                        PhoneNumber          = model.PhoneNumber,
                        PhoneNumberConfirmed = true,
                        Address              = model.Address,
                        IdCity               = model.IdCity
                    };
                    // Добавление нового пользователя
                    var result = await _userManager.CreateAsync(user,
                                                                model.Password);

                    await _signInManager.SignOutAsync();

                    await _signInManager.SignInAsync(user, false); // установка куки

                    if (result.Succeeded)                          //если успешно
                    {
                        Log.WriteSuccess("AccountController.Register", "Пользователь добавлен и вошел в систему.");
                        IdentityResult x = await _userManager.AddToRoleAsync(user, "user");    //роль - пользователь

                        var msg = new
                        {
                            message = "Добавлен новый пользователь: " + user.UserName
                        };

                        IEnumerable <City> b = d.Where(c => c.Id == user.IdCity);
                        Order order          = new Order()
                        {
                            User         = user,
                            UserId       = user.Id,
                            Amount       = 0,
                            Active       = 1,
                            SumOrder     = 0,
                            DateDelivery = DateTime.Now.AddDays(b.FirstOrDefault().DeliveryTime),
                            DateOrder    = DateTime.Now
                        };
                        //  order.DateDelivery= DateTime.Now.AddMonths(1);
                        _context.Order.Add(order);         //добавление заказа в БД
                        await _context.SaveChangesAsync(); //асинхронное сохранение изменений

                        Log.WriteSuccess(" OrdersController.Create", "добавление заказа " + order.Id + " в БД");
                        //return Ok(msg);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {    //вывод ошибок при неудаче
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty,
                                                     error.Description);
                        }
                        Log.WriteSuccess("AccountController.Register", "Пользователь не добавлен.");
                        var errorMsg = new
                        {
                            message = "Пользователь не добавлен.",
                            error   = ModelState.Values.SelectMany(e =>
                                                                   e.Errors.Select(er => er.ErrorMessage))
                        };
                        return(View(model));
                    }
                }
                else
                {    //если неверно введены данные
                    Log.WriteSuccess("AccountController.Register", "Неверные входные данные.");
                    var errorMsg = new
                    {
                        message = "Неверные входные данные.",
                        error   = ModelState.Values.SelectMany(e =>
                                                               e.Errors.Select(er => er.ErrorMessage))
                    };
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                var errorMsg = new
                {
                    message = "Неверные входные данные.",
                    error   = ModelState.Values.SelectMany(e =>
                                                           e.Errors.Select(er => er.ErrorMessage))
                };
                return(View(model));
            }
        }
Esempio n. 29
0
 /// <summary>
 /// Represents the _UnitOfWork_ `CommitAsync` method
 /// </summary>
 /// <returns></returns>
 public async Task <int> CommitAsync() => await _context.SaveChangesAsync();
Esempio n. 30
0
        public async Task <int> CommitAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await domainEventsDispatcher.DispatchAsync();

            return(await ctx.SaveChangesAsync(cancellationToken));
        }