public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { using(var db= new ELearningContext()) { User userr= new User(){UserName=model.UserName, Password= model.Password}; db.Users.Add(userr); db.SaveChanges(); } var user = new ApplicationUser() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }
public ChatMessage(extmodels.User _sender, extmodels.User _recipient, string _message) { Sender = _sender; Recipient = _recipient; Message = _message; Date = DateTime.Now; }
public ViewResult Register(ViewModels.RegisterViewModel registerViewModel) { if (ModelState.IsValid) { if (!DatabaseContext.Users.Any(current => current.EmailAddress == registerViewModel.EmailAddress.Trim().ToLower())) { Models.User user = new Models.User { RoleId = 1, Username = registerViewModel.Username, EmailAddress = registerViewModel.EmailAddress.Trim().ToLower(), Password = registerViewModel.Password, ActiveCode = System.Guid.NewGuid().ToString(), IsActive = true, RegisterDate = System.DateTime.Now, }; DatabaseContext.Users.Add(user); DatabaseContext.SaveChanges(); #region Send Active EmailAddress string body = PartialToStringClass.RenderPartialView("ManageEmails", "_ActivationEmailPartialView", user); SendEmail.Send(user.EmailAddress, "ایمیل فعالسازی", body); #endregion return(View("SuccessRegister", user)); } else { ModelState.AddModelError(registerViewModel.EmailAddress, "ایمیل وارد شده تکراری می باشد"); } } return(View(registerViewModel)); }
public void add() { if(IsAjaxRequest) CancelLayout(); PropertyBag["u"] = new User(); RenderView("addoredit"); }
public void ReadUserPostsTest() { // act string input = "Bob"; var user = new User { UserId = Guid.NewGuid(), Username = input }; var output = new StringBuilder(); output.AppendLine("Good game though. (1 minute(s) ago)"); output.AppendLine("Damn! We lost! (2 minute(s) ago)"); var messages = new List<Message> { new Message { Description = "Good game though.", PostedDt = DateTime.UtcNow.AddMinutes(-1)}, new Message { Description = "Damn! We lost!", PostedDt = DateTime.UtcNow.AddMinutes(-2)} }; _userManagerMock.Setup(x => x.GetUserByUsername(user.Username, true)).Returns(user); _messageManagerMock.Setup(x => x.GetMessages(user)).Returns(messages); var read = new Read(_userManagerMock.Object, _messageManagerMock.Object); // actual var actual = read.Perform(input); // assert Assert.AreEqual(actual, output.ToString()); _messageManagerMock.Verify(x => x.GetMessages(user), Times.Once); }
public Community(Models.User currentUser) { InitializeComponent(); communityViewModel = new CommunityViewModel(currentUser); this.DataContext = communityViewModel; this.currentUser = currentUser; }
private void btnServiceReference_Click(object sender, EventArgs e) { try { string idString = txtUserId.Text; int id = int.Parse(idString); User user; using (var service = new UsersService.UsersServiceSoapClient()) { // Service References add it's own classes to match the ones in the Web Service UsersService.User serviceUser = service.GetUser(id); if (serviceUser == null) { throw new Exception("User not found."); } user = new User { Id = serviceUser.Id, Name = serviceUser.Name }; } userName.Text = user.Name; } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal static void SeedAdmin(SciHubDbContext context) { const string adminUserName = "******"; const string adminPassword = "******"; if (context.Users.Any(u => u.UserName == adminUserName)) { return; } var userManager = new UserManager<User>(new UserStore<User>(context)); var admin = new User { UserName = adminUserName, Email = "*****@*****.**", FirstName = "Admin", LastName = "Adminos", Avatar = UserDefaultPictureConstants.Female, Gender = Gender.Female, About = "I am the Decider!" }; userManager.Create(admin, adminPassword); userManager.AddToRole(admin.Id, UserRoleConstants.Admin); userManager.AddToRole(admin.Id, UserRoleConstants.Default); context.SaveChanges(); }
public User SearchUserByLogin(string login) { var user = new Models.User(); using (var connection = factory.CreateConnection()) { connection.ConnectionString = connectionString; var command = (SqlCommand)connection.CreateCommand(); command.CommandText = "SELECT UserID, Login, PasswordHash, U.RoleID, Name " + "FROM [Users] as U JOIN [Roles] as R ON U.RoleID = R.RoleID " + "WHERE LOWER(@Login) = LOWER(Login)"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@Login", string.IsNullOrEmpty(login) ? DBNull.Value : (object)login); connection.Open(); using (var reader = command.ExecuteReader()) { if (reader.Read()) { user.UserID = (int)reader["UserID"]; user.Login = reader["Login"] as string; user.PasswordHash = reader["PasswordHash"] as string; user.Role = new Role(); user.Role.RoleID = (int)reader["RoleID"]; user.Role.Name = reader["Name"] as string; } } } return(user); }
private async void btn_Login_Click(object sender, EventArgs e) { var user = new User { Account = this.textBox_Account.Text, Password = this.textBox_Password.Text }; try { var state = await RemoteServer.Instance.Login(user, false); if (state == false) { MessageBox.Show("账号或密码错误...", "系统提示"); } else { this.Hide(); new SumForm().ShowDialog(); this.Close(); } } catch (TimeoutException ex) { this.Text = ex.Message; } catch (RemoteException ex) { MessageBox.Show(ex.Message, "远程服务器异常"); } catch (Exception ex) { MessageBox.Show(ex.Message, "未分类的异常"); } }
/// <summary> /// 添加用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public static Guid Add(string userName, string phoneNumber, string key) { if (userName == "" || phoneNumber == "" || key == "") { throw (new Exception("请将注册信息填写完整")); } else if (phoneNumber.Length != 11) { throw (new Exception("请输入正确的手机号")); } else { using (DataContext dc = new DataContext(Dap.common.conn)) { var tb = dc.GetTable <Models.User>(); Models.User user = new Models.User(); user.UserName = userName; user.MobilePhone = phoneNumber; user.Password = key; user.ID = System.Guid.NewGuid(); tb.InsertOnSubmit(user); dc.SubmitChanges();//后台自动生成用户ID return(user.ID); } } }
public void SeedUser(UserSeedModel model, HomeGrownBulgariaDbContext context) { if (!context.Users.Any(u => u.UserName == model.Username)) { var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); var user = new User { UserName = model.Username, Email = model.Username, FirstName = model.FirstName, LastName = model.LastName, AverageRatingReceived = ValidationConstants.AverageRatingInitialValue, City = model.City }; IdentityResult result = userManager.Create(user, model.Password); if (!result.Succeeded) { throw new OperationCanceledException(result.Errors.First()); } if (model.Role != null) { userManager.AddToRole(user.Id, model.Role); } context.SaveChanges(); } }
static void Main(string[] args) { using (IRiakEndPoint endpoint = RiakCluster.FromConfig("riakConfig")) { IRiakClient client = endpoint.CreateClient(); UserRepository userRepo = new UserRepository(client); MsgRepository msgRepo = new MsgRepository(client); TimelineRepository timelineRepo = new TimelineRepository(client); TimelineManager timelineMgr = new TimelineManager(timelineRepo, msgRepo); // Create and save users var marleen = new User("marleenmgr", "Marleen Manager", "*****@*****.**"); var joe = new User("joeuser", "Joe User", "*****@*****.**"); userRepo.Save(marleen); userRepo.Save(joe); // Create new Msg, post to timelines Msg msg = new Msg(marleen.UserName, joe.UserName, "Welcome to the company!"); timelineMgr.PostMsg(msg); // Get Joe's inbox for today, get first message Timeline joesInboxToday = timelineMgr.GetTimeline(joe.UserName, Timeline.TimelineType.Inbox, DateTime.UtcNow); Msg joesFirstMsg = msgRepo.Get(joesInboxToday.MsgKeys.First()); Console.WriteLine("From: " + joesFirstMsg.Sender); Console.WriteLine("Msg : " + joesFirstMsg.Text); } }
public static void Main() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ErisSystemContext, Data.Migrations.EfConfiguration>()); Importer.ImportCountries(); var db = new ErisSystemContext(); var date = new DateTime(1991, 01, 01); var country = db.Countries.Find(3); var hitman = new User(); hitman.AboutMe = "Thug life"; hitman.UserName = "******"; hitman.PasswordHash = "ASFADSFDEFE@#@$@$@ASDFAS"; hitman.DateOfBirth = date; hitman.CountriesOfOperation.Add(country); db.Users.AddOrUpdate(hitman); db.SaveChanges(); var repositoryTest = new EfGenericRepository<User>(db); var hitmen = repositoryTest.All(); foreach (var x in hitmen) { Console.WriteLine(x.UserName); Console.WriteLine(x.Gender); Console.WriteLine(x.AboutMe); Console.WriteLine(x.DateOfBirth); } }
public override void Import(BGTouristGuideDbContext db) { PasswordHasher hasher = new PasswordHasher(); User admin = new User { Email = "*****@*****.**", UserName = "******", FirstName = "Admin", LastName = "Admin", PasswordHash = hasher.HashPassword("admin"), RegistrationDate = DateTime.Now, SecurityStamp = Guid.NewGuid().ToString() }; db.Users.Add(admin); IdentityUserRole adminRole = new IdentityUserRole(); var dbadminRole = db.Roles.Where(r => r.Name == DatabaseConstants.AdminUserRole).FirstOrDefault(); adminRole.UserId = admin.Id; adminRole.RoleId = dbadminRole.Id; dbadminRole.Users.Add(adminRole); db.SaveChanges(); }
private void btnSave_Click(object sender, EventArgs e) { Models.DataBaseContext OdbContext = null; try { OdbContext = new Models.DataBaseContext(); Models.User Ouser = new Models.User(); var model = OdbContext.Users.Where(E => (E.UserName == tbxUserName.Text.Trim() && E.Password == tbxPassword.Text.Trim())).ToList(); if (model.Count > 0) { trustUser = true; this.Close(); } else { LoginErrorCount++; MessageBox.Show("نام کاربری یا کلمه عبور شما اشتباه است "); if (LoginErrorCount == 3)// اگر کاربر سه بار نام کاربری و کلمه عبور را اشتباه وارد کرد برنامه بسته شود { this.Close(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void PerformPostMessageOnExistingUserTest() { // act string input = "Bob -> Good game though."; User user = new User { UserId = Guid.NewGuid(), Username = "******" }; Message userMessage = new Message { UserId = user.UserId }; _userManagerMock.Setup(x => x.GetUserByUsername(user.Username, false)).Returns(user); _messageManagerMock.Setup(x => x.AddMessage(user.UserId, input)); var perform = new Post(_userManagerMock.Object, _messageManagerMock.Object); // actual var actual = perform.Perform(input); // assert Assert.AreEqual(actual, string.Empty); _userManagerMock.Verify(x => x.AddUser(It.IsAny<string>()), Times.Never); _messageManagerMock.Verify(x => x.AddMessage(It.IsAny<Guid>(), It.IsAny<string>()), Times.AtLeastOnce); }
public void PerformPostNewMessageOnNewUserTest() { // act string input = "Alice -> I love the weather today"; var user = new User { UserId = Guid.NewGuid(), Username = "******" }; _userManagerMock.Setup(x => x.GetUserByUsername(user.Username, false)).Returns((User) null); _userManagerMock.Setup(x => x.AddUser(user.Username)).Returns(user); _messageManagerMock.Setup(x => x.AddMessage(user.UserId, input)); var perform = new Post(_userManagerMock.Object, _messageManagerMock.Object); // actual var actual = perform.Perform(input); // assert Assert.AreEqual(actual, string.Empty); _userManagerMock.Verify(x=>x.AddUser(It.IsAny<string>()), Times.Once); _messageManagerMock.Verify(x=>x.AddMessage(It.IsAny<Guid>(),It.IsAny<string>()), Times.AtLeastOnce); }
public MembershipCreateStatus SignUp(string userName, string password, string email) { var user = new User { Name = userName, PasswordHash = password, Email = email }; return !Repository.AddUser(user) ? MembershipCreateStatus.DuplicateUserName : MembershipCreateStatus.Success; }
public void SeedData(EmployerEmployeeHuntDbContext context) { var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); var adminUser = new User { UserName = AdministratorUserName, Email = AdministratorUserName }; var headhunterUser = new User { UserName = HeadhunterUserName, Email = HeadhunterUserName }; var developerUser = new User { UserName = DeveloperUserName, Email = DeveloperUserName }; var employerUser = new User { UserName = EmployerUserName, Email = EmployerUserName }; userManager.Create(adminUser, AdministratorPassword); userManager.Create(headhunterUser, HeadhunterPassword); userManager.Create(developerUser, DeveloperPassword); userManager.Create(employerUser, EmployerPassword); userManager.AddToRole(adminUser.Id, GlobalConstants.AdministratorRoleName); userManager.AddToRole(headhunterUser.Id, GlobalConstants.HeadhunterRoleName); userManager.AddToRole(developerUser.Id, GlobalConstants.UserRoleName); userManager.AddToRole(employerUser.Id, GlobalConstants.UserRoleName); for (int i = 0; i < 60; i++) { var currentUser = new User { Email = string.Format("user_{0}@somemail.com", i + 1), UserName = string.Format("user_{0}", i + 1) }; userManager.Create(currentUser, currentUser.Email); if (i % 2 == 0) { userManager.AddToRole(currentUser.Id, GlobalConstants.HeadhunterRoleName); } else { userManager.AddToRole(currentUser.Id, GlobalConstants.UserRoleName); } } }
public static double CalculateUserDamage(User attacker, User defender) { double attack = CalculateUserAttack(attacker); double defence = CalculateUserDefence(defender); double modifier = CalculateModifier(); double damage = (((2 * modifier + 100) / 20) * ((attack / defence) / 10) + 2) * (10 / modifier); return Math.Round(damage, 2); }
public void AddOrUpdate(User user) { if (user == null) throw new ArgumentNullException("user"); if (user.Identifier == Guid.Empty) user.Identifier = Guid.NewGuid(); _users.AddOrUpdate(user.FacebookId, user, (key, oldValue) => user); }
public void ActivateUser(User user, string code) { user.IsActive = true; user.LastModifiedDate = DateTime.Now; user.Password = code; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); }
public void Check_AddUser() { var editUser = new User { UserName = "******"}; var userStore = new UserStore(_databaseContextMock.Object); userStore.EditUser(editUser, 1); var result = userStore.GetById(1); Assert.AreEqual("new", result.UserName); }
private User MVCToLogic(UserForm userMVC) { var userLogic = new User(); userLogic.Email = userMVC.Email; userLogic.Username = userMVC.Username; userLogic.Password = userMVC.Password; return(userLogic); }
public async Task <int> AddNewUser(Models.User UserInfo) { using (var context = ContextFactory.CreateDbContext(ConnectionString)) { context.Users.Add(UserInfo); await context.SaveChangesAsync(); } return(0); }
private void EnrichPostWithAuthor(Models.Post post, Models.User user) { if (user == null) { Logger.LogWarning("Post Author was not found! post id: {}, poster id: {}", post._id, post.Poster._id); } else { post.Poster = user; } }
public static User Convert(RegisterUser user) { User dbUser = new User(); dbUser.FirstName = user.FirstName; dbUser.LastName = user.LastName; dbUser.PhoneNumber = user.PhoneNumber; dbUser.Password = user.CryptPass; dbUser.Username = user.Username; return dbUser; }
public void FirstName_ShouldBeSetAndGottenCorrectly(string firstName) { //Arrange && Act var user = new Models.User() { FirstName = firstName }; //Assert Assert.AreEqual(firstName, user.FirstName); }
public static int CalculateNextStatLevelPrice(User user) { var sum = (user.Agility + user.Charisma + user.Defence + user.Stamina + user.Strength); var price = sum * 3; if (price < GoldConstants.StartingStatPrice) { price = GoldConstants.StartingStatPrice; } return price; }
public static List <Models.User> RemoveReferences(this List <Models.User> list) { var newList = new List <Models.User>(); list.ForEach(item => { var obj = new Models.User(); obj = item.RemoveRefernces(); newList.Add(obj); }); return(newList); }
public static void DisplayIsValidUser(Models.User user, Pool poolObj) { if (user != null) { Console.WriteLine($"Login Successful----Welcome {user.Name}"); } else { Console.WriteLine("Sorry Authentication Failed"); Init(poolObj); } }
public static void EnsureSafe(NameValueCollection form, User CurrentUser) { string xsrfFormValue = form["fkey"]; if (xsrfFormValue.IsNullOrEmpty()) throw new InvalidOperationException("XSRF validation: Request did not have required form value 'fkey'"); if (!xsrfFormValue.Equals(CurrentUser.XSRFFormValue, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException( "XSRF validation: Request form value 'fkey' did not match CurrentUser.XSRFFormValue"); Debug.WriteLine("XSRFSafeAttribute.EnsureSafe => true"); }
public void PhoneNumber_ShouldBeSetAndGottenCorrectly() { //Arrange var testPhoneNumber = "08758649645"; //Act var user = new Models.User { PhoneNumber = testPhoneNumber }; //Assert Assert.AreSame(testPhoneNumber, user.PhoneNumber); }
public void Username_ShouldBeSetAndGottenCorrectly() { //Arrange var testUsername = "******"; //Act var user = new Models.User { Username = testUsername }; //Assert Assert.AreSame(testUsername, user.Username); }
public User CreateUser(User item) { var r = this.Core.CreateUser( item.UserName, item.Password, item.GivenName, item.MiddleName, item.FamilyName, item.Email, item.Gender, item.Birthdate); return r; }
public void GetAllCourses() { var user = new User(); user.EmailAddress = "*****@*****.**"; user.Grade = "2"; user.Name = "Test User"; user.Role = "1"; var courseFacade = new CourseFacade(); var courses = courseFacade.GetAllCourses(user); Assert.IsTrue(courses.Count > 0); }
public void FirstName_ShouldBeSetAndGottenCorrectly() { //Arrange var testFirstName = "Anton"; //Act var user = new Models.User { FirstName = testFirstName }; //Assert Assert.AreSame(testFirstName, user.FirstName); }
public void LastName_ShouldBeSetAndGottenCorrectly() { //Arrange var testLastName = "Angelov"; //Act var user = new Models.User { LastName = testLastName }; //Assert Assert.AreSame(testLastName, user.LastName); }
public async void SignUpLocally(string username, string password) { var newUser = new User { Username = username, Password = password }; var userCollection = await this.users.Get(); if (!userCollection.Contains(newUser)) { await this.users.Insert(newUser); } }
public async Task Userinfo_StateUnderTest_ExpectedBehavior_InvalidUser() { // Arrange var unitUnderTest = this.CreateUserinfoController(); Models.User user = null; this.mockUserBusiness.Setup(r => r.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(user); // Act var result = await unitUnderTest.Userinfo(); // Assert Assert.IsType <BadRequestObjectResult>(result.Result); }
private async Task CheckIfAdminExists() { User user = await this._userManager.FindByNameAsync("admin"); if (user == null) { // add editor user user = new User { UserName = "******" }; await this._userManager.CreateAsync(user, "BasicPwd24!"); } }
private static void CreateNewUser(UserManager<User> userManager, RoleManager<IdentityRole> roleManager, string name, string email, string password) { //Create User with password var user = new User(); user.UserName = "******"; user.Email = email; var adminresult = userManager.Create(user, password); //Add User to Role if (adminresult.Succeeded) { var result = userManager.AddToRole(user.Id, name); } }
public void UserRegistration() { var user = new User(); user.EmailAddress = "*****@*****.**"; user.Grade = "2"; user.Name = "Test User"; user.Password = "******"; user.Role = Enums.Role.Student.ToString(); var userRegistrationFacade = new UserRegistrationFacade(); var newUser = userRegistrationFacade.RegisterUser(user); Assert.IsTrue(newUser.Id > 0); }
public static Models.User GetUser() { try { Console.WriteLine("Please Enter Name:"); string name = GetName(); Console.WriteLine("Age:"); int age = GetInt(); Console.WriteLine("Gender:"); Gender gender = GetGender(); Console.WriteLine("Adhar No:"); Int64 adharNo = GetAdharNo(); Console.WriteLine("Mobile No:"); Int64 mobileNo = GetMobileNo(); Console.WriteLine("Do you have DrivingLicenceNumber:"); bool hasDrivingLicence = HasDrivingLicence(); string drivingLicenceNumber; drivingLicenceNumber = null; if (hasDrivingLicence) { Console.WriteLine("Please enter driving licence Number"); drivingLicenceNumber = GetDrivingLicenceNo(); } Console.WriteLine("Username:"******"Password"); string password = GetString(); bool isActive = true; Wallet wallet = new Wallet(); wallet.Balance = 0; User userObj = new Models.User(); userObj.Name = name; userObj.Age = age; userObj.Type = gender; userObj.AdharNo = adharNo; userObj.MobileNo = mobileNo; userObj.DrivingLicenseNo = drivingLicenceNumber; userObj.UserName = username; userObj.Password = password; userObj.IsActive = isActive; userObj.Wallet = wallet; return(userObj); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
public ActionResult CheckUser(string email, string cellNumber, string fullName) { try { cellNumber = cellNumber.Replace("۰", "0").Replace("۱", "1").Replace("۲", "2").Replace("۳", "3").Replace("۴", "4").Replace("۵", "5").Replace("۶", "6").Replace("v", "7").Replace("۸", "8").Replace("۹", "9"); bool isValidMobile = Regex.IsMatch(cellNumber, @"(^(09|9)[0-9][0-9]\d{7}$)|(^(09|9)[3][12456]\d{7}$)", RegexOptions.IgnoreCase); if (!isValidMobile) { return(Json("invalidMobile", JsonRequestBehavior.AllowGet)); } bool isEmail = Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); if (!isEmail) { return(Json("invalidEmail", JsonRequestBehavior.AllowGet)); } User user = db.Users.FirstOrDefault(current => current.CellNum == cellNumber); string code; if (user != null) { code = user.Password; } else { Guid userId = CreateUser(fullName, cellNumber, email); int codeInt = CreateActivationCode(userId); code = codeInt.ToString(); } db.SaveChanges(); SendSms(cellNumber, code); return(Json("true", JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(Json("false", JsonRequestBehavior.AllowGet)); } }
public static WhatsNewImageCommentDTO ToWhatsNewComment(Comment comment, User uploadedBy, string filename) { var author = (comment.Deleted) ? null : ToUserDTO(comment.Author); var uploader = ToUserDTO(uploadedBy); return new WhatsNewImageCommentDTO { Author = author, Deleted = comment.Deleted, ID = comment.ID, ImageID = comment.ContextID, ImageUploadedBy = uploader, Text = comment.Text, Filename = filename, }; }
public int ReturnCode() { Guid userRoleId = ReturnUserEmployeeRole(); Guid userEmployerRoleId = ReturnUserEmployerRole(); User user = db.Users.Where(current => current.RoleId == userRoleId || current.RoleId == userEmployerRoleId).OrderByDescending(current => current.Code).FirstOrDefault(); if (user != null) { return(user.Code + 1); } else { return(300001); } }
public static int CalculateGoldToAdd(User user, int wins) { int modifier = RandomGenerator.GenerateRandomNumber(GoldConstants.MinGold, GoldConstants.MaxGold); int gold = 0; if (wins != 0) { gold = modifier / wins; } else { gold = modifier; } return gold; }
public bool Login(User user, bool ifAdmin) { // 调用客户端的Sort var sortResult = this.CurrentContext.Session.InvokeApi<List<int>>("Sort", new List<int> { 3, 1, 2 }).Result; if (user == null) { throw new ArgumentNullException("user"); } // 记录客户端的登录结果 var state = this.UserDao.IsExist(user); this.CurrentContext.Session.TagBag.Logined = state; return state; }
public User GetUser() { string firstName = this.firstNames[this.random.Next(0, this.firstNames.Length)]; string lastName = this.lastNames[this.random.Next(0, this.lastNames.Length)]; var user = new User { FirstName = firstName, LastName = lastName, ProfileImageUrl = "~/Images/default.jpg", FacebookAccountUrl = "http://facebook.com", YouTubeAccountUrl = "http://youtube.com" }; return user; }
/// <summary> /// This method get user records by pass applicationId parameter synchronously /// </summary> /// <param name="applicationId"></param> /// <returns> /// Return a record of user by applicationId /// </returns> public User GetVerifierUser(Guid applicationId) { var result = DbSet .Where(current => current.Id == applicationId) .FirstOrDefault() ; if (result == null) { return(null); } Models.User user = result.VerifierUser; return(user); }
/// <summary> /// 用户登陆成功事件注册的方法 /// </summary> /// <param name="objUser"></param> private void FrmLogin_LoginCompleted(Models.User objUser) { Program.objCurrentUser = objUser; toolStripStatusLbl_User.Text = " 登陆用户:" + objUser.UserName; ShowMessage(objUser.UserName + "登陆成功"); //启用menustrip this.menuStrip1.Enabled = true; //创建型号选择窗体并显示,此时为登录状态 CloseExistedSubForm(); FrmType objFrmtype = FrmType.GetSingleInstance(); objFrmtype.SelectTypeCompleted += Frmtype_SelectTypeCompleted; OpenSubForm(objFrmtype); }
/// <summary> /// This method get user records by pass applicationId parameter asynchronously /// </summary> /// <param name="applicationId"></param> /// <returns> /// Return a record of user by applicationId /// </returns> public virtual async Task <User> GetVerifierUserAsuync(Guid applicationId) { var result = await DbSet .Where(current => current.Id == applicationId) .FirstOrDefaultAsync() ; if (result == null) { return(null); } Models.User user = result.VerifierUser; return(user); }
public UserShow(MainWindow mainWindow, User user) { InitializeComponent(); this.mainWindow = mainWindow; this.user = user; listSkills.ItemsSource = user.Skills; username.Content = user.Username; if ((user.FirstName != "" && user.FirstName != null) || (user.LastName != "" && user.LastName != null)) { username.Content += $" ({user.FirstName} {user.LastName})"; } description.Text = user.Description; }
public void LogInTest() { var newUser = new UserLogic(); newUser.Username = "******"; newUser.Email = "*****@*****.**"; newUser.Password = "******"; userController.Add(newUser); var user = userController.LogIn("NewUser", "iamnewuser"); Assert.AreEqual("*****@*****.**", user.Email); user = userController.LogIn("NewUser", "1234"); Assert.IsNull(user); }
public System.String CreateUser(Models.User user) { var ctx = WebOperationContext.Current; ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; try{ this._log.Debug(new { user = user, _name = "CreateUser" }); return(this._service.CreateUser(user)); } catch (Exception ex) { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.ExpectationFailed; ctx.OutgoingResponse.StatusDescription = ex.Message; this._log.Error(new { name = "CreateUser", ex = ex }); return(""); } }
public async Task <dynamic> GetByAuthorId(string id) { var postCollection = MongoWrapper.Database.GetCollection <Models.Post>(nameof(Models.Post)); var postFilterBuilder = new FilterDefinitionBuilder <Models.Post>(); var postFilter = postFilterBuilder.And ( postFilterBuilder.Eq(p => p.Poster._id, new ObjectId(id)), GeneralUtils.NotDeactivated(postFilterBuilder) ); var postSortBuilder = new SortDefinitionBuilder <Models.Post>(); var postSort = postSortBuilder.Descending(p => p._id); var posts = (await postCollection.FindAsync(postFilter, new FindOptions <Models.Post> { AllowPartialResults = true, Sort = postSort })).ToList(); if (posts.Count > 0) { Models.User user = await RetrieveAuthor(posts.First()); posts.ForEach(p => EnrichPostWithAuthor(p, user)); return(new ResponseBody { Code = ResponseCode.GenericSuccess, Success = true, Message = "Posts encontrados com sucesso!", Data = posts.Select(post => post.BuildPostResponse()), }); } else { return(new ResponseBody { Code = ResponseCode.GenericSuccess, Success = true, Message = "Nenhum Post encontrado!", Data = Array.Empty <Models.Post>(), }); } }
/// <summary> /// 获取AdminMsg对象信息信息 /// </summary> /// <param name="code"></param> /// <param name="Pass"></param> /// <returns></returns> public Models.AdminMsg GetAdminMsg(string code, string Pass) { string IP = GetLocalIP(); Models.User user = this.GetUserInfo(code, Pass); AdminMsg msg = new AdminMsg(); msg.AdminGuid = user.UserGuid; msg.AdminLoginCode = user.UserCode; msg.AdminNickName = user.UserNickName; msg.AdminSex = user.UserSex; msg.Token = GetLoginToken(user.UserGuid, IP); msg.LoginTime = DateTime.Now; msg.LoginIP = IP; //用户行为记录 BOperation = new BOperationRecord(SqlConn); BOperation.RecordHandle(user.UserGuid, BOperationRecord.Level.Daily, string.Format("登入系统,IP:{0}", IP)); return(msg); }
public static User GetUser() { DatabaseContext db = new DatabaseContext(); if (HttpContext.Current.User.Identity.IsAuthenticated) { var identity = (System.Security.Claims.ClaimsIdentity)HttpContext.Current.User.Identity; Guid id = new Guid(identity.Name); Models.User user = db.Users.FirstOrDefault(current => current.Id == id); if (user != null) { return(user); } } return(new User()); }