public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { try { // Create a profile, password, and link the local login before signing in the user User user = new User(model.UserName); if (await Users.Create(user) && await Secrets.Create(new UserSecret(model.UserName, model.Password)) && await Logins.Add(new UserLogin(user.Id, IdentityConfig.LocalLoginProvider, model.UserName))) { await SignIn(user.Id, isPersistent: false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError(String.Empty, "Failed to create login for: " + model.UserName); } } catch (DbEntityValidationException e) { ModelState.AddModelError("", e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); } } // If we got this far, something failed, redisplay form return View(model); }
public void StrongUserShouldDefeatWeakUserInBattle() { var weakUser = new User { Agility = 5, Stamina = 5, Strength = 5, Charisma = 5, Defence = 5 }; var strongUser = new User { Agility = 10, Stamina = 10, Strength = 10, Charisma = 10, Defence = 10 }; var battle = new Battle { FirstPlayer = strongUser, SecondPlayer = weakUser }; var baattleReturn = BattleController.PlayBattle(battle); Assert.AreEqual(strongUser, baattleReturn.Winner); }
public void CreateTutorInformation(User tutor, ITutor information) { Message = ""; Succeed = false; using (var db = new BaseDbContext()) { var contextUser = db.Users.Find(tutor.Id); if (contextUser == null) { Message = "未能从数据库中找到用户"; return; } var info = new TutorInformation { Tutor = contextUser, Introduction = information.TutorIntroduction, Position = information.TutorPosition, Avatar = information.TutorAvatar }; db.TutorInformations.Add(info); try { db.SaveChanges(); } catch (Exception) { Message = "出现错误"; return; } Succeed = true; return; } }
public Guid Create(User user) { user.UniqueId = Guid.NewGuid(); user.CreateDate = user.ModifiedDate = DateTime.Now.ToJavaScriptMilliseconds(); Users.Add(user); return user.UniqueId; }
public ActionResult Create(FormCollection collection) { //var item = new User(); var item = new User() { CreatedOn = DateTime.Now}; //please don't omit this... var whiteList=new string[]{"UserName","OpenID","Friendly","LastLogin","ModifiedOn"}; UpdateModel(item,whiteList,collection.ToValueProvider()); var dummy = item; if(ModelState.IsValid){ try { _session.Add<User>(item); _session.CommitChanges(); this.FlashInfo("User saved..."); return RedirectToAction("Index"); } catch { this.FlashError("There was an error saving this record"); return View(item); } } return View(item); }
public ActionResult Edit(User user) { if (ModelState.IsValid) { context.Entry(user).State = EntityState.Modified; context.SaveChanges(); return RedirectToAction("Index"); } return View(user); }
public void UserShouldHaveValidDefence() { var user = new User { Charisma = 5, Defence = 5 }; var defence = BattleController.CalculateUserDefence(user); Assert.AreEqual(27, defence); }
public ActionResult Create(User user) { if (ModelState.IsValid) { context.Users.Add(user); context.SaveChanges(); return RedirectToAction("Index"); } return View(user); }
public void UserShouldHaveValidAttack() { var user = new User { Agility = 5, Stamina = 5, Strength = 5 }; var attack = BattleController.CalculateUserAttack(user); Assert.AreEqual(25, attack); }
public ActionResult Create(User user) { try { userRepository.InsertUser(user); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult Delete(int id, User user) { try { userRepository.DeleteUser(id); return RedirectToAction("Index"); } catch { return View(); } }
public void Update(Guid uniqueId, User user) { var userToUpdate = Users.FirstOrDefault(i => i.UniqueId == uniqueId); if (userToUpdate == null) return; userToUpdate.FirstName = user.FirstName ?? userToUpdate.FirstName; userToUpdate.LastName = user.LastName ?? userToUpdate.LastName; userToUpdate.Password = user.Password ?? userToUpdate.Password; userToUpdate.Roles = user.Roles ?? userToUpdate.Roles; userToUpdate.TimezoneOffset = user.TimezoneOffset; userToUpdate.TwitterUsername = user.TwitterUsername ?? userToUpdate.TwitterUsername; userToUpdate.SocialNetworks = user.SocialNetworks ?? userToUpdate.SocialNetworks; userToUpdate.ModifiedDate = DateTime.Now.ToJavaScriptMilliseconds(); }
public static User CreateUser(SiteDB db, string Username, string Password, string Email) { //create a new user. User user = new User(); user.Username = Username; user.Email = Email; user.Enabled = true; //create salt for password hash. user.PasswordHash = CreatePasswordHash(Password); user.Created = DateTime.Now; user.Updated = user.Created; db.Users.Add(user); db.SaveChanges(); return user; }
public static User Create3rdPartyAuthUser(SiteDB db, string LoginId, string LoginToken, short UserTypeId, string Username) { //create a new user. User user = new User(); user.LoginId = LoginId; user.LoginToken = LoginToken; user.UserTypeId = UserTypeId; user.Username = Username; //set dummy email. user.Email = "*****@*****.**"; user.Enabled = true; user.Created = DateTime.Now; user.Updated = user.Created; db.Users.Add(user); db.SaveChanges(); return user; }
public void StrongerUserShouldHaveMoreDamage() { var weakUser = new User { Agility = 5, Stamina = 5, Strength = 5, Charisma = 5, Defence = 5 }; var strongUser = new User { Agility = 10, Stamina = 10, Strength = 10, Charisma = 10, Defence = 10 }; var strongerUserDamage = BattleController.CalculateUserDamage(strongUser, weakUser); var weakerUserDamage = BattleController.CalculateUserDamage(weakUser, strongUser); Assert.IsTrue(strongerUserDamage > weakerUserDamage); }
/// <summary> /// Cache any info about the user we'll be accessing frequently like their name, email, or Organization. /// </summary> /// <param name="FormsAuthService"></param> /// <param name="user"></param> public static void CacheUserData(IFormsAuthenticationService FormsAuthService, User user) { ////cache all the info we can for the user. //friendlyname: HttpContext.Current.Cache.GetOrStore<string>(GetUserSignInKey(FormsAuthService, UserFriendlyNameKey), user.Username); }
public ActionResult UserEdit(User model) { if (ModelState.IsValid) { db.Users.Attach(model); db.Entry(model).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index", new { status = AdminOperationStatus.Success }); } return View(); }
/// <summary> /// Builds a MembershipUser object from the given data. /// </summary> /// <param name="user">The user.</param> /// <returns></returns> /// <remarks>EDIT ON REUSE: User</remarks> private MembershipUser BuildMemberObject(User user) { if (user != null) { //convert User to miniUser and pass into BuildMemberObject. miniUser muu = new miniUser(); muu.CreateDate = user.Created; muu.Email = user.Email; muu.LastLoginDate = user.LastLogin; muu.MemberId = user.UserId; muu.Name = user.Email; return BuildMemberObject(muu); } else { return null; } }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider ClaimsIdentity id = await HttpContext.GetExternalIdentity(); if (id == null) { return View("ExternalLoginFailure"); } try { // Create a local user and sign in var user = new User(model.UserName); if (await Users.Create(user) && await Logins.Add(new UserLogin(user.Id, model.LoginProvider, id.FindFirstValue(ClaimTypes.NameIdentifier)))) { await SignIn(user.Id, id.Claims, isPersistent: false); return RedirectToLocal(returnUrl); } else { return View("ExternalLoginFailure"); } } catch (DbEntityValidationException e) { ModelState.AddModelError("", e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
public TeamRecord(Team team, TeamMemberStatus status,User user) : base() { Team = team; Status = status; Receiver = user; }
//[Authorize(Roles="Administrator")] public ActionResult Create() { var item = new User(); return View(item); }
/// <summary> /// Create a new User object. /// </summary> /// <param name="id">Initial value of the ID property.</param> /// <param name="userName">Initial value of the UserName property.</param> /// <param name="openID">Initial value of the OpenID property.</param> /// <param name="lastLogin">Initial value of the LastLogin property.</param> /// <param name="createdOn">Initial value of the CreatedOn property.</param> /// <param name="modifiedOn">Initial value of the ModifiedOn property.</param> /// <param name="friendly">Initial value of the Friendly property.</param> public static User CreateUser(global::System.Guid id, global::System.String userName, global::System.String openID, global::System.DateTime lastLogin, global::System.DateTime createdOn, global::System.DateTime modifiedOn, global::System.String friendly) { User user = new User(); user.ID = id; user.UserName = userName; user.OpenID = openID; user.LastLogin = lastLogin; user.CreatedOn = createdOn; user.ModifiedOn = modifiedOn; user.Friendly = friendly; return user; }
public void UpdateUser(int id, User user) { var userOld = GetUserByID(id); userOld.FirstName = user.FirstName; userOld.LastName = user.LastName; }
public void InsertUser(User user) { user.UserID = UserData.Users.Count; UserData.Users.Add(user); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // 从外部登录提供程序获取有关用户的信息 var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new User { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new User { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName, Time = DateTime.Now, IsDisabled = false, Profile = new Profile { Email = model.Email, Phone = "", Searchable = true, InformationPrivacy = false, Other = "" } }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); //为账户添加角色 var roleName = "student"; ApplicationRoleManager roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(new BaseDbContext())); //判断角色是否存在 if (!roleManager.RoleExists(roleName)) { //角色不存在则建立角色 await roleManager.CreateAsync(new IdentityRole(roleName)); } //将用户加入角色 await UserManager.AddToRoleAsync(user.Id, roleName); // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771 // 发送包含此链接的电子邮件 // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // 如果我们进行到这一步时某个地方出错,则重新显示表单 return View(model); }
/// <summary> /// If userIsOnline is true it updates the LastLoginDate. /// </summary> /// <param name="db"></param> /// <param name="user"></param> /// <param name="userIsOnline"></param> /// <remarks>EDIT ON REUSE: User</remarks> private void UpdateLastLogin(SiteDB db, User user, bool userIsOnline) { if (userIsOnline && user != null) { user.LastLogin = DateTime.Now; db.SaveChanges(); } }
/// <summary> /// Deprecated Method for adding a new object to the Users EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToUsers(User user) { base.AddObject("Users", user); }
public ActionResult Edit(int id, User user) { try { userRepository.UpdateUser(id, user); return RedirectToAction("Index"); } catch { return View(); } }
public static List<CourseOperation> List(string select, bool IsTeacher,User user) { using (BaseDbContext db = new BaseDbContext()) { try { int pageSize = 5; int page = 0; IQueryable<CourseOperation> Course = db.CourseOperations.Where(a => a.Enabled != false); if (IsTeacher) { user = db.Users.Find(user.Id); if (select == null | select == "") { Course = (from a in db.CourseOperations where a.Creator.Id == user.Id orderby a.Name select a).AsQueryable(); } else { Course = (from a in db.CourseOperations where a.Creator.Id == user.Id && a.Name == @select orderby a.Name select a).AsQueryable(); } } else { if (select == null) { Course = (from a in db.CourseOperations where a.StartTime > DateTime.Now orderby a.Time select a).AsQueryable(); } else { Course = (from a in db.CourseOperations where a.Name == @select && a.StartTime > DateTime.Now orderby a.Time select a).AsQueryable(); } } var paginatedNews = new ListPage<CourseOperation>(Course, page, pageSize); return paginatedNews; } catch { return null; } } }