コード例 #1
0
        public Task SignUpAsync(Guid id, string email, string password, string role)
        {
            var user = new User(id, email, role);

            user.SetPassword(password, _passwordHasher);
            _usersRepository.Add(user);

            return(Task.FromResult(user));
        }
コード例 #2
0
        public Users CreateUser(string firstName, string lastName)
        {
            Users user = new Users {
                UserFirstName = firstName,
                UserLastName  = lastName
            };

            UsersRepository.Add(user);
            return(user);
        }
コード例 #3
0
 public IActionResult Insert(User user)
 {
     if (ModelState.IsValid)
     {
         usersRepository.Add(user);
         return(RedirectToAction("Index"));
     }
     ViewBag.Collections = Get();
     return(View("Index"));
 }
コード例 #4
0
        public ActionResult Create([Bind("Name,CanCreatePlan,Removed")] Users users)
        {
            if (ModelState.IsValid)
            {
                usersRepository.Add(users);
                return(RedirectToAction("Index"));
            }

            return(Ok(users));
        }
コード例 #5
0
ファイル: ReposTests.cs プロジェクト: zilius/MVC-asp.net
        private void TestAdd()
        {
            var userToadd = new User
            {
                Password  = "******",
                Email     = "testEmail",
                BirthDate = DateTime.Now,
                Name      = "testName"
            };

            repo.Add(userToadd);
        }
コード例 #6
0
ファイル: UnitTest1.cs プロジェクト: IriyaKun/blog-engine
        public void UserShouldBeAdded()
        {
            var user = new User()
            {
                Email          = "*****@*****.**",
                HashedPassword = "******",
                Login          = "******",
                NameSurname    = "Gomel Ilya"
            };

            Assert.Equal(BlogOperationResult.OK, _repo.Add(user));
        }
コード例 #7
0
        public ActionResult Create([Bind(Include = "Id,UserName,Password,FirstName,LastName,Mail")] Users users)
        {
            if (ModelState.IsValid)
            {
                users.Id = Guid.NewGuid();
                usersRepository.Add(users);
                usersRepository.Save();
                return(RedirectToAction("Index"));
            }

            return(View(users));
        }
コード例 #8
0
        public ActionResult <string> Get(int id)
        {
            Users model = new Users();

            model.NickName    = "张三";
            model.PassWord    = "******";
            model.UserName    = "******";
            model.Description = "xx";

            UsersRepository.Add(model);
            UsersRepository.SaveChanges();
            return(new JsonResult(new { users = model }));
        }
コード例 #9
0
        public Users AddUser([FromForm] Users user)
        {
            bool check = _UsersRepository.CheckExistUser(user.Gmail, user.Password);

            if (check == true)
            {
                _UsersRepository.Add(user);
                return(user);
            }
            else
            {
                return(user);
            }
        }
コード例 #10
0
        public void Add_Test()
        {
            Mock <BaseStartupDemo> mockedContext = new Mock <BaseStartupDemo>();

            mockedContext.Object.Users = LoadMockedUsers();

            UsersRepository repo = new UsersRepository(mockedContext.Object, false);

            repo.Add(new DtoUser(0, "NewUser", "New User Hash", true));

            DtoUser added = (from u in mockedContext.Object.Users where u.UserName == "NewUser" select u).FirstOrDefault();

            Assert.IsNotNull(added);
        }
コード例 #11
0
        public ActionResult Register(User newUser)
        {
            User existUser = UsersRepository.GetByLogin(newUser.Login);

            if (existUser != null)
            {
                return(ErrorToJson("Пользователь с таким логином уже существует."));
            }

            string error = "";

            if (newUser.Login == null ||
                !new Regex(@"^[a-zA-Z][A-Za-z0-9]{1,16}$").IsMatch(newUser.Login))
            {
                error = "Логин не отвечает требованиям";
            }
            else if (newUser.Name == null ||
                     !new Regex(@"^.{2,20}$").IsMatch(newUser.Name))
            {
                error = "Имя пользователя не отвечает требованиям";
            }
            else if (newUser.Password == null ||
                     !new Regex(@"^[A-Za-z0-9.,!?(){}<>;:'""\\|/*\-+=_@#№$^]{5,20}$").IsMatch(newUser.Password))
            {
                error = "Пароль не отвечает требованиям";
            }
            // До введения системы персонажей description будет тут выполнять роль почты
            else if (newUser.Description == null ||
                     !new Regex(@"^[a-zA-Z0-9\-_.]+@.+\.[a-z]{1,4}$").IsMatch(newUser.Description))
            {
                error = "Неподдерживаемый формат почтового адреса";
            }

            if (!error.IsEmpty())
            {
                return(ErrorToJson(error));
            }

            newUser.AvatarImageName = "default_avatar.png";
            newUser.Role            = UserRoles.User;
            var user = UsersRepository.Add(newUser);

            UsersRepository.SaveChanges();
            AuthenticationService.Login(user, false);

            var response = new { RedirectURL = Url.Action("Index", "Home") };

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
コード例 #12
0
        public ActionResult SignIn(LoginSignModel loginSignModel)
        {
            User userToAdd = null;

            if (ModelState.IsValid)
            {
                UsersRepository.Add(loginSignModel.SignInUser.FirstName, loginSignModel.SignInUser.LastName, loginSignModel.SignInUser.BirthDate, loginSignModel.SignInUser.Email, loginSignModel.SignInUser.UserName, loginSignModel.SignInUser.Password, out userToAdd);
                HttpCookie cookie = new HttpCookie("SignInCookie");
                cookie.Value   = userToAdd.Id.ToString() + "," + userToAdd.FirstName;
                cookie.Expires = DateTime.Now.AddMinutes(10);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                return(RedirectToAction("Index", loginSignModel));
            }
            return(View(loginSignModel));
        }
コード例 #13
0
        public static Users Register(Users inst, ref string message)
        {
            if (UsersRepository.GetByName(inst.name) != null)
            {
                message = "账号已存在,请更换!";
                return(null);
            }

            int newId = UsersRepository.Add(inst);

            if (newId > 0)
            {
                return(UsersRepository.GetById(newId));
            }
            return(null);
        }
コード例 #14
0
        public void AddUser(Users entityToAdd)
        {
            IUsersRepository repo = new UsersRepository(getEntities());

            Entities.Users entityToAdd2 = Mapper.Map <Users, Entities.Users>(entityToAdd);
            repo.Add(entityToAdd2);
            switch (entityToAdd.UserType.ToUpper())
            {
            case "ADMINISTRATOR":
                IAdministratorsRepository adminRepo = new AdministratorsRepository(getEntities());
                Entities.Administrators   admin     = new Entities.Administrators()
                {
                    UserId = entityToAdd.Id
                };
                adminRepo.Add(admin);
                break;

            case "MANAGER":
                IManagersRepository managerRepo = new ManagersRepository(getEntities());
                Entities.Managers   manager     = new Entities.Managers()
                {
                    UserId = entityToAdd.Id
                };
                managerRepo.Add(manager);
                break;

            case "STUDENT":
                IStudentsRepository studentRepo = new StudentsRepository(getEntities());
                Entities.Students   student     = new Entities.Students()
                {
                    UserId = entityToAdd.Id
                };
                studentRepo.Add(student);
                break;

            case "TEACHER":
                ITeachersRepository teacherRepo = new TeachersRepository(getEntities());
                Entities.Teachers   teacher     = new Entities.Teachers()
                {
                    UserId = entityToAdd.Id
                };
                teacherRepo.Add(teacher);
                break;

            default:; break;
            }
        }
コード例 #15
0
        public void Add_In_ReadOnly_Test()
        {
            Mock <BaseStartupDemo> mockedContext = new Mock <BaseStartupDemo>();

            mockedContext.Object.Users = LoadMockedUsers();

            UsersRepository repo        = new UsersRepository(mockedContext.Object, true);
            Exception       expected_ex = null;

            try
            {
                repo.Add(new DtoUser(0, "NewUser", "New User Hash", true));
            }
            catch (ReadOnlyException ex) { expected_ex = ex; }

            Assert.IsNotNull(expected_ex);
        }
コード例 #16
0
        public static async void Populate(DatabaseContext s)
        {
            var categoryRepo = new IngredientsCategoryRepository(s);
            IEnumerable <IngredientCategory> categories = GetDefaultCategories();

            foreach (var ingredientCategory in categories)
            {
                await categoryRepo.Add(ingredientCategory);
            }
            var fridgeRepos    = new FridgeRepository(s);
            var ingredientRepo = new IngredientsRepository(s, categoryRepo, fridgeRepos);
            var recipeRepo     = new RecipesRepository(s, fridgeRepos, ingredientRepo);

            Ingredient i1   = Ingredient.Create(categories.First().Id, "i1", "cup", 0.9);
            Ingredient i2   = Ingredient.Create(categories.First().Id, "i2", "piece", 1.9);
            Ingredient i3   = Ingredient.Create(categories.First().Id, "i3", "slice", 0.5);
            Ingredient i4   = Ingredient.Create(categories.First().Id, "i3", "cup", 30);
            User       user = User.Create("xx", true, "*****@*****.**", "sh", "sdsbdk", "sureal");

            var userRepo = new UsersRepository(s);
            await userRepo.Add(user);

            await ingredientRepo.Add(i1);

            await ingredientRepo.Add(i2);

            await ingredientRepo.Add(i3);

            await ingredientRepo.Add(i4);

            Recipe recipe1 = Recipe.Create(user.Id, "r1", "reteta", RecipeStatusType.Approved, 10, 1, KitchenType.Asian);
            Recipe recipe2 = Recipe.Create(user.Id, "r2", "reteta2", RecipeStatusType.Approved, 15, 2, KitchenType.Unspecified);
            await recipeRepo.Add(recipe1);

            await recipeRepo.Add(recipe2);

            await recipeRepo.UpdateAllCosts();

            await fridgeRepos.Add(PairItem.Create(i1.Id, recipe1.Id, 2));

            await fridgeRepos.Add(PairItem.Create(i2.Id, recipe1.Id, 4));

            await fridgeRepos.Add(PairItem.Create(i3.Id, recipe1.Id, 1));

            await fridgeRepos.Add(PairItem.Create(i1.Id, recipe2.Id, 3));
        }
コード例 #17
0
 public bool GetNewUser(User newUser)
 {
     lock (_lockObj5)
     {
         if (IsExistUser(newUser))
         {
             return(false);
         }
         UsersRepository.Add(newUser);
         UserWithStatus userWithStatus = new UserWithStatus {
             UserName = newUser.UserName, Status = StatusOfConnection.Offline
         };
         UsersWithStatus.Add(userWithStatus);
         UpdateAllUsersNamesAndConnectionStatus();
         return(true);
     }
 }
コード例 #18
0
        public void Given_Repository_When_Delete_Then_ShouldBe_Correct()
        {
            RunOnDatabase(async s =>
            {
                DestroyDatabase();
                // Arrange
                var repository = new UsersRepository(s);
                var user       = GetDefaultUsers().First();

                // Act
                await repository.Add(user);
                await repository.Delete(user.Id);

                // Assert
                var users = repository.GetAll();
                Assert.AreEqual(0, users.Result.ToList().Count);
            });
        }
コード例 #19
0
        public void TestGetUserByUsername_NormalCase_ShouldReturnUser()
        {
            var userList = new List <User>()
            {
                new User("newUser", "123456", Role.Student),
                new User("anotherNewUser", "1234567", Role.Lecturer),
                new User("andAnotherOne", "1234568", Role.Student)
            };

            foreach (var user in userList)
            {
                users.Add(user);
            }

            var actualUser = users.GetByUsername("newUser");

            Assert.AreEqual(userList[0], actualUser);
        }
コード例 #20
0
        public void Given_Repository_When_Update_Then_ShouldBe_Correct()
        {
            RunOnDatabase(async s =>
            {
                DestroyDatabase();
                // Arrange
                var repository = new UsersRepository(s);
                var user       = GetDefaultUsers().First();

                // Act
                await repository.Add(user);
                user.Update("new name", true, "*****@*****.**", "pass12_676", "gcsw2345678hgh", "hello world");
                await repository.Edit(user);

                // Assert
                var addedUser = repository.FindById(user.Id);
                Assert.AreEqual(addedUser.Result.UserName, "new name");
            });
        }
コード例 #21
0
        public void Test_Auction_Created_Successfully()
        {
            var repo     = new AuctionRepository();
            var userRepo = new UsersRepository();
            var user     = new User()
            {
                UserName = testUserName
            };

            userRepo.Add(user);
            userRepo.SetLogin(user, true);
            var sut       = new AuctionService(repo, userRepo);
            var auctionId = sut.CreateAuction(testUserName, DateTime.UtcNow.AddDays(2));
            var auction   = repo.FindAuctionById(auctionId);

            Assert.NotNull(auction);
            Assert.Equal(testUserName, auction.Seller.UserName);
            Assert.Equal(auctionId, auction.Id);
        }
        public void AddNewUsersServices(UsersDTO entity)
        {
            Users users = new Users
            {
                UserRoleId     = entity.UserRoleId,
                UserName       = entity.UserName,
                UserPassword   = entity.UserPassword,
                UserPhoto      = entity.UserPhoto,
                NameSurname    = entity.NameSurname,
                IdentityNumber = entity.IdentityNumber,
                Phone          = entity.Phone,
                Email          = entity.Email,
                TerritoryId    = entity.TerritoryId,
                RegionId       = entity.RegionId,
                CountryId      = entity.CountryId
            };

            usersRepository.Add(users);
        }
コード例 #23
0
ファイル: UsersController.cs プロジェクト: NevilleAdrian/Zika
        public async Task <IActionResult> Create(Email email)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    bool result = await _repo.Add(email);

                    if (result)
                    {
                        return(RedirectToAction("Index"));
                    }
                    return(View("Create"));
                }
                catch
                {
                }
            }
            return(RedirectToAction("Error", "Home"));
        }
コード例 #24
0
        public void CreateEntity_FromListItem_EntityFilledWithRightData()
        {
            Perform(web =>
            {
                try
                {
                    UsersRepository.Add(web, MockUsers.User1);
                    var item = UsersRepository.GetEntitiesByTitle(web, MockUsers.User1.DisplayName)[0].ListItem;

                    var entity = UsersRepository.CreateEntity(web, item);

                    Assert.IsNotNull(entity);
                    Assert.AreEqual(MockUsers.User1.DisplayName, entity.DisplayName);
                }
                finally
                {
                    UsersRepository.DeleteAll(web);
                }
            });
        }
コード例 #25
0
        public void Given_Repository_When_GetAdmins_Then_TheCount_ShouldBe_3()
        {
            RunOnDatabase(async s =>
            {
                DestroyDatabase();
                // Arrange
                var repository = new UsersRepository(s);
                var userList   = GetDefaultUsers(5);

                // Act
                foreach (var usr in userList)
                {
                    await repository.Add(usr);
                }

                // Assert
                var users = repository.GetAdmins();
                Assert.AreEqual(3, users.Result.ToList().Count);
            });
        }
コード例 #26
0
        public void GetAllEntities_Recursive_SameItemsAmount()
        {
            Perform(web => {
                var folderName = "New Employees";

                try
                {
                    UsersRepository.AddRange(web, MockUsers.AllUsers);
                    UsersRepository.Add(web, folderName, MockUsers.User1);
                    var items = UsersRepository.GetAllEntities(web);

                    Assert.AreEqual(items.Length, MockUsers.AllUsers.Length + 1);
                }
                finally
                {
                    UsersRepository.DeleteAll(web);
                    UsersRepository.DeleteFolder(web, folderName);
                }
            });
        }
コード例 #27
0
        public void UploadAttachment_FromLocalPath_FileWasAttached()
        {
            Perform(web =>
            {
                try
                {
                    var user = MockUsers.User1;
                    UsersRepository.Add(web, user);

                    UsersRepository.UploadAttachment(web, user, "CV", Resources.Test_document);

                    Assert.AreEqual(1, user.ListItem.Attachments.Count);
                    Assert.AreEqual("CV", user.ListItem.Attachments[0]);
                }
                finally
                {
                    UsersRepository.DeleteAll(web);
                }
            });
        }
コード例 #28
0
 public ControllerResult CheckIn(string userName)
 {
     try
     {
         userRepository.Add(new User(userName));
         return(Ok());
     }
     catch (MongoWriteException ex)
     {
         string message = ex.Message;
         if (ex.WriteError.Code == DuplicatedKeyErrorCode)
         {
             message = "User with such name already exists";
         }
         return(Error(message));
     }
     catch (Exception ex)
     {
         return(Error(ex.Message));
     }
 }
コード例 #29
0
        public void GetEntities_FromSpecificFolder_EqualAmount()
        {
            var folderPath = "Old men";

            Perform(web => {
                try
                {
                    UsersRepository.Add(web, folderPath, MockUsers.User1);
                    UsersRepository.Add(web, folderPath, MockUsers.User2);

                    var oldMenEntities = UsersRepository.GetEntities(web, folderPath);

                    Assert.AreEqual(2, oldMenEntities.Length);
                }
                finally
                {
                    UsersRepository.DeleteAll(web);
                    UsersRepository.DeleteFolder(web, folderPath);
                }
            });
        }
コード例 #30
0
        public async Task <ActionResult> Register([FromBody] UserAuthDTO userAuth)
        {
            using (UnitOfWork uow = new UnitOfWork())
            {
                try
                {
                    UsersAuthRepository usersAuthRepository = new UsersAuthRepository(uow);
                    bool exist = await usersAuthRepository.Exist(userAuth);

                    if (!exist)
                    {
                        await usersAuthRepository.Add(userAuth);

                        userAuth = await usersAuthRepository.Login(userAuth);

                        UserDTO userDTO = new UserDTO
                        {
                            Id   = userAuth.Id,
                            Name = userAuth.Email
                        };

                        UsersRepository usersRepository = new UsersRepository(uow);
                        await usersRepository.Add(userDTO, true);

                        uow.Commit();
                        return(Ok());
                    }
                    else
                    {
                        return(this.Conflict());
                    }
                }
                catch (Exception e)
                {
                    uow.Rollback();
                    return(this.Conflict(e));
                }
            }
        }