protected void Page_Load(object sender, EventArgs e) { // disable caching for masterpage (so that OutputCache will not cache this pages) Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); // check if user is log on if (MyWebAuthentication.IsUserLogOn()) { UsersLogic users = new UsersLogic(); // if he is log on thats mean i can access to his userID: User user = users.GetUser(MyWebAuthentication.UserID); // set the userName inside the button btnUserOptions.Text = user.UserName; // hide the two links of signin and signup lnkSignIn.Visible = lnkSignUp.Visible = false; // if the user is Admin show link to AdminPage if (user.IsAdmin == true) { lnkLinkToAdmin.Visible = true; } } else// hide the button that sould hold the userName if the user is not login { btnUserOptions.Visible = false; } }
public string DeAllocateRole(string Email, string Role) { try { if (Context.User.IsInRole("Administrator")) { string myEmail = Email.Trim(); int myRole = Convert.ToInt32(Role.Trim()); UserDeAllocate myResult = new UsersLogic().DeAllocateRole(myEmail, myRole); if (myResult == UserDeAllocate.UserIsAdmin) { return("Role Cannot Be De Allocated : Same Permission"); } else if (myResult == UserDeAllocate.OnlyUser) { return("User Must Either Be an Administrator, a User, or Both"); } else { return(""); } } else { return(""); } } catch (Exception Exception) { throw Exception; } }
private void MakeLogin() { try { using (StartOperation()) { User user = UsersLogic.GetUserByLogin(Login); if (user == null || !PasswordManager.ValidatePassword(Password, user.Password)) { ErrorMessage = "Incorrect login or password."; } else { var mainViewModel = ServiceLocator.GetInstance <MainViewModel>(); mainViewModel.InitializeAsync(user.Id); mainViewModel.Show(); Close(true); } } } catch (Exception exc) { ErrorMessage = "Can't connect to database. Try again."; Debug.WriteLine(exc.ExpandToString()); } }
public string[] CheckProductQuantities() { try { if (Context.User.IsInRole("User")) { User myLoggedUser = new UsersLogic().RetrieveUserByUsername(Context.User.Identity.Name); List <ShoppingCart> myShoppingCartItems = new ShoppingCartLogic().RetrieveAllShoppingCartItems(myLoggedUser.Id).ToList(); List <string> ViolatingIDs = new List <string>(); foreach (ShoppingCart myShoppingCartItem in myShoppingCartItems) { if (!new OrdersLogic().HasSufficientQuantity(myShoppingCartItem.ProductFK, myShoppingCartItem.Quantity)) { ViolatingIDs.Add(myShoppingCartItem.ProductFK.ToString()); } } return(ViolatingIDs.ToArray()); } else { return(new string[] { "" }); } } catch (Exception Exception) { throw Exception; } }
/// <summary> /// Выполняем метод, если авторизация успешна /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AuthLogic_AuthSuccessful(object sender, MyEventArgs e) { // Выделяем память остальной логике для работы с сервисом ВК //token = e.GetToken(); UserLogic = new UsersLogic(token); GroupLogic = new GroupLogic(token); }
public void PutAUserWithExistingUserPasses() { var mock = new Mock <IUserRepository>(); var username = "******"; var email = "*****@*****.**"; var id = 1; var putUserModel = new PutUserModel { Username = username, Active = true, EmailAddress = email }; var userModel = new UserModel { Id = id, PassWord = "******", UserName = "******", Active = true, Created = new DateTime(), EmailAddress = "*****@*****.**", Updated = new DateTime() }; mock.Setup(e => e.CheckIfIdExists(id)).Returns(true); mock.Setup(e => e.CheckIfUserExists(username)).Returns(false); mock.Setup(e => e.CheckIfEmailExists(email)).Returns(false); mock.Setup(e => e.GetSingleUser(id)).Returns(userModel); var service = new UsersLogic(mock.Object); service.UpdateAUser(id, putUserModel); mock.Verify(x => x.Update(It.IsAny <UserModel>()), Times.Exactly(1)); }
public ActionResult NewMessage(HttpPostedFileBase file, string Receptor, string Message) { HttpCookie objRequestRead = Request.Cookies["auth"]; if (objRequestRead != null && objRequestRead["jwt"] != null && JWT.ValidateSession(objRequestRead["jwt"], objRequestRead["username"])) { if (objRequestRead != null) { LoggedUser = objRequestRead["username"]; } var user = new UsersLogic(); if (user.UserExist(Receptor)) { Messages.Create(LoggedUser + '|' + Receptor, Message, file); return(RedirectToAction("Index", new { receptor = Receptor })); } else { return(RedirectToAction("Index", new { receptor = "404" })); } } else { return(RedirectToAction("Error")); } }
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { UsersLogic users = new UsersLogic(); IEnumerable <User> usersList = users.GetUsers(); foreach (User user in usersList) { // convert the password to bytes array byte[] passBytes = Convert.FromBase64String(user.Password); // get the salt array with the default SaltSize in 'MyWebAuthentication' byte[] salt = new byte[MyWebAuthentication.SaltSize]; // fill the salt array with the values from passBytes Array.Copy(passBytes, 0, salt, 0, 16); // now i have the salt and i can hash the password that the user enterd string password = txtPassword.Text; string hashedPassword = MyWebAuthentication.HashPassword(password, salt); // the email that was entered string email = txtEmail.Text.ToLower(); // compare the two hashed passwords if (MyWebAuthentication.CompareHashedPasswords(hashedPassword, user.Password) == true && email == user.Email) // check if the email is correct also { // if password founds equal set the validator to valid and finish! args.IsValid = true; // set userID in the session MyWebAuthentication.UserID = user.UserID; return; } } // if no found equal password args.IsValid = false; }
public void GetByUserIdReturnsAValidUser() { var mock = new Mock <IUserRepository>(); var id = 1; var username = "******"; var password = "******"; mock.Setup(e => e.GetSingleUser(id)).Returns( new UserModel { Id = id, PassWord = password, UserName = username, Active = true, Created = new DateTime(), EmailAddress = "*****@*****.**", Updated = new DateTime() }); var service = new UsersLogic(mock.Object); var sut = service.GetById(id); Assert.Equal(sut.Id, id); Assert.Equal(sut.Username, username); }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Title = "Nutrition Tracker"; LogOutCommand = new RelayCommand( () => { User = null; Properties.Settings.Default["UserId"] = ""; Properties.Settings.Default.Save(); } ); ExitCommand = new RelayCommand( () => Application.Current.Shutdown() ); // bring the user guid from default settings try { string userId = Properties.Settings.Default["UserId"] as string; UsersLogic usersLogic = new UsersLogic(); User = usersLogic.GetUser(new Guid(userId)); } catch (Exception) { } }
protected override void OnClosed() { base.OnClosed(); UsersLogic.Dispose(); BooksLogic.Dispose(); OrdersLogic.Dispose(); }
public static void ValidateRoleForNewUser(this UsersLogic usersLogic, string role) { if (role.ToLowerInvariant() != "admin" && role.ToLowerInvariant() != "user") { throw new ArgumentException($"Role: {role} not valid must be either admin or user"); } }
public void AddToCart(string ProductID, string Quantity) { try { if (Context.User.IsInRole("User")) { Guid myProductID = Guid.Parse(ProductID.Trim()); int myQuantity = 0; User myLoggedUser = new UsersLogic().RetrieveUserByUsername(Context.User.Identity.Name); if (Quantity.Trim() != string.Empty) { myQuantity = Convert.ToInt32(Quantity.Trim()); } else { myQuantity = 1; } new ShoppingCartLogic().AddToCart(myLoggedUser.Id, myProductID, myQuantity); } } catch (Exception Exception) { throw Exception; } }
public string LoadShoppingCartItems() { try { if (Context.User.IsInRole("User")) { string HTML = ""; User myLoggedUser = new UsersLogic().RetrieveUserByUsername(Context.User.Identity.Name); List <ShoppingCart> myShoppingCartItems = new ShoppingCartLogic().RetrieveAllShoppingCartItems(myLoggedUser.Id).ToList(); List <Product> myProductList = new List <Product>(); foreach (ShoppingCart myShoppingCartItem in myShoppingCartItems) { myProductList.Add(new ProductsLogic().RetrieveProductByID(myShoppingCartItem.ProductFK.ToString())); } Product[] myProducts = myProductList.ToArray(); if (myProducts.Length > 0) { for (int i = 1; i <= (myProducts.Length + 4 / 4); i++) { int Counter = i * 4; HTML += "<tr>"; for (int j = (Counter - 3); j <= Counter; j++) { HTML += "<td>"; HTML += TDContents(myProducts[j - 1]); HTML += "</td>"; if (j == myProducts.Length) { goto LoopEnd; } } HTML += "</tr>"; } } LoopEnd: return(HTML); } else { return(""); } } catch (Exception Exception) { throw Exception; } }
public void K_GetAllUsersWithRoleAdmin_CanGetAllUsers_ReturnsTrue() { var userLogic = new UsersLogic(); List <User> result = (List <User>)userLogic.getAllUsersWithRole(0); Assert.IsTrue(result.Count > 0); }
public void Initialize(int userId) { using (StartOperation()) { Employee = UsersLogic.GetEmployeeByUserId(userId); Title = "Booko: " + Employee.Branch.Name; } }
public void M_GetAllUsersWithRoleDeveloper_CanGetAllUsers_ReturnsTrue() { var userLogic = new UsersLogic(); List <User> result = (List <User>)userLogic.getAllUsersWithRole(2); Assert.IsTrue(result.Count > 0); }
public static void ValidateEmailAddress(this UsersLogic usersLogic, string emailAddress) { var valid = new EmailAddressAttribute().IsValid(emailAddress); if (!valid) { throw new ArgumentException($"{emailAddress} was not a valid mailaddress"); } }
public void CompleteCheckout(string CreditCard) { try { if (Context.User.IsInRole("User")) { User myLoggedUser = new UsersLogic().RetrieveUserByUsername(Context.User.Identity.Name); List <ShoppingCart> myShoppingCartItems = new ShoppingCartLogic().RetrieveAllShoppingCartItems(myLoggedUser.Id).ToList(); List <OrderItem> myOrderItems = new List <OrderItem>(); foreach (ShoppingCart myShoppingCartItem in myShoppingCartItems) { UserTypeProduct myPriceType = new PriceTypesLogic().RetrievePriceTypeByID(myLoggedUser.UserTypeFK, myShoppingCartItem.ProductFK); OrderItem myOrderItem = new OrderItem(); myOrderItem.Id = myShoppingCartItem.ProductFK; double myPrice = 0; if (myPriceType != null) { myPrice = myPriceType.Price; double?NewPrice = 0; if ((myPriceType.DiscountDateFrom != null) && (myPriceType.DiscountDateTo != null) && (myPriceType.DiscountPercentage != null)) { if ((DateTime.Now >= myPriceType.DiscountDateFrom) && (DateTime.Now <= myPriceType.DiscountDateTo)) { NewPrice = myPriceType.Price - ((myPriceType.DiscountPercentage / 100) * myPriceType.Price); myPrice = Convert.ToDouble(NewPrice); } } } myOrderItem.Price = myPrice; myOrderItem.Quantity = myShoppingCartItem.Quantity; myOrderItems.Add(myOrderItem); } //if ( new OrdersLogic().AddOrder(null, myLoggedUser.Id, CreditCard.Trim(), myOrderItems); //{ //new UsersLogic().InsertCreditCardNumber(CreditCard.Trim(), myLoggedUser.Id); //new ShoppingCartLogic().EmptyCart(myLoggedUser.Id); //} } } catch (Exception Exception) { throw Exception; } }
public void N_ReturnAllUsers_CanGetAllUsers_ReturnsTrue() { DBBroker broker = new DBBroker(); var userLogic = new UsersLogic(); List <User> expected = (List <User>)broker.reaturnAllUsers(); List <User> result = (List <User>)userLogic.reaturnAllUsers(); Assert.AreEqual(result.Count, expected.Count); }
public IHttpActionResult AddUser(int id, string password) { var user = new UserDTO() { profileId = id, pass = password }; return(Ok(UsersLogic.AddUser(user))); }
public MarketPageUserViewModel() { usersLogic = UsersLogic.GetInstance(); historiesLogic = HistoriesLogic.GetInstance(); Condition = "Visible"; FullName = usersLogic.GetFullName(); Checks = new ObservableCollection <Check>(historiesLogic.GetChecks(UsersLogic.GetId())); SeeCheck = new RelayCommand <int>(ThisCheck); ProductsLogic.GetInstance(); }
public void D_RemoveUserLazar_CanRemovelUser_ReturnsTrue() { var userLogic = new UsersLogic(); User user = new User(); user.Username = "******"; var result = userLogic.removeUser(user); Assert.IsTrue(result); }
public void E_RemoveUserJovan_CanRemovelUser_ReturnsTrue() { var userLogic = new UsersLogic(); User user = new User(); user.Username = "******"; var result = userLogic.removeUser(user); Assert.IsTrue(result); }
public void DeleteAUserWithNonExistingUserFails() { var mock = new Mock <IUserRepository>(); var id = 1; mock.Setup(e => e.CheckIfIdExists(id)).Returns(false); var service = new UsersLogic(mock.Object); Assert.Throws <RecordNotFoundException>(() => service.DeleteAUser(id)); }
protected void btSignup_Click1(object sender, EventArgs e) { UsersLogic us = new UsersLogic(); if (us.checkExistPassword(password.Text)) { Label1.Text = "סיסמא קיימת בחר סיסמא אחרת"; } // else //us.addnew... }
private void WaitingOrder() { Task.Run(() => { while (orderViewModel.Condition == "Visible") { ; } Checks = new ObservableCollection <Check>(historiesLogic.GetChecks(UsersLogic.GetId())); }); }
public void C_RemoveUserIgor_CanRemovelUser_ReturnsTrue() { var userLogic = new UsersLogic(); User user = new User(); user.Username = "******"; var result = userLogic.removeUser(user); Assert.IsTrue(result); }
public void D_IsUsernameUnique2_CanGetInformationAbouthThat_ReturnsFalse() { var userLogic = new UsersLogic(); User user = new User(); user.Username = "******"; var result = userLogic.isUsernameUnique(user.Username); Assert.IsTrue(result); }
public void R_RemoveUser3_CanRemovelUser_ReturnsTrue() { var userLogic = new UsersLogic(); User user = new User(); user.Username = "******"; var result = userLogic.removeUser(user); Assert.IsTrue(result); }
public void ShouldThrowExceptionWhenUpdateUserFails() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Edit(It.IsAny<User>())) .Throws(new Exception()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); Assert.Throws<BlogException>(() => _usersLogic.Update(new Common.Contracts.User())); }
public void ShouldErrorWhenAddUserWhenUserExists() { var request = new Common.Contracts.User { UserName = "******", IdentityId = "bar", FirstName = "foo", LastName = "bar", EmailAddress = "*****@*****.**", BirthDate = DateTime.Now }; _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), false)) .Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.Add(request); Assert.NotNull(user.Error); Assert.AreEqual(user.Error.Id, (int)Constants.Error.ValidationError); Assert.AreEqual(user.Error.Message, "Username already exists"); }
public void ShouldThrowExceptionWhenGetUsersWithNoIdentityIdFails() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Throws(new Exception()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var result = Assert.Throws<BlogException>(() => _usersLogic.GetUsersWithNoIdentityId()); Assert.IsInstanceOf(typeof(BlogException), result); }
public void ShouldThrowExceptionWhenAddUserFails() { var request = new Common.Contracts.User { UserName = "******", IdentityId = "fooBar12345!", FirstName = "foo", LastName = "bar", EmailAddress = "*****@*****.**", BirthDate = DateTime.Now }; _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Add(It.IsAny<User>())) .Throws(new Exception()); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), false)) .Returns(new List<User>()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); Assert.Throws<BlogException>(() => _usersLogic.Add(request)); }
public void ShouldSearchUsers() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.SearchUsers(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var users = _usersLogic.SearchUsers("foo", 5, 5); Assert.NotNull(users); Assert.IsInstanceOf(typeof(List<Common.Contracts.User>), users); }
public void ShouldGetUserByUsername() { const string username = "******"; var educations = _educations.Where(a => a.UserId == 1).ToList(); _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _addressRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Address, bool>>>(), false)) .Returns(_addresses); _educationRepository = new Mock<IEducationRepository>(); _educationRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Education, bool>>>(), true)) .Returns(educations); _mediaRepository = new Mock<IMediaRepository>(); _mediaRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Media, bool>>>(), null, string.Empty)) .Returns(_mediae); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.GetByUserName(username); Assert.NotNull(user); Assert.NotNull(user.Address); Assert.NotNull(user.Education); Assert.NotNull(user.Hobbies); Assert.NotNull(user.Picture); Assert.NotNull(user.Background); Assert.AreEqual(user.UserName, username); }
public void ShouldGetUsersWithNoIdentityIdSuccessfully() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var users = _usersLogic.GetUsersWithNoIdentityId(); Assert.NotNull(users); Assert.IsInstanceOf(typeof(List<Common.Contracts.User>), users); }
public void ShouldErrorWhenAddUserHasInvalidEmail() { var request = new Common.Contracts.User { UserName = "******", IdentityId = "bar", FirstName = "foo", LastName = "bar", EmailAddress = "test", BirthDate = DateTime.Now }; _userRepository = new Mock<IUserRepository>(); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.Add(request); Assert.NotNull(user.Error); Assert.AreEqual(user.Error.Id, (int)Constants.Error.ValidationError); Assert.AreEqual(user.Error.Message, "Invalid email address"); }
public void ShouldGetUsersByCommunitySuccessfully() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.GetUsersByCommunity(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var users = _usersLogic.GetUsersByCommunity(1, 5, 10); Assert.NotNull(users); Assert.IsInstanceOf(typeof(List<Common.Contracts.User>), users); }
public void ShouldThrowExceptionWhenGetUserByUsernameFails() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Throws(new Exception()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); Assert.Throws<BlogException>(() => _usersLogic.GetByUserName("foo")); }
public void ShouldGetUserByIdentityId() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Returns(_users); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.GetByIdentity("lorem-ipsum-dolor-sit-amet"); Assert.NotNull(user); Assert.IsNull(user.Error); Assert.IsInstanceOf(typeof(Common.Contracts.User), user); }
public void ShouldUpdateUser() { var request = new Common.Contracts.User { UserName = "******", IdentityId = "fooBar12345!", FirstName = "foo", LastName = "bar", EmailAddress = "*****@*****.**", BirthDate = DateTime.Now }; var result = new User { UserName = "******", IdentityId = "fooBar12345!", FirstName = "foo", LastName = "bar", EmailAddress = "*****@*****.**", BirthDate = DateTime.Now }; _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Edit(It.IsAny<User>())) .Returns(result); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.Update(request); Assert.NotNull(user); Assert.IsNull(user.Error); }
public void ShouldGetEmptyEducationListWhenGetUserHasNoId() { const int userId = 1; var educations = _educations.Where(a => a.UserId == userId).ToList(); var dbUser = _users.Where(a => a.UserId == 1).ToList(); dbUser[0].UserId = 0; _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Returns(dbUser); _addressRepository = new Mock<IAddressRepository>(); _addressRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Address, bool>>>(), false)) .Returns(_addresses); _educationRepository = new Mock<IEducationRepository>(); _educationRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Education, bool>>>(), true)) .Returns(educations); _mediaRepository = new Mock<IMediaRepository>(); _mediaRepository.Setup(a => a.Find(It.IsAny<Expression<Func<Media, bool>>>(), null, string.Empty)) .Returns(_mediae); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.Get(userId); Assert.NotNull(user); Assert.NotNull(user.Address); Assert.NotNull(user.Education); Assert.AreEqual(0, user.Education.Count); }
public void ShouldThrowExceptionWhenSearchUsersFails() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.SearchUsers(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Throws(new Exception("")); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var result = Assert.Throws<BlogException>(() => _usersLogic.SearchUsers("foo", 5, 5)); Assert.IsInstanceOf(typeof(BlogException), result); }
public void ShouldErrorWhenGetUserByUsernameHasNoResult() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.Find(It.IsAny<Expression<Func<User, bool>>>(), It.IsAny<Func<IQueryable<User>, IOrderedQueryable<User>>>(), It.IsAny<string>())) .Returns(new List<User>()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var user = _usersLogic.GetByUserName("foo"); Assert.IsNotNull(user.Error); Assert.AreEqual(user.Error.Id, (int)Constants.Error.RecordNotFound); }
public void ShouldThrowExceptionWhenGetUsersByCommunityFails() { _userRepository = new Mock<IUserRepository>(); _userRepository.Setup(a => a.GetUsersByCommunity(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Throws(new Exception()); _addressRepository = new Mock<IAddressRepository>(); _educationRepository = new Mock<IEducationRepository>(); _mediaRepository = new Mock<IMediaRepository>(); _usersLogic = new UsersLogic(_userRepository.Object, _addressRepository.Object, _educationRepository.Object, _mediaRepository.Object); var users = Assert.Throws<BlogException>(() => _usersLogic.GetUsersByCommunity(1, 5, 10)); Assert.IsInstanceOf(typeof(BlogException), users); }