public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { if (string.IsNullOrEmpty(roleName)) { return false; } using (StudentContext Context = new StudentContext()) { Role Role = null; Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName); if (Role == null) { return false; } if (throwOnPopulatedRole) { if (Role.Users.Any()) { return false; } } else { Role.Users.Clear(); } Context.Roles.Remove(Role); Context.SaveChanges(); return true; } }
public void AddClasses() { var context = new StudentContext(); context.Classes.Add(new Class { Name = "Grade One" }); context.SaveChanges(); Assert.AreEqual(1, context.Classes.Count()); }
public void DeleteClasses() { var context = new StudentContext(); context.Classes.Remove(context.Classes.FirstOrDefault(p => p.Id == 1)); context.SaveChanges(); Assert.AreEqual(0, context.Classes.Count()); }
public MainWindowViewModel( StudentContext studentContext, ParameterContext adminContext, ObservableCollection<CollegeLife> collegeLife, ObservableCollection<DegreeProgram> degreePrograms, ObservableCollection<Term> terms) { if(studentContext == null) { throw new ArgumentNullException("studentContext"); } if(adminContext == null) { throw new ArgumentNullException("adminContext"); } if(collegeLife == null) { throw new ArgumentNullException("collegeLife"); } if(degreePrograms == null) { throw new ArgumentNullException("degreePrograms"); } if(terms == null) { throw new ArgumentNullException("terms"); } Students = studentContext; Parameters = adminContext; CollegeLife = collegeLife; DegreePrograms = degreePrograms; Terms = terms; ObservableCollection<StudentViewModel> students = new ObservableCollection<StudentViewModel>(); foreach(Student student in studentContext.Items) { students.Add(new StudentViewModel(student, studentContext)); } ObservableCollection<ParameterViewModel> parameters = new ObservableCollection<ParameterViewModel>(); foreach(Parameter parameter in adminContext.Items) { parameters.Add(new ParameterViewModel(parameter, adminContext)); } InquiryWorkspace = new InquiryWorkspaceViewModel(studentContext, collegeLife, degreePrograms, terms); StudentWorkspace = new StudentWorkspaceViewModel(students, studentContext); AdminWorkspace = new AdminWorkspaceViewModel(parameters, adminContext, terms); ApprovalsWorkspace = new StudentApprovalsViewModel(degreePrograms, students.ToList<StudentViewModel>(), terms); SaveCommand = new DelegateCommand(o => Save()); }
public void UpdateStudents() { var context = new StudentContext(); var students = context.Students.FirstOrDefault(p => p.Id == 1); if (students != null) students.Name = "tom"; context.SaveChanges(); if (students != null) StringAssert.AreEqualIgnoringCase(students.Name, "tom"); }
public void UpdateClasses() { var context = new StudentContext(); var classes = context.Classes.FirstOrDefault(p => p.Id == 1); if (classes != null) classes.Name = "中班"; context.SaveChanges(); if (classes != null) StringAssert.AreEqualIgnoringCase(classes.Name, "中班"); }
public void AddStudents() { var context = new StudentContext(); var cl = context.Classes.FirstOrDefault(p => p.Id == 1); var student = new Student() { Name = "Tom", Class = cl }; context.SaveChanges(); Assert.AreEqual(1, context.Students.Count()); }
public StudentViewModel(Student student, StudentContext context) { if(student == null) { throw new ArgumentNullException("student"); } if(context == null) { throw new ArgumentNullException("context"); } this.Context = context; this.student = student; }
public static StudentPoco GetStudentPoco(string id) { Mapper.CreateMap<Student, StudentPoco>(); var context = new StudentContext(); var student = context.Students.Find(id); if (student == null) throw new Exception("Student not found..."); var result = Mapper.Map<Student, StudentPoco>(student); return result; }
public ActionResult EditStudent([Bind(Include = "ID, StudentName, Email, Address")] Student student) { if (ModelState.IsValid) { using (var ctx = new StudentContext()) { ctx.Entry(student).State = EntityState.Modified; ctx.SaveChanges(); return(Json(new { data = student, message = "success" })); } } else { return(Json(new { data = student, message = "Something went wrong, please try again" })); } }
public async Task <JsonResult> AddStudent([Bind(Include = "StudentName, Email, Address")] Student student) { try { using (var ctx = new StudentContext()) { ctx.Students.Add(student); await ctx.SaveChangesAsync(); return(Json(new { message = "Success" })); } } catch (Exception ex) { return(Json(new { message = ex.Message })); } }
private void UpdateJournalProgress(object sender, EventArgs e) { var journalProgressService = new JournalProgressService(_unit, _unit); var discipline = (Discipline)addLBox.SelectedItem; var journalProgress = Progress.JournalProgresses.ToList().Find(t => t.JournalCurriculum.Discipline == discipline); var appraisalFormReports = (AppraisalFormReport)cmBox_AppraisalFormReport.SelectedItem; journalProgress.AppraisalFormReport = appraisalFormReports; journalProgressService.UpdateJournalProgress(journalProgress); _unit.Commit(); _context.Dispose(); _context = new StudentContext(Resources.ConnectionString); _unit = new UnitOfWork(_context); GetAllDataFromDb(); }
public ActionResult ResetPassword(string id) { using (StudentContext studentContext = new StudentContext()) { var student = studentContext.students.Where(s => s.ResetPasswordCode == id).FirstOrDefault(); if (student != null) { ResetPasswordModel model = new ResetPasswordModel(); model.RestCode = id; return(View(model)); } else { return(HttpNotFound()); } } }
public List <BorrowList> DeSerializeBorrowListFromXml() { using (StudentContext db = new StudentContext()) { Type[] _types = new Type[] { typeof(Student) }; List <BorrowList> _studentList = new List <BorrowList>(); XmlSerializer reader = new XmlSerializer(_studentList.GetType(), _types); String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//SerializationBorrowList.xml"; System.IO.StreamReader file = new System.IO.StreamReader(path); _studentList = (List <BorrowList>)reader.Deserialize(file); file.Close(); return(_studentList); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); //read database //get count //set count SDP_MVC5.Models.StudentContext db = new StudentContext(); switch (result) { case SignInStatus.Success: { int studentID = int.Parse(model.Email.ToString().Substring(0, 8)); int ReminderCount = db.Reminder.Where(x => x.studentID == studentID && x.remindertime <= DateTime.Today).Count(); if (ReminderCount == 0) { Session.Abandon(); } else { Session["reminders"] = ReminderCount; } return(RedirectToLocal(returnUrl)); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public ActionResult Registration(T_Student model) { StudentContext eb = new StudentContext(); if (eb.T_Student.Any(x => x.UserName == model.UserName)) { TempData["Success"] = "UserName Already Available!"; return(View()); } model.RoleId = 2;//bydefault selected as student model.IsAdmin = false; model.IsTeacher = false; eb.T_Student.Add(model); eb.SaveChanges(); TempData["Success"] = "Added Successfully!"; return(View()); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); ObservableCollection<CollegeLife> collegeLife; ObservableCollection<DegreeProgram> degreePrograms; ObservableCollection<Term> terms; try { //connect with mysql database Database.ConnectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString; Students = new StudentContext( from DataRow row in Database.Query("SELECT * FROM ais.tblstudent").Rows select new Student(row)); Parameters = new ParameterContext( from DataRow row in Database.Query("SELECT * FROM ais.tblparameter").Rows select new Parameter(row)); collegeLife = new ObservableCollection<CollegeLife>( from DataRow row in Database.Proc("getPersonalInterest").Rows select new CollegeLife(row)); degreePrograms = new ObservableCollection<DegreeProgram>( from DataRow row in Database.Proc("getDegreePrograms").Rows select new DegreeProgram(row)); terms = new ObservableCollection<Term>( from DataRow row in Database.Proc("getTerm").Rows select new Term(row)); } catch { Students = ModelGenerator.BuildFakeStudents(); Parameters = ModelGenerator.BuildFakeParameters(); collegeLife = ModelGenerator.BuildFakeCollegeLife(); degreePrograms = ModelGenerator.BuildFakeDegreePrograms(); terms = null; } MainWindowViewModel model = new MainWindowViewModel(Students, Parameters, collegeLife, degreePrograms, terms); MainWindow window = new MainWindow { DataContext = model }; window.Show(); }
public override string ResetPassword(string username, string answer) { string pass = string.Empty; using (StudentContext Context = new StudentContext()) { var currentUser = Context.Users.Where(u => u.Username == username).SingleOrDefault(); Random rdm = new Random(9978787); pass = rdm.Next().ToString(); string hashedPass = Crypto.HashPassword(pass); currentUser.Password = hashedPass; currentUser.ConfirmPassword = hashedPass; Context.SaveChanges(); } return(pass); }
//[ValidateAntiForgeryToken] public ActionResult Create(Student student) { try { using (var db = new StudentContext()) { student.registration_date = DateTime.Now; db.Student.Add(student); db.SaveChanges(); return(RedirectToAction("Index")); } } catch (Exception e) { ModelState.AddModelError("Error al ingresar el alumno", e); return(View()); } }
public int Total() { int total = 0; try { using (var db = new StudentContext()) { total = db.Students.Count(); } } catch (Exception ex) { Console.WriteLine($"Failed to get total record of students [{ex.Message}]"); } return(total); }
public ActionResult StudentPage() { if (Session["Email"] != null) { ViewBag.FirstName = Session["FirstName"]; StudentContext studentContext = new StudentContext(); string email = (string)Session["Email"]; Student student = studentContext.Students.Single(e => e.Email.Equals(email)); RotationListContext rotationListContext = new RotationListContext(); List <RotationList> rotationsList = rotationListContext.RotationList.Where(e => e.StudentId == student.ID).ToList(); return(View(rotationsList)); } return(RedirectToAction("Index", "Home")); }
public bool Update(Student itm) { try { using (var db = new StudentContext()) { db.Students.Update(itm); db.SaveChanges(); } } catch (Exception ex) { Console.WriteLine($"Failed to update student ({itm.Id}) [{ex.Message}]"); return(false); } return(true); }
public async Task <int> AddNewStudent(StudentModel model) { var student = new Student() { Name = model.Name, Group = model.Group, Roll = model.Roll, ProfilePicUri = model.ProfilePicUri }; using (var db = new StudentContext(this.optionsBuilder.Options)) { await db.StudentInfo.AddAsync(student); await db.SaveChangesAsync(); } return(student.Id); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, StudentContext studentContext) { studentContext.Database.EnsureDeleted(); studentContext.Database.EnsureCreated(); app.UseStaticFiles(); app.UseNodeModules(env.ContentRootPath); app.UseMvc(routes => { routes.MapRoute( name: "StudentRoute", template: "{controller}/{action}/{id?}", defaults: new { controller = "Student", action = "Index" }, constraints: new { id = "[0-9]+" }); }); }
public Student Get(string id) { Student student = null; try { using (var db = new StudentContext()) { Console.WriteLine($"Attempting to get student({id})"); student = db.Students.Single(s => s.Id == id); } } catch (Exception ex) { Console.WriteLine($"Failed to get student({id}) [{ex.Message}]"); } return(student); }
static void Main() { Database.SetInitializer( new MigrateDatabaseToLatestVersion<StudentContext, Configuration>()); var db = new StudentContext(); var course = new Course("c#", "New javascript web technology", new List<string> { "1", "2", "3" }); db.Courses.Add(course); var student = new Student("Venci", 9999); db.Students.Add(student); student.Courses.Add(course); var homework = new Homework() { Course = course, Content = "Good", TimeSent = DateTime.Now }; student.Homeworks.Add(homework); db.SaveChanges(); }
public StudentController(StudentContext context) { _context = context; if (_context.Students.Count() == 0) { //Add new student objects to context to be saved _context.Students.Add(new Student { FirstName = "Robert", LastName = "Searle", EmailID = "*****@*****.**", PhoneNo = "224-456-9800" }); _context.Students.Add(new Student { FirstName = "Autumn", LastName = "Ellis", EmailID = "*****@*****.**", PhoneNo = "331-845-7459" }); _context.Students.Add(new Student { FirstName = "Anna", LastName = "Searle", EmailID = "*****@*****.**", PhoneNo = "224-326-1562" }); _context.SaveChanges(); } }//end studentContoller
public static void Initialize(StudentContext context) { if (!context.Students.Any()) { context.Students.AddRange( new StudentModel { Name = "Илья", Surname = "Капралов", Motherland = "Максимович", Speciality = "Тракторостроительный факультет, он же главный магосфабрикатор", State = "Учащийся", Course = "Т-1А" } ); context.SaveChanges(); } }
protected void DeleteFiles(string subdirectory, long itemId) { StudentContext db = new StudentContext(); var attachments = db.Attachments.Where(a => a.ParentType == subdirectory && a.ItemId == itemId).ToList(); foreach (var file in attachments) { db.Attachments.Remove(file); } db.SaveChanges(); string destDirectory = Server.MapPath("~/Attachments/AttachedFiles"); destDirectory = Path.Combine(destDirectory, subdirectory, itemId.ToString()); if (Directory.Exists(destDirectory)) { Directory.Delete(destDirectory, true); } }
public ActionResult Delete(int?id) { if (Session["Email"] != null) { if (id != null) { StudentContext context = new StudentContext(); Student student = context.Students.Single(pro => pro.ID == id); return(View(student)); } else { return(RedirectToAction("Index", "StudentList")); } } return(RedirectToAction("Index", "Home")); }
//GET: /Home/Delete/id public ActionResult Delete(int ID) { StudentContext studentContext = new StudentContext(); try { if (studentContext.DeleteStudent(ID)) { ViewBag.DeleteMessage = "Student Successfully Deleted"; } return(RedirectToAction("Index")); } catch { return(View()); } }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (StudentContext Context = new StudentContext()) { List <User> Users = Context.Users.Where(Usr => usernames.Contains(Usr.Username)).ToList(); List <Role> Roles = Context.Roles.Where(Rl => roleNames.Contains(Rl.RoleName)).ToList(); foreach (User user in Users) { foreach (Role role in Roles) { if (!user.Roles.Contains(role)) { user.Roles.Add(role); } } } Context.SaveChanges(); } }
public List <Student> GetAll() { List <Student> students = null; try { using (var db = new StudentContext()) { Console.WriteLine("Attempting to get all students"); students = db.Students.ToList <Student>(); } } catch (Exception ex) { Console.WriteLine($"Failed to get all students [{ex.Message}]"); } return(students); }
public static void UpdateUploaded(Assignment assignment, out string errorMessage) { try { using (var context = new StudentContext()) { var studentObj = (from student in context.Students where student.Student_ID == assignment.Student_ID select student).FirstOrDefault(); studentObj.Uploaded = true; context.SaveChanges(); errorMessage = ""; } } catch (Exception) { errorMessage = "Database Error"; } }
public List <Faculty> GetAll() { Console.WriteLine($"Attempting to get all faculties"); List <Faculty> faculties = null; try { using (var db = new StudentContext()) { faculties = db.Faculties.ToList(); } } catch (Exception ex) { Console.WriteLine($"Failed to get all faculties [{ex.Message}]"); } return(faculties); }
[HttpGet]//Solo por Get public ActionResult Edit(int matricula) { Student student = new Student(); using (var db = new StudentContext()) { student = db.Students.FirstOrDefault(s => s.Id == matricula); } return(View(student)); //StudentViewModel studentVM = new StudentViewModel(); //using (var db = new StudentContext()) //{ // studentVM.student = db.Students.First(s => s.Id == matricula); //} //return View(studentVM); }
public List <Course> GetAll() { Console.WriteLine($"Attempting to get all courses"); List <Course> courses = null; try { using (var db = new StudentContext()) { courses = db.Courses.ToList(); } } catch (Exception ex) { Console.WriteLine($"Failed to get all courses [{ex.Message}]"); } return(courses); }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (StudentContext Context = new StudentContext()) { List<User> Users = Context.Users.Where(Usr => usernames.Contains(Usr.Username)).ToList(); List<Role> Roles = Context.Roles.Where(Rl => roleNames.Contains(Rl.RoleName)).ToList(); foreach (User user in Users) { foreach (Role role in Roles) { if (!user.Roles.Contains(role)) { user.Roles.Add(role); } } } Context.SaveChanges(); } }
public ActionResult Autherize(HomeWork_2.Models.Student studentModel) { using (StudentContext db = new StudentContext()) { var studentDetails = db.Students.Where(x => x.UserName == studentModel.UserName && x.Password == studentModel.Password).FirstOrDefault(); if (studentDetails == null) { studentModel.LoginErrorMessage = "Wrong UserName or Password."; return(View("Index", studentModel)); } else { Session["StudentID"] = studentDetails.StudentID; Session["UserName"] = studentDetails.UserName; return(RedirectToAction("Index", "Home")); } } }
public bool AddOrUpdateSubject(Subject subject, int ClassID = 0) { bool returnValue = false; using (var db = new StudentContext()) { db.Entry(subject).State = subject.SubjectID == 0 ? EntityState.Added : EntityState.Modified; if (db.Entry(subject).State == EntityState.Added) { SubjectClassMapping subjectClassMapping = new SubjectClassMapping() { ClassID = ClassID, SubjectID = subject.SubjectID }; db.Entry(subjectClassMapping).State = subjectClassMapping.ID == 0 ? EntityState.Added : EntityState.Modified; } returnValue = db.SaveChanges() > 0; } return(returnValue); }
public override bool UnlockUser(string userName) { using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == userName); if (User != null) { User.IsLockedOut = false; User.PasswordFailuresSinceLastSuccess = 0; Context.SaveChanges(); return(true); } else { return(false); } } }
public override string[] GetUsersInRole(string roleName) { if (string.IsNullOrEmpty(roleName)) { return(null); } using (StudentContext Context = new StudentContext()) { Role Role = null; Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName); if (Role != null) { return(Role.Users.Select(Usr => Usr.Username).ToArray()); } else { return(null); } } }
public override void CreateRole(string roleName) { if (!string.IsNullOrEmpty(roleName)) { using (StudentContext Context = new StudentContext()) { Role Role = null; Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName); if (Role == null) { Role NewRole = new Role { RoleId = Guid.NewGuid(), RoleName = roleName }; Context.Roles.Add(NewRole); Context.SaveChanges(); } } } }
public InquiryWorkspaceViewModel( StudentContext context, ObservableCollection<CollegeLife> collegeLife, ObservableCollection<DegreeProgram> degreePrograms, ObservableCollection<Term> terms) { if(context == null) { throw new ArgumentNullException("context"); } if(collegeLife == null) { throw new ArgumentNullException("collegeLife"); } if(degreePrograms == null) { throw new ArgumentNullException("degreePrograms"); } if(terms == null) { throw new ArgumentNullException("terms"); } Terms = terms; CollegeLife = collegeLife; DegreePrograms = degreePrograms; this.context = context; SelectedTerm = 0; SelectedProgram = 0; SelectedInterest = 0; Student = new StudentViewModel(context.Create(), context); InquireCommand = new DelegateCommand(o => Inquire()); ApplyCommand = new DelegateCommand(o => Apply()); }
public StudentWorkspaceViewModel(ObservableCollection<StudentViewModel> students, StudentContext context) { if(students == null) { throw new ArgumentNullException("students"); } Students = students; Students.CollectionChanged += (s, o) => { if(o.OldItems != null && o.OldItems.Contains(CurrentStudent)) { CurrentStudent = null; } }; CurrentStudent = students.Count > 0 ? students[0] : null; Add = new DelegateCommand(o => AddStudent()); Delete = new DelegateCommand(o => DeleteStudent()); Accept = new DelegateCommand(o => AcceptStudent()); Deny = new DelegateCommand(o => DenyStudent()); this.context = context; }
public override bool UnlockUser(string userName) { using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == userName); if (User != null) { User.IsLockedOut = false; User.PasswordFailuresSinceLastSuccess = 0; Context.SaveChanges(); return true; } else { return false; } } }
public static long RegisterNewUser(string Username, string Password, string Email, bool IsApproved, string FirstName, string LastName, long organizationId, string token, DateTime? DateOfBirth = null, string Title = null) { MembershipCreateStatus CreateStatus; Membership.CreateUser(Username, Password, Email, null, null, IsApproved, Guid.NewGuid(), out CreateStatus); if (CreateStatus == MembershipCreateStatus.Success) { StudentTracker.Core.Entities.User User = null; using (StudentContext Context = new StudentContext()) { User = Context.Users.FirstOrDefault(Usr => Usr.Username == Username); User.FirstName = FirstName; User.LastName = LastName; User.ConfirmPassword = User.Password; User.OrganizationId = organizationId; User.RegistrationToken = token; Context.SaveChanges(); } if (IsApproved) { FormsAuthentication.SetAuthCookie(Username, false); } return User.UserId; } return -1; }
public string CreateAccount(User user) { if (string.IsNullOrEmpty(user.Username)) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName); } if (string.IsNullOrEmpty(user.Password)) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } if (string.IsNullOrEmpty(user.Email)) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidEmail); } string hashedPassword = Crypto.HashPassword(user.Password); if (hashedPassword.Length > 128) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } using (StudentContext Context = new StudentContext()) { if (Context.Users.Where(Usr => Usr.Username == user.Username).Any()) { throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName); } if (Context.Users.Where(Usr => Usr.Email == user.Email).Any()) { throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail); } string token = string.Empty; token = GenerateToken(); User NewUser = new User { Username = user.Username, Password = hashedPassword, StatusId = (int)UserStatus.Pending, Email = user.Email, InsertedOn = DateTime.UtcNow, LastPasswordChangedDate = DateTime.UtcNow, PasswordFailuresSinceLastSuccess = 0, LastLoginDate = DateTime.UtcNow, LastActivityDate = DateTime.UtcNow, LastLockoutDate = DateTime.UtcNow, IsLockedOut = false, LastPasswordFailureDate = DateTime.UtcNow, ConfirmationToken = token, RegistrationToken = token, FirstName = user.FirstName, LastName = user.LastName, OrganizationId = user.OrganizationId }; NewUser.ConfirmPassword = hashedPassword; Context.Users.Add(NewUser); Context.SaveChanges(); return token; } }
public static MembershipCreateStatus Register(string Username, string Password, string Email, bool IsApproved, string FirstName, string LastName, DateTime? DateOfBirth = null, string Title = null) { MembershipCreateStatus CreateStatus; Membership.CreateUser(Username, Password, Email, null, null, IsApproved, Guid.NewGuid(), out CreateStatus); if (CreateStatus == MembershipCreateStatus.Success) { using (StudentContext Context = new StudentContext()) { StudentTracker.Core.Entities.User User = Context.Users.FirstOrDefault(Usr => Usr.Username == Username); User.FirstName = FirstName; User.LastName = LastName; User.ConfirmPassword = User.Password; // User.DateOfBirth = DateOfBirth; // User.Title = Title; Context.SaveChanges(); } if (IsApproved) { FormsAuthentication.SetAuthCookie(Username, false); } } return CreateStatus; }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { if (string.IsNullOrEmpty(username)) { return false; } using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User != null) { Context.Users.Remove(User); Context.SaveChanges(); return true; } else { return false; } } }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (string.IsNullOrEmpty(username)) { status = MembershipCreateStatus.InvalidUserName; return null; } if (string.IsNullOrEmpty(password)) { status = MembershipCreateStatus.InvalidPassword; return null; } if (string.IsNullOrEmpty(email)) { status = MembershipCreateStatus.InvalidEmail; return null; } string HashedPassword = Crypto.HashPassword(password); if (HashedPassword.Length > 128) { status = MembershipCreateStatus.InvalidPassword; return null; } using (StudentContext Context = new StudentContext()) { if (Context.Users.Where(Usr => Usr.Username == username).Any()) { status = MembershipCreateStatus.DuplicateUserName; return null; } if (Context.Users.Where(Usr => Usr.Email == email).Any()) { status = MembershipCreateStatus.DuplicateEmail; return null; } User NewUser = new User { Username = username, Password = HashedPassword, StatusId = Convert.ToInt32(UserStatus.Active), Email = email, InsertedOn = DateTime.UtcNow, LastPasswordChangedDate = DateTime.UtcNow, PasswordFailuresSinceLastSuccess = 0, LastLoginDate = DateTime.UtcNow, LastActivityDate = DateTime.UtcNow, LastLockoutDate = DateTime.UtcNow, IsLockedOut = false, LastPasswordFailureDate = DateTime.UtcNow }; NewUser.ConfirmPassword = HashedPassword; try { Context.Users.Add(NewUser); Context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } status = MembershipCreateStatus.Success; return new MembershipUser(Membership.Provider.Name, NewUser.Username, NewUser.UserId, NewUser.Email, null, null, NewUser.StatusId == 1, NewUser.IsLockedOut, NewUser.InsertedOn, NewUser.LastLoginDate.Value, NewUser.LastActivityDate.Value, NewUser.LastPasswordChangedDate.Value, NewUser.LastLockoutDate.Value); } }
public override int GetNumberOfUsersOnline() { DateTime DateActive = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(Convert.ToDouble(Membership.UserIsOnlineTimeWindow))); using (StudentContext Context = new StudentContext()) { return Context.Users.Where(Usr => Usr.LastActivityDate > DateActive).Count(); } }
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection MembershipUsers = new MembershipUserCollection(); using (StudentContext Context = new StudentContext()) { totalRecords = Context.Users.Count(); IQueryable<User> Users = Context.Users.OrderBy(Usrn => Usrn.Username).Skip(pageIndex * pageSize).Take(pageSize); foreach (User user in Users) { MembershipUsers.Add(new MembershipUser(Membership.Provider.Name, user.Username, user.UserId, user.Email, null, null, user.StatusId == (int)UserStatus.Active, user.IsLockedOut, user.InsertedOn, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value)); } } return MembershipUsers; }
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { if (providerUserKey is long) { } else { return null; } using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.Find(providerUserKey); if (User != null) { if (userIsOnline) { User.LastActivityDate = DateTime.UtcNow; Context.SaveChanges(); } return new MembershipUser(Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.StatusId == (int)UserStatus.Active, User.IsLockedOut, User.InsertedOn, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value); } else { return null; } } }
public override MembershipUser GetUser(string username, bool userIsOnline) { if (string.IsNullOrEmpty(username)) { return null; } using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User != null) { if (userIsOnline) { User.LastActivityDate = DateTime.UtcNow; User.ConfirmPassword = User.Password; Context.SaveChanges(); } return new MembershipUser(Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.StatusId == (int)UserStatus.Active, User.IsLockedOut, User.InsertedOn, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value); } else { return null; } } }
public override string GetUserNameByEmail(string email) { using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Email == email); if (User != null) { return User.Username; } else { return string.Empty; } } }
public override string ResetPassword(string username, string answer) { string pass = string.Empty; using (StudentContext Context = new StudentContext()) { var currentUser = Context.Users.Where(u => u.Username == username).SingleOrDefault(); Random rdm = new Random(9978787); pass = rdm.Next().ToString(); string hashedPass = Crypto.HashPassword(pass); currentUser.Password = hashedPass; currentUser.ConfirmPassword = hashedPass; Context.SaveChanges(); } return pass; }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (string.IsNullOrEmpty(username)) { return false; } if (string.IsNullOrEmpty(oldPassword)) { return false; } if (string.IsNullOrEmpty(newPassword)) { return false; } using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User == null) { return false; } String HashedPassword = User.Password; Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, oldPassword)); if (VerificationSucceeded) { User.PasswordFailuresSinceLastSuccess = 0; } else { int Failures = User.PasswordFailuresSinceLastSuccess; if (Failures < MaxInvalidPasswordAttempts) { User.PasswordFailuresSinceLastSuccess += 1; User.LastPasswordFailureDate = DateTime.UtcNow; } else if (Failures >= MaxInvalidPasswordAttempts) { User.LastPasswordFailureDate = DateTime.UtcNow; User.LastLockoutDate = DateTime.UtcNow; User.IsLockedOut = true; } Context.SaveChanges(); return false; } String NewHashedPassword = Crypto.HashPassword(newPassword); if (NewHashedPassword.Length > 128) { return false; } User.Password = NewHashedPassword; User.ConfirmPassword = NewHashedPassword; User.LastPasswordChangedDate = DateTime.UtcNow; Context.SaveChanges(); return true; } }
public override bool ValidateUser(string username, string password) { if (string.IsNullOrEmpty(username)) { return false; } if (string.IsNullOrEmpty(password)) { return false; } using (StudentContext Context = new StudentContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User == null) { return false; } if (User.StatusId != (int)UserStatus.Active) { return false; } if (User.IsLockedOut) { return false; } String HashedPassword = User.Password; Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, password)); if (VerificationSucceeded) { User.PasswordFailuresSinceLastSuccess = 0; User.LastLoginDate = DateTime.UtcNow; User.LastActivityDate = DateTime.UtcNow; } else { int Failures = User.PasswordFailuresSinceLastSuccess; if (Failures < MaxInvalidPasswordAttempts) { User.PasswordFailuresSinceLastSuccess += 1; User.LastPasswordFailureDate = DateTime.UtcNow; } else if (Failures >= MaxInvalidPasswordAttempts) { User.LastPasswordFailureDate = DateTime.UtcNow; User.LastLockoutDate = DateTime.UtcNow; User.IsLockedOut = true; } } try { // Your code... // Could also be before try if you know the exception occurs in SaveChanges User.ConfirmPassword = User.Password; Context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } if (VerificationSucceeded) { return true; } else { return false; } } }
//CodeFirstMembershipProvider does not support UpdateUser because this method is useless. public override void UpdateUser(MembershipUser user) { using (StudentContext Context = new StudentContext()) { Int64 userId = Convert.ToInt64(user.ProviderUserKey); var currentUser = Context.Users.Where(u => u.UserId == userId).SingleOrDefault(); currentUser.StatusId = (int)UserStatus.Active; currentUser.ConfirmPassword = currentUser.Password; Context.SaveChanges(); } }