public async Task <IActionResult> Create([Bind("AnketaId,Surname,Name,Middlename,SurnameR,NameR,MiddlenameR,Birthday,Sex,IdentityNumber,PassportSeries,PassportNumber,DateOfIssue,DateOfValidity,IssuedBy,PlaceOfBirth,Postcode,Region,TypeOfSettlement,NameOfSettlement,StreetType,StreetName,HouseNumber,HullNumber,ApartmentNumber,HomePhone,SocialBehavior,KinshipTypeFather,SurnameFather,NameFather,MiddlenameFather,AddressFather,KinshipTypeMother,SurnameMother,NameMother,MiddlenameMother,AddressMother,EducationLevel,Institution,YearOfEnding,PlaceOfWorkAndPosition,SeniorityGeneral,SeniorityProfileSpecialty,SpecialtyId,DocumentTypeId")] Anketa anketa)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);

                if (user == null)
                {
                    return(NotFound("Пользователь не найден"));
                }

                await _context.AddAsync(anketa);

                await _context.SaveChangesAsync();

                user.AnketaId = anketa.AnketaId;
                _context.Users.Update(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DocumentTypeId"] = new SelectList(_context.DocumentTypes, "DocumentTypeId", "Name", anketa.DocumentTypeId);
            ViewData["SpecialtyId"]    = new SelectList(_context.Specialties, "SpecialtyId", "GetSpecialtyNameBranch", anketa.SpecialtyId);
            return(View(anketa));
        }
        public async void AddTransfer(InnerTransfer transfer)
        {
            if (transfer.AccountSender != null && !transfer.AccountSender.Locked)
            {
                await context.AddAsync(transfer);

                if (transfer.TransferState.IsEqual(TransferStatesEnum.Confirmed))
                {
                    List <Transaction> transactions = transactionService.CreateTransactions(transfer);
                    transactionService.AddTransactions(transactions);
                }
                context.SaveChanges();
            }
            if (transfer.AccountSender == null)
            {
                await context.AddAsync(transfer);

                if (transfer.TransferState.IsEqual(TransferStatesEnum.Confirmed))
                {
                    List <Transaction> transactions = transactionService.CreateTransactions(transfer);
                    transactionService.AddTransactions(transactions);
                }
                context.SaveChanges();
            }
        }
Esempio n. 3
0
        private async Task <Corporation> GetOrCreateCorporation(int corporationId)
        {
            Corporation corp = await context.Corporations.FirstOrDefaultAsync(x => x.Id == corporationId);

            if (corp == null)
            {
                var corpdata = await eSIService.GetCorporation(corporationId);

                corp = new Corporation
                {
                    Id          = corporationId,
                    Name        = corpdata.Name,
                    Ticker      = corpdata.Ticker,
                    MemberCount = corpdata.MemberCount,
                    LastUpdated = DateTime.UtcNow
                };

                await context.AddAsync(corp);
            }
            else if (corp.LastUpdated < DateTime.UtcNow.AddHours(-24))
            {
                var corpdata = await eSIService.GetCorporation(corporationId);

                corp.Name        = corpdata.Name;
                corp.Ticker      = corpdata.Ticker;
                corp.MemberCount = corpdata.MemberCount;
                corp.LastUpdated = DateTime.UtcNow;
            }

            return(corp);
        }
        public async Task <Hotel> Add(Hotel hotel)
        {
            await applicationContext.AddAsync(hotel);

            await applicationContext.SaveChangesAsync();

            return(hotel);
        }
        public async Task SaveMachineConfiguration(string userId, EnigmaMachineConfigurationModelBL model)
        {
            await RemoveExisitngUserMachineConfigurations(userId);

            var configuration = mapper.Map <EnigmaConfiguration>(model);

            configuration.ApplicationUserId = userId;

            await context.AddAsync(configuration);

            await context.SaveChangesAsync();
        }
Esempio n. 6
0
        public async Task <T[]> UpdateAsync(IEnumerable <T> items)
        {
            var newItemsMap = items.ToDictionary(x => x.Id, x => x);
            var newItemsIds = newItemsMap.Keys.ToArray();
            var oldItemsMap = await Context.Set <T>()
                              .Where(_notDeleted)
                              .Where(x => newItemsIds.Contains(x.Id))
                              .ToDictionaryAsync(x => x.Id, x => x);

            foreach (var(newItemId, newItem) in newItemsMap)
            {
                if (!oldItemsMap.TryGetValue(newItemId, out var oldItem))
                {
                    await Context.AddAsync(newItem);

                    continue;
                }

                Context.Entry(oldItem).State = EntityState.Detached;
                newItem.CreatedAtUtc         = oldItem.CreatedAtUtc;
                newItem.UpdatedAtUtc         = DateTime.UtcNow;
                Context.Entry(newItem).State = EntityState.Modified;
            }

            return(newItemsMap.Select(x => x.Value).ToArray());
        }
        public async Task <IActionResult> AddTrainingManually(AddTrainingManuallyViewModel model)
        {
            if (model != null)
            {
                string userId = userManager.GetUserId(HttpContext.User);
                if (headHandler.IsNumberPresent(model.NumDocument, userId))
                {
                    ModelState.AddModelError($"Document:{model.NumDocument} is present in DB",
                                             $"Document:{model.NumDocument} with same number is present in DB");
                    return(RedirectToAction("AddTrainingManually"));
                }
                else
                {
                    var head = headHandler.GetHead(model.NumDocument, userId, model.TrainingName, model.Date.ToUniversalTime());
                    head.DateEnd  = model.Date.AddMinutes(model.Duration).ToUniversalTime();
                    head.UserId   = userId;
                    head.Calories = model.Calories;
                    await appContext.AddAsync(head);

                    await appContext.SaveChangesAsync();

                    int headId = headHandler.FindId(model.NumDocument, userId);
                    return(RedirectToAction("ViewTrainingSpecs", new { headId }));
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 8
0
        public async Task <IActionResult> Create(string Name)
        {
            if (ModelState.IsValid)
            {
                var group = _context.Groups.SingleOrDefault(p => p.Name == Name);
                if (group == null)
                {
                    var user  = _context.Users.SingleOrDefaultAsync(p => p.Name == User.Identity.Name);
                    var Group = new Group()
                    {
                        Name    = Name,
                        AdminId = (await user).Id,
                    };
                    await _context.AddAsync(Group);

                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
        public async Task <bool> AddOrder(Product product, OrderModel model)
        {
            var user = await _userManager.FindByIdAsync(model.UserId);

            if (user != null)
            {
                Order orderBD = await IsIdentityProduct(user.Id, product.ProductId);

                if (model.Count > 0)
                {
                    if (orderBD == null)
                    {
                        Order orderInDb = new Order()
                        {
                            TotalCost = model.Count * product.Price, UserId = user.Id, Product = product, User = user, IdProduct = product.ProductId, DateOfOrder = DateTime.Now, Count = model.Count
                        };
                        await _context.AddAsync(orderInDb);
                    }
                    else
                    {
                        orderBD.Count     = model.Count;
                        orderBD.IsConfirm = false;
                    }
                }
                await _context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
Esempio n. 10
0
        public async Task CreateOrUpdate_Success()
        {
            //arrange
            var pedido = new Pedido(
                new List <ItemPedido> {
                new ItemPedido("001", "produto 001", 1, 12.34m),
                new ItemPedido("002", "produto 002", 2, 23.45m)
            },
                "clienteId", "clienteNome", "*****@*****.**", "fone", "endereco", "complemento", "bairro", "municipio", "uf", "12345-678");

            var options = new DbContextOptionsBuilder <ApplicationContext>().UseInMemoryDatabase(databaseName: "database_name").Options;

            using (var context = new ApplicationContext(options))
            {
                var pedidoEntity = await context.AddAsync(pedido);

                var repo = new PedidoRepository(context);

                //act
                Pedido result = await repo.CreateOrUpdate(pedido);

                //assert
                Assert.Equal(2, result.Itens.Count);
                Assert.Collection(result.Itens,
                                  item => Assert.Equal("001", item.ProdutoCodigo),
                                  item => Assert.Equal("002", item.ProdutoCodigo)
                                  );
            }
        }
Esempio n. 11
0
        public async Task <bool> Register(string username, string password, string firstName, string lastName)
        {
            User user = new User
            {
                Username  = username,
                Password  = password,
                FirstName = firstName,
                LastName  = lastName,
                Role      = "Admin"
            };
            var isExist = _context.Users.Where(x => x.Username == username).Any();

            if (isExist)
            {
                return(false);
            }

            try
            {
                await _context.AddAsync(user);

                await _context.SaveChangesAsync();
            }
            catch
            {
                return(false);
            }

            return(true);
        }
        public async Task CreateOrUpdate_Success()
        {
            //arrange
            var order = new Order(
                new List <OrderItem> {
                new OrderItem("001", "product 001", 1, 12.34m),
                new OrderItem("002", "product 002", 2, 23.45m)
            },
                "customerId", "customerName", "*****@*****.**", "phone", "address", "additionalAddress", "district", "city", "state", "12345-678");

            var options = new DbContextOptionsBuilder <ApplicationContext>().UseInMemoryDatabase(databaseName: "database_name").Options;

            using (var context = new ApplicationContext(options))
            {
                var orderEntity = await context.AddAsync(order);

                var repo = new OrderRepository(context);

                //act
                Order result = await repo.CreateOrUpdate(order);

                //assert
                Assert.Equal(2, result.Items.Count);
                Assert.Collection(result.Items,
                                  item => Assert.Equal("001", item.ProductCode),
                                  item => Assert.Equal("002", item.ProductCode)
                                  );
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> Create(ArticleFormObject formObject)
        {
            var article = new Models.Article
            {
                Slug         = sanitizer.Sanitize(formObject.Slug),
                Title        = sanitizer.Sanitize(formObject.Title),
                Description  = sanitizer.Sanitize(formObject.Description),
                ThumbnailUrl = sanitizer.Sanitize(formObject.ThumbnailUrl)
            };
            var index = 0;

            foreach (var chapter in formObject.ArticleChapters)
            {
                article.ArticleChapters.Add(new ArticleChapter
                {
                    Name          = sanitizer.Sanitize(chapter.LinkText),
                    Text          = sanitizer.Sanitize(chapter.Text),
                    ChapterNumber = ++index
                });
            }
            await context.AddAsync(article);

            await context.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Esempio n. 14
0
        public async Task SendInfo(TravianPlayerHistory dto)
        {
            dto.Date = DateTime.UtcNow.Date;

            await db.AddAsync(dto);

            await db.SaveChangesAsync();
        }
        public async Task <Equipment> AddEquipment(Equipment equipment)
        {
            var newEquipment = await _dbContext.AddAsync(equipment);

            await _dbContext.SaveChangesAsync();

            return(newEquipment.Entity);
        }
Esempio n. 16
0
        public async Task <TEntity> AddAsync(TEntity entity)
        {
            await _context.AddAsync(entity);

            await _context.SaveChangesAsync();

            return(entity);
        }
Esempio n. 17
0
        public async Task <Account> CreateAsync(Account account)
        {
            await _ctx.AddAsync(account);

            await _ctx.SaveChangesAsync();

            return(await FindAsync(account.Id));
        }
Esempio n. 18
0
            public static void Seed(ApplicationContext context)
            {
                User  user = UserData.FakeUser.Generate();
                Event e    = EventData.FakeEvent.Generate();

                context.Add(user);
                context.AddAsync(e);
                context.SaveChanges();
            }
Esempio n. 19
0
        public async Task AddAsync(User user)
        {
            user.CreateAt = DateTime.UtcNow;
            user.UpdateAt = DateTime.UtcNow;

            await _context.AddAsync(user);

            await _context.SaveChangesAsync();
        }
        public async Task CreateAsync(User user)
        {
            if (user != null)
            {
                await dbcontext.AddAsync(user);

                await dbcontext.SaveChangesAsync();
            }
        }
Esempio n. 21
0
        public async Task AddDogAsync(DogDTO addDogDTO, string userId)
        {
            var newDog = mapper.Map <DogDTO, Dog>(addDogDTO);

            newDog.UserId = userId;
            await applicationContext.AddAsync(newDog);

            await applicationContext.SaveChangesAsync();
        }
Esempio n. 22
0
        public async Task <Room> AddRoom(int hotelId, Room room)
        {
            room.HotelId = hotelId;
            await context.AddAsync(room);

            await context.SaveChangesAsync();

            return(room);
        }
Esempio n. 23
0
        public async Task <IActionResult> LogIn(string type, AuthenticationModels.SocialLogIn model)
        {
            var handler = _authServices.FirstOrDefault(s => s.ProviderName == type);

            if (handler != null)
            {
                var identity = await handler.GetIdentity(model.Token);

                var user = await handler.FindUser(identity);

                if (user == null)
                {
                    await using var transaction = await _db.Database.BeginTransactionAsync();

                    try
                    {
                        var account = await handler.CreateAccount(identity);

                        if (account == null)
                        {
                            return(BadRequest());
                        }

                        user = await SignUpInternal(new AuthenticationModels.SignUp());

                        if (user == null)
                        {
                            return(BadRequest());
                        }
                        account.UserId = user.Id;

                        await _db.AddAsync(account);

                        await _db.SaveChangesAsync();

                        await transaction.CommitAsync();
                    }
                    catch (Exception)
                    {
                        return(BadRequest());
                    }
                }

                user = await _userService.Authenticate(user);

                if (user != null)
                {
                    return(Ok(user.WithoutSensitive(token: true, useLikeIds: true, useFavoriteIds: true, useSaleIds: true)));
                }

                return(NotFound(ModelState));
            }

            ModelState.AddModelError("Auth", $"Неправильный тип социальной сети.");
            return(NotFound(ModelState));
        }
Esempio n. 24
0
        public static async Task <Assigment> CreateAssigmentAsync(ApplicationContext dbContext)
        {
            var assigment = BuildAssigment();

            await dbContext.AddAsync(assigment);

            await dbContext.SaveChangesAsync();

            return(assigment);
        }
Esempio n. 25
0
        public async Task <IActionResult> Store([FromBody] Movie movie)
        {
            await _context.AddAsync(movie);

            await _context.SaveChangesAsync();

            var uri = $"movie/{movie.Id}";

            return(Created(uri, movie));
        }
        public async Task Add(Part part)
        {
            _logger.LogInformation($"Attempting to save new part Id:{part.Id} Manufacturer's #:{part.MfrsPartNumber}.");
            await _applicationContext.BeginTransaction();

            await _applicationContext.AddAsync(part);

            await _applicationContext.Commit();

            _logger.LogInformation($"Successfully saved new part Id:{part.Id} Manufacturer's #:{part.MfrsPartNumber}.");
        }
        public async Task <UserInfo> CreateUserInfo(User user, PassportInfo passportInfo, UserInfoViewModel model, ContactInfo contact)
        {
            DateTime birthDay = DateTime.Parse(model.BirthDay);
            UserInfo userInfo = new UserInfo {
                UserId = user.Id, FirstName = model.FirstName, SecondName = model.SecondName, MiddleName = model.MiddleName, PassportInfoId = passportInfo.Id, Email = model.Email, BirthDay = birthDay, Inn = model.Inn, CitezenshipId = model.CountryId, Gender = model.Gender, ContactInfoId = contact.Id
            };
            await context.AddAsync(userInfo);

            context.SaveChanges();
            return(userInfo);
        }
        public async Task <OkObjectResult> CreateChat([FromBody] Chat chat)
        {
            chat.CreationDate     = DateTime.UtcNow;
            chat.LastModification = DateTime.UtcNow;
            chat.Status           = "0";

            await _context.AddAsync(chat);

            await _context.SaveChangesAsync();

            return(Ok(chat));
        }
            public async Task <int> Handle(AddRationalResponseCommand request, CancellationToken cancellationToken)
            {
                var entity = new RationalResponseExercise();

                entity.Entries     = request.Entries;
                entity.UserId      = request.UserId;
                entity.CreatedDate = DateTime.UtcNow;
                var added = await _context.AddAsync <RationalResponseExercise>(entity, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(added.Entity.Id);
            }
        public async Task <ActionResult <User> > Post(User user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            await _dbcontext.AddAsync(user);

            await _dbcontext.SaveChangesAsync();

            return(Ok(user));
        }