public ActionResult UpdateStatus(int userId) { UserDataStore Obj = new UserDataStore(); Obj.UpdateUserStatus(userId); return(RedirectToAction("ShowUserList")); }
public ActionResult ShowCountryList() { UserDataStore Obj = new UserDataStore(); List <SA_Country> CountryList = _context.SA_Country.ToList(); return(View("country-list", CountryList)); }
public ActionResult EditUser(int id) { ChemAnalystContext _context = new ChemAnalystContext(); UserDataStore Obj = new UserDataStore(); SA_User obj = Obj.GetUserByid(id); SA_UserViewModel Objuser = new SA_UserViewModel(); Objuser.id = obj.id; Objuser.Fname = obj.Fname; Objuser.Lname = obj.Lname; Objuser.Phone = obj.Phone; Objuser.ProfileImage = obj.ProfileImage; Objuser.Role = obj.Role; Objuser.Email = obj.Email; Objuser.UserPassword = obj.UserPassword; Objuser.Gender = obj.Gender; var customerData = (from User in _context.SA_Role // select { Fname = User.Fname+" "+User.Lname , Phone = User.Phone, Role=User.Role,Email=User.Email,UserPassword=User.Password}); select new SelectListItem { Text = User.Role, Value = User.Role }).ToList(); Objuser.UserRoleList = customerData; return(View("add-user", Objuser)); }
public ActionResult ShowUserList() { UserDataStore Obj = new UserDataStore(); List <SA_User> UserList = Obj.GetUserList(); return(View("user-list", UserList)); }
private async void Login_OnClicked(object sender, EventArgs e) { UserDataStore uds = new UserDataStore(); User user = await uds.GetItemAsync(loginViewModel.Username); if (user != null && user.UserName.Length > 0) { if (loginViewModel.Password.Equals(user.Password)) { loginViewModel.LoggedOnUser = user.UserName + " you are now logged in."; loginViewModel.Username = ""; loginViewModel.Password = ""; props.SetPropertyValue("UserLoggedInUser", user.UserName); start_btn.IsVisible = true; await Navigation.PushAsync(new MainPage()); } else { await App.Current.MainPage.DisplayAlert("Wrong Credentials", "Please Enter again", "OK"); loginViewModel.LoggedOnUser = ""; props.SetPropertyValue("UserLoggedInUser", ""); start_btn.IsVisible = false; } } }
public ActionResult Register(RegisterDto registerDto) { if (!ModelState.IsValid) { return(View(registerDto)); } if (registerDto.RepeatedPassword != registerDto.Password) { ModelState.AddModelError(nameof(registerDto.Password), "Пароли не совпадают"); ModelState.AddModelError(nameof(registerDto.RepeatedPassword), "Пароли не совпадают"); return(View(registerDto)); } var existedUser = UserDataStore.GetAll() .SingleOrDefault(user => user.Login == registerDto.Login && user.PasswordHash == string.Empty); if (existedUser == null) { ModelState.AddModelError(nameof(registerDto.Login), "Данный логин недоступен, обратитесь к администратору"); return(View(registerDto)); } existedUser.PasswordHash = PasswordHashService.GetHash(registerDto.Password); UserDataStore.Update(existedUser); return(RedirectToAction("Index")); }
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (var transaction = new TransactionScope(mConfiguration)) { var usersInRolesStore = new UserInRoleDataStore(transaction); foreach (string userName in usernames) { foreach (string roleName in roleNames) { var rDS = new RoleDataStore(transaction); Role role = rDS.FindByName(mApplicationName, roleName); var uDS = new UserDataStore(transaction); User user = uDS.FindByName(mApplicationName, userName); UserInRole userInRole = usersInRolesStore.Find(ApplicationName, user, role); if (userInRole == null) { throw new UserInRoleNotFoundException(userName, roleName); } userInRole.Deleted = true; usersInRolesStore.Update(userInRole); } } transaction.Commit(); } }
private async void CalculateEXP() { //Personal Experience var user1 = await UserDataStore.GetItemsAsync(true); foreach (var user in user1) { if (user.Name == "User1") { var result = ExperienceToLevel(user.PersonalExperience); PersonalLevel = result.Item1.ToString(); PersonalLevelEXP = result.Item2.ToString(); PersonalRemainingEXP = result.Item3.ToString(); PersonalProgressBar = result.Item4.ToString(); if (result.Item1 == 9) { Level9Image = true; Level10Image = false; } else { Level9Image = false; Level10Image = true; } var result2 = ExperienceToLevel(user.PartyExperience); PartyLevel = result2.Item1.ToString(); PartyLevelEXP = result2.Item2.ToString(); PartyRemainingEXP = result2.Item3.ToString(); PartyProgressBar = result2.Item4.ToString(); } } }
private async void SaveFavorite_Clicked(object sender, EventArgs e) { using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Učitavanje..")) { string SelectedAdId = ((Button)sender).BindingContext as string; var currentUserCached = (FirebaseUser)JsonConvert.DeserializeObject(Preferences.Get("FirebaseUser", ""), typeof(FirebaseUser)); var allUsers = await UserDataStore.GetItemsAsync(false); var currentUserFirebase = allUsers.Where(u => u.Email == currentUserCached.Email).FirstOrDefault(); if (currentUserFirebase != null) { UserFavoriteAd favoriteAd = new UserFavoriteAd { Username = currentUserFirebase.Username, AdId = SelectedAdId }; var allUserFavorites = await UserFavoriteAdsDataStore.GetItemsAsync(false); var alreadyExists = allUserFavorites.Where(f => f.AdId == favoriteAd.AdId && f.Username == favoriteAd.Username).ToList(); if (alreadyExists.Count() > 0) { await XF.Material.Forms.UI.Dialogs.MaterialDialog.Instance.AlertAsync(message : "Oglas je već bio spremljen!"); } else { await UserFavoriteAdsDataStore.AddItemAsync(favoriteAd); await XF.Material.Forms.UI.Dialogs.MaterialDialog.Instance.AlertAsync(message : "Uspješno ste spremili oglas!"); } } } }
async Task ExecuteLoadUsersCommand() { if (IsBusy) { return; } IsBusy = true; try { Users.Clear(); var users = await UserDataStore.GetUsersAsync(true); foreach (var user in users) { Users.Add(user); } } catch (Exception ex) { Debug.WriteLine(ex); } finally { IsBusy = false; } }
public async void DisplayResult() { var user = await UserDataStore.GetItemAsync("User1"); HatResult = user.HatColour; DisplayDescription(); }
/// <summary> /// /// </summary> /// <param name="userName"></param> /// <param name="isAssigned">A site can be not assigned to a user, but still exists as a record, /// this flag can suppress those that are not assigned.</param> /// <returns></returns> public override IList <Site> GetSitesByUser(string userName, bool isAssigned) { using (var transaction = new TransactionScope(_configuration)) { // Find all the Persons who match the MembershipUser id of 'username'. var userDs = new UserDataStore(transaction); User user = userDs.FindByName(_applicationName, userName); // Then, find all the sites via PersonSite that match the personIds. IList <Site> runningList = new List <Site>(); var ppDs = new PersonSiteDataStore(transaction); if (user.Person != null) { IList <PersonSite> pps = ppDs.FindSitesByPerson(user.Person.Id, isAssigned); foreach (PersonSite pSite in pps) { IEnumerable <Site> q = from x in runningList where x.Id.Equals(pSite.Site.Id) select x; if (!q.Any()) { runningList.Add(pSite.Site); } } return(runningList); } } return(new List <Site>()); }
public async void OnAppearing() { if (!isLoaded) { //Get all groups to check for data where user exists var users = await UserDataStore.GetItemsAsync(); foreach (var user in users) { if (user.Name == "User1") { if (user.HatColour == null) { await App.Current.MainPage.DisplayAlert("You're not in a party yet!", "Complete the Quest to join a party first.", "Continue"); //await Shell.Current.Navigation.PopToRootAsync().ConfigureAwait(true); //await Shell.Current.GoToAsync($"{nameof(HatQuiz)}"); // If user is not in group go to HatQuiz break; } else { FillUserData(); break; } } } } }
public ActionResult UpdatePassword(FormCollection ChangePassword) { int LoginUser = int.Parse(ChangePassword["LoginUser"]); string CurPassword = ChangePassword["CurPassword"]; string newPassword = ChangePassword["newPassword"]; string confirmpasswd = ChangePassword["confirmpasswd"]; UserDataStore ObjUser = new UserDataStore(); SA_User loginUser = ObjUser.GetUserByid(LoginUser); if ((loginUser != null)) { if (loginUser.UserPassword == CurPassword) { loginUser.id = LoginUser; loginUser.UserPassword = newPassword; int valid = ObjUser.UpdatePassword(loginUser); if (valid > 0) { ViewBag.Message = "Password Updated Successfuly."; } else { ViewBag.Message = "Password not Updated Successfuly."; } } else { ViewBag.Message = "Your current Password is not matched."; } } return(View("changePassword")); }
public ActionResult SaveProfile(SA_User User) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/images"), fileName); file.SaveAs(path); User.ProfileImage = fileName; } } UserDataStore Obj = new UserDataStore(); Obj.UpdateUser(User); if ((User.Role).ToUpper() != "ADMIN") { return(View("UserView")); } return(RedirectToAction("ShowUserList", "Admin")); }
public async void OnQuizSubmitBlack(object obj) { var user1 = await UserDataStore.GetItemAsync("User1"); QuestsCompleted1 = user1.QuestsCompleted; PersonalExperience1 = user1.PersonalExperience; User newUser = new User() { Name = "User1", Username = "******", Password = null, PersonalExperience = PersonalExperience1 + 500, PartyExperience = 2100, HatColour = "Black", // This needs to be updated when hat quiz is completed //statistics QuestionsAnswered = 13, QuestsCompleted = QuestsCompleted1, //trophygained Trophy5Gained = true, Trophy6Gained = false, Trophy7Gained = false, Trophy8Gained = false, Trophy9Gained = false, }; await UserDataStore.UpdateItemAsync(newUser); await Shell.Current.GoToAsync($"{nameof(HatQuizResult)}"); }
async Task ExecuteLoadItemsCommand() { if (IsBusy) { return; } IsBusy = true; try { Users.Clear(); var items = await UserDataStore.GetItemsAsync(true); Users.ReplaceRange(items); } catch (Exception ex) { Debug.WriteLine(ex); MessagingCenter.Send(new MessagingCenterAlert { Title = "Error", Message = "Unable to load items.", Cancel = "OK" }, "message"); } finally { IsBusy = false; } }
public override bool IsUserInPersonType(string userName, string personTypeId) { using (var transaction = new TransactionScope(_configuration)) { var pptDS = new PersonPersonTypeDataStore(transaction); IList <PersonPersonType> peoples = pptDS.FindPersonByPersonType(personTypeId); // Find the person who corresponds to username. var uDS = new UserDataStore(transaction); User user = uDS.FindByName(_applicationName, userName); // If there is no matching person, then do not continue. if (user.Person == null) { throw new PersonNotFoundException(user.Name); } IEnumerable <PersonPersonType> q = from x in peoples where x.Person.Id.Equals(user.Person.Id) select x; if (q.Count() > 0) { return(true); } else { return(false); } } }
protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage Request, CancellationToken CancelToken) { Guid SessionToken = GetSessionToken(Request); if (!SessionToken.Equals(Guid.Empty)) { UserDataStore Users = new UserDataStore(); IUser FoundUser = (await Users.Get("SessionToken", SessionToken)).FirstOrDefault(); if (null != FoundUser) { if (DateTime.UtcNow < FoundUser.SessionExpires) { Thread.CurrentPrincipal = new GenericPrincipal(new DevSpaceIdentity(FoundUser), null); Request.GetRequestContext().Principal = Thread.CurrentPrincipal; } else { // We previously sent expired tokens back with a 401. // This was causing errors with password retreval. // So, just don't validate an expired token and let // the Authorize attributes handle the 401 return(await base.SendAsync(Request, CancelToken)); } } HttpResponseMessage Response = await base.SendAsync(Request, CancelToken); await Users.UpdateSession((Thread.CurrentPrincipal.Identity as DevSpaceIdentity).Identity); return(Response); } return(await base.SendAsync(Request, CancelToken)); }
public override IList <PersonType> GetPersonTypesByUser(string userName) { using (var transaction = new TransactionScope(_configuration)) { // Find all the Persons who match the MembershipUser id of 'username'. var userDS = new UserDataStore(transaction); User user = userDS.FindByName(_applicationName, userName); // If there is no matching person, then do not continue. if (user.Person == null) { throw new PersonNotFoundException(user.Name); } // Then, find all the PersonTypes via PersonPersonType that match the personIds. IList <PersonType> runningList = new List <PersonType>(); var ppDS = new PersonPersonTypeDataStore(transaction); IList <PersonPersonType> pps = ppDS.FindPersonTypesByPerson(user.Person.Id); foreach (PersonPersonType ppt in pps) { IEnumerable <PersonType> q = from x in runningList where x.Id.Equals(ppt.PersonType.Id) select x; if (q.Count() == 0) { runningList.Add(ppt.PersonType); } } return(runningList); } }
public LoginViewModel() { LoginCommand = new Command(OnLogin); SignUpCommand = new Command(SignUpClicked); Items = UserDataStore.GetItemsAsync(true).Result.ToList(); Counties = SettingsDataStore.GetItemsAsync(true).Result.ToList(); InvalidLoginIsVisible = false; }
async void LoadList() { _users = (await UserDataStore.GetItemsAsync(true)).Where(c => !c.Name.Equals("Storage")).ToList(); _ingredientCounts = (await IngredientCountDataStore.GetItemsAsync(true)) .OrderBy(c => DateTime.Parse(c.Date)).ToList(); _ingredients = (await IngredientDataStore.GetItemsAsync(true)).ToList(); _records = (await RecordDataStore.GetItemsAsync(true)).ToList(); _avtomats = (await AvtomatDataStore.GetItemsAsync(true)).ToList(); _userAvtomats = (await UserAvtomatDataStore.GetItemsAsync(true)).ToList(); }
public App() { ApiHelper = new ApiService(); UserDataStore = new UserDataStore(); JobsDataStore = new JobsDataStore(); InitializeComponent(); MainPage = new MainPage(); }
private async void NewProfilePicture_Clicked(object sender, EventArgs e) { try { var pickResult = await FilePicker.PickAsync(new PickOptions { FileTypes = FilePickerFileType.Images, PickerTitle = "Odaberite sliku profila" }); if (pickResult != null) { bool success = false; using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Pričekajte..")) { var imageStream = await pickResult.OpenReadAsync(); var firebaseStorage = new FirebaseStorage("automat-29cec.appspot.com"); var nazivSlike = Guid.NewGuid().ToString(); var task = await firebaseStorage .Child("data") .Child(nazivSlike + ".png") .PutAsync(imageStream); var urlSlike = await firebaseStorage .Child("data") .Child(nazivSlike + ".png") .GetDownloadUrlAsync(); FirebaseUserViewModel.FirebaseUser.PicturePath = urlSlike; success = await UserDataStore.UpdateItemAsync(FirebaseUserViewModel.FirebaseUser); }; if (success) { await App.Current.MainPage.DisplayAlert("Informacija", $"Uspješno ste promjenili profilnu sliku", "OK"); Preferences.Clear(); Preferences.Set("FirebaseUser", JsonConvert.SerializeObject(FirebaseUserViewModel.FirebaseUser)); profilePicture.Source = FirebaseUserViewModel.FirebaseUser.PicturePath; } else { await App.Current.MainPage.DisplayAlert("Greška", $"Dogodila se pogreška pri postavljanju nove slike profila", "OK"); } } } catch (Exception ex) { System.Console.WriteLine("Exception choosing file: " + ex.ToString()); } }
public UsersViewModel() { Title = "View Users"; Users = new ObservableCollection <User> (); LoadUsersCommand = new Command(async() => ExecuteLoadUsersCommand()); MessagingCenter.Subscribe <AddUserPage, User>(this, "AddUser", (Action <AddUserPage, User>)(async(obj, user) => { var newUser = user as User; Users.Add((User)newUser); await UserDataStore.AddUserAsync((User)newUser); })); }
public User Login(LoginPassDto loginPasswordDto) { var passHash = PasswordHashService.GetHash(loginPasswordDto.Password); var user = UserDataStore.GetAll() .SingleOrDefault(u => u.Login == loginPasswordDto.Login && u.PasswordHash == passHash); if (user != null) { CreateCookie(user, loginPasswordDto.RememberMe); } return(user); }
public User GetCurrentUser() { var principal = AuthenticationService.CurrentUserPrincipal; if (!principal.Identity.IsAuthenticated) { return(null); } var login = principal.Identity.Name; return(UserDataStore.GetAll().SingleOrDefault(user => user.Login == login)); }
public ActionResult LoadUserData() { try { UserDataStore Obj = new UserDataStore(); List <SA_User> UserList = Obj.GetUserList().Where(w => w.Email != "*****@*****.**").ToList(); return(Json(new { data = UserList }, JsonRequestBehavior.AllowGet)); } catch (Exception) { throw; } }
public bool ConnectUser(string connectionId, Guid UsertoConnectId) { userConnection = new UserConnection() { Connected = true, ConnectionID = connectionId, UserId = UsertoConnectId, }; var result = UserDataStore.CreateUserConnection(userConnection); return(result); }
protected async override void OnAppearing() { UserDataStore = new UserDataStore(); var seller = await UserDataStore.GetItemAsync(Advertisement.UserId); BindingContext = AdViewModel = new AdvertismentViewModel { Advertisment = this.Advertisement, CurrentImageIndex = 0, FirebaseUser = seller }; foreach (var imageUrl in AdViewModel.Advertisment.PicturesURL) { AdViewModel.ImageSources.Add(ImageSource.FromUri(new Uri(imageUrl))); } }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { try { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { if (deleteAllRelatedData) { Roles.UserInRoleDataStore userInRoleStore = new Eucalypto.Roles.UserInRoleDataStore(transaction); IList<Roles.UserInRole> userInRoles = userInRoleStore.FindForUser(ApplicationName, username); foreach (Roles.UserInRole ur in userInRoles) userInRoleStore.Delete(ur.Id); } UserDataStore dataStore = new UserDataStore(transaction); User user = dataStore.FindByName(ApplicationName, username); if (user == null) throw new UserNotFoundException(username); dataStore.Delete(user.Id); transaction.Commit(); } return true; } catch (Exception ex) { LogException(ex, "DeleteUser"); return false; } }
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { try { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User user = dataStore.FindByName(ApplicationName, username); if (user == null) throw new UserNotFoundException(username); if (user.CheckPassword(password) == false) throw new UserNotFoundException(username); user.ChangePasswordQuestionAnswer(newPasswordQuestion, newPasswordAnswer); transaction.Commit(); } return true; } catch (Exception ex) { LogException(ex, "ChangePasswordQuestionAndAnswer"); return false; } }
public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { System.Web.Security.MembershipUserCollection membershipUsers = new MembershipUserCollection(); using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); PagingInfo paging = new PagingInfo(pageSize, pageIndex); IList<User> users = dataStore.FindAll(ApplicationName, paging); totalRecords = (int)paging.RowCount; foreach (User u in users) membershipUsers.Add(UserToMembershipUser(u)); } return membershipUsers; }
/// <summary> /// /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="email"></param> /// <param name="passwordQuestion"></param> /// <param name="passwordAnswer"></param> /// <param name="isApproved"></param> /// <param name="providerUserKey">Not used</param> /// <param name="status"></param> /// <returns></returns> public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status) { try { //Validate password ValidatePassword(username, password, true); using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); //Check name if (dataStore.FindByName(ApplicationName, username) != null) { status = MembershipCreateStatus.DuplicateUserName; return null; } //Check email if (RequiresUniqueEmail) { if (email == null || email.Length == 0) { status = MembershipCreateStatus.InvalidEmail; return null; } if (dataStore.FindByEmail(ApplicationName, email).Count > 0) { status = MembershipCreateStatus.DuplicateEmail; return null; } } User user = new User(ApplicationName, username); user.EMail = email; user.ChangePassword(password); user.ChangePasswordQuestionAnswer(passwordQuestion, passwordAnswer); user.Enabled = isApproved; dataStore.Insert(user); transaction.Commit(); status = MembershipCreateStatus.Success; return UserToMembershipUser(user); } } catch (CodeInvalidCharsException ex) //this exception is caused by an invalid user Name { LogException(ex, "CreateUser"); status = MembershipCreateStatus.InvalidUserName; return null; } catch (MembershipPasswordException ex) { LogException(ex, "CreateUser"); status = MembershipCreateStatus.InvalidPassword; return null; } catch (Exception ex) { LogException(ex, "CreateUser"); status = MembershipCreateStatus.ProviderError; return null; } }
public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline) { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User user = dataStore.FindByKey((string)providerUserKey); if (user == null) return null; if (userIsOnline) user.LastActivityDate = DateTime.Now; transaction.Commit(); return UserToMembershipUser(user); } }
public override int GetNumberOfUsersOnline() { TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); return dataStore.NumbersOfLoggedInUsers(ApplicationName, onlineSpan); } }
public override string GetUserNameByEmail(string email) { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); IList<User> users = dataStore.FindByEmail(ApplicationName, email); if (users.Count == 0) return null; return users[0].Name; } }
public override bool ValidateUser(string username, string password) { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User dbUser = dataStore.FindByName(ApplicationName, username); if (dbUser == null) return false; //throw new UserNotFoundException(username); bool valid = dbUser.Login(password, PasswordAttemptWindow, MaxInvalidPasswordAttempts); transaction.Commit(); return valid; } }
public override void UpdateUser(System.Web.Security.MembershipUser user) { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User dbUser = dataStore.FindByName(ApplicationName, user.UserName); if (dbUser == null) throw new UserNotFoundException(user.UserName); //Check email if (RequiresUniqueEmail) { if (user.Email == null || user.Email.Length == 0) { throw new EMailNotValidException(user.Email); } IList<User> emailUsers = dataStore.FindByEmail(ApplicationName, user.Email); if (emailUsers.Count > 0 && emailUsers[0].Id != dbUser.Id) { throw new EMailDuplucatedException(user.Email); } } dbUser.Comment = user.Comment; dbUser.EMail = user.Email; dbUser.Enabled = user.IsApproved; transaction.Commit(); } }
public override bool UnlockUser(string userName) { using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User user = dataStore.FindByName(ApplicationName, userName); if (user == null) throw new UserNotFoundException(userName); user.Unlock(); transaction.Commit(); } return true; }
public override string ResetPassword(string username, string answer) { if (!EnablePasswordReset) { throw new NotSupportedException(); } using (TransactionScope transaction = new TransactionScope(mConfiguration)) { UserDataStore dataStore = new UserDataStore(transaction); User user = dataStore.FindByName(ApplicationName, username); if (user == null) throw new UserNotFoundException(username); if (RequiresQuestionAndAnswer && user.ValidatePasswordAnswer(answer, PasswordAttemptWindow, MaxInvalidPasswordAttempts) == false) { transaction.Commit(); throw new MembershipPasswordException(); } else { string newPassword = System.Web.Security.Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); user.ChangePassword(newPassword); transaction.Commit(); return newPassword; } } }