/// <summary> /// Creates a new instance of nearforums user with properties from a facebook User /// </summary> public static User CreateUser(dynamic facebookUser) { //Full facebook documentation: http://developers.facebook.com/docs/reference/api/user/ User user = new User(); user.UserName = facebookUser.first_name + " " + facebookUser.last_name; user.ExternalProfileUrl = facebookUser.link; user.Profile = facebookUser.about; #region Birthdate DateTime? birthDate = null; if (birthDate != null) { DateTime parsedBirthDate = DateTime.MinValue; if (DateTime.TryParse(facebookUser.birthday, new CultureInfo("en-US"), DateTimeStyles.AdjustToUniversal, out parsedBirthDate)) { birthDate = parsedBirthDate; } } user.BirthDate = birthDate; #endregion #region Timezone if (facebookUser.timezone != null) { user.TimeZone = TimeSpan.FromHours((double)facebookUser.timezone); } else { user.TimeZone = new TimeSpan(); } #endregion #region Picture user.Photo = String.Format("http://graph.facebook.com/{0}/picture?type=normal", facebookUser.id); #endregion return user; }
public User(User user) { Login = user.Login; FirstName = user.FirstName; LastName = user.LastName; Role = user.Role; Group = user.Group; }
public IHttpActionResult PostUser(User user) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Users.Add(user); try { db.SaveChanges(); } catch (DbUpdateException) { if (UserExists(user.carsite_id)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = user.carsite_id }, user); }
public VMQuickContact(User user) { FirstName = user.FirstName; LastName = user.LastName; Email = user.Email; UserId = user.Id; }
public void CalculateBadges(User user, List<BadgeType> badgeTypes) { foreach (var badgeType in badgeTypes) { this.badgeStrategyFactory.GetBadgeStrategy(badgeType).CalculateBadges(user, badgeType); } }
public HttpResponseMessage AddUser(UserSignUpViewModel userParam) { UserManager userManager = new UserManager(); HistoryManager historyManager = new HistoryManager(); try { var user = new User(); user.UserName = userParam.UserName; user.Password = userParam.Password; user.Email = userParam.Email; user.FirstName = userParam.FirstName; user.MiddleName = userParam.MiddleName; user.LastName = userParam.LastName; userManager.Create(user); var dbUser = userManager.FindUserEmail(user.Email); historyManager.AddHistory(new History(dbUser) { Activity = Activities.Joined, Description = Helper.GenerateActivityDescription(dbUser, Activities.Joined) }); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user); return response; } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } }
public IHttpActionResult PutUser(int id, User user) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != user.carsite_id) { return BadRequest(); } db.Entry(user).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!UserExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
private void CreateAndLoginUser() { if (!IsValid) { return; } try { var user = new User(userName.Text); var manager = new IdentityAuthenticationManagerSync(); if (manager.CreateAndSignInExternalUser(new HttpContextWrapper(Context), ProviderName, user)) { IdentityConfig.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ModelState.AddModelError(String.Empty, "There was an error processing this request."); return; } } catch (IdentityException e) { ModelState.AddModelError("", e.Message); } }
protected void Page_Load(object sender, EventArgs e) { if (!Permission.Check("user.read", true)) return; if (!Page.IsPostBack) { using (MooDB db = new MooDB()) { int userAID = int.Parse(Request["userA"]); int userBID = int.Parse(Request["userB"]); userA = (from u in db.Users where u.ID == userAID select u).SingleOrDefault<User>(); userB = (from u in db.Users where u.ID == userBID select u).SingleOrDefault<User>(); if (userA == null || userB == null) { PageUtil.Redirect(Resources.Moo.FoundNothing, "~/"); return; } BindDatas(db); Page.DataBind(); } } }
public void CanQueryFromMultipleSources() { using (var store = NewDocumentStore()) { using (var session = store.OpenSession()) { var user = new User { Name = "Ayende Rahien" }; session.Store(user); for (int i = 0; i < 5; i++) { session.Store(new Post { AuthorId = user.Id, Title = "blah" }); } session.SaveChanges(); } using (var session = store.OpenSession()) { var users = session.Query<User>().Customize(x => x.WaitForNonStaleResults()).Count(); var posts = session.Query<Post>().Customize(x => x.WaitForNonStaleResults()).Count(); Assert.Equal(1, users); Assert.Equal(5, posts); } } }
public User Update(User user) { this.users.Update(user); this.users.SaveChanges(); return user; }
public Radar(User owner) : base(owner.engine) { this.owner = owner; this.PopulateFunctions(); }
public PassOne(User user) { InitializeComponent(); //UserManager.CreateUser("Peter", "Varner-Howland", "pvarnerhowland", "testPass321"); //var user = UserManager.Authenticate("pvarnerhowland", "testPass321"); _myApp = new PassOneApp(this, user); }
public UserViewModel GetUser(User user) { var userViewModel = new UserViewModel(); userViewModel.Name = user.Name; userViewModel.Password = user.Password; return userViewModel; }
public User GetUserDomainModel(UserViewModel userViewModel) { var user = new User(); user.Name = userViewModel.Name; user.Password = userViewModel.Password; return user; }
public void Init(string email, IRepository repository) { if (!string.IsNullOrEmpty(email)) { User = repository.GetUser(email); } }
public static UserModel ToViewModel(this User a, User viewer, bool isOfficerAsking) { int privacyLevel = (viewer == null) ? 0 : viewer.PrivacyLevel; return new UserModel { Alias = a.Alias ?? a.Name, UserId = a.ID, Bio = a.Bio, BirthDate = (((a.PrivacyLevel < 2) || (privacyLevel < 2)) || !a.Birthdate.HasValue) ? null : (((a.PrivacyLevel < 3) || (privacyLevel < 3)) ? a.Birthdate.Value.ToString("MMMM dd") : a.Birthdate.Value.ToString("MMMM dd, yyyy")), Furcode = a.FurCode, InterestTags = a.Interests, Messenger1Id = (privacyLevel == 0) ? null : a.Messenger1ID, Messenger1Type = (privacyLevel == 0) ? null : a.Messenger1Type, Messenger2Id = (privacyLevel == 0) ? null : a.Messenger2ID, Messenger2Type = (privacyLevel == 0) ? null : a.Messenger2Type, Messenger3Id = (privacyLevel == 0) ? null : a.Messenger3ID, Messenger3Type = (privacyLevel == 0) ? null : a.Messenger3Type, Messenger4Id = (privacyLevel == 0) ? null : a.Messenger4ID, Messenger4Type = (privacyLevel == 0) ? null : a.Messenger4Type, Orientation = (privacyLevel == 0) ? null : (((string.Compare(a.Sex, "Female") == 0) && (string.CompareOrdinal(a.Orientation, "Gay") == 0)) ? "Lesbian" : a.Orientation), PrivacyLevel = a.PrivacyLevel, RelationshipStatus = (privacyLevel == 0) ? null : a.RelationshipStatus, Sex = a.Sex, Species = a.Species, SpeciesDetails = a.SpeciesDetails, Username = a.Name }; }
public ImageLinkImpl(User publisher, ImageFile file) { Publisher = publisher; File = file; _tags = new List<Tag>(); DateCreate = DateTime.Now; }
public User CreateUser(string username, string email, string password, int[] roles) { var existingUser = this.userRepository.GetSingleUserByName(username); if(existingUser != null) throw new ApplicationException("User exisits in the database"); var passwordSalt = this.encryptionService.CreateSalt(); var user = new User() { UserName = username, Email = email, IsLocked = false, Salt = passwordSalt, HashedPassword = encryptionService.EncryptPassword(password, passwordSalt), DateCreated = DateTime.Now }; this.userRepository.Add(user); unitofWork.Commit(); foreach (var aRole in roles) { this.AddUserToRole(user, aRole); } unitofWork.Commit(); return user; }
private void bindFace( User user ) { set( "profile", t2( new ProfileController().Main ) ); set( "user.Face", user.PicMedium ); set( "user.FriendCount", user.FriendCount ); set( "user.FollowingCount", user.FollowingCount ); set( "user.FollowersCount", user.FollowersCount ); set( "user.FriendLink", t2( new Users.FriendController().FriendList ) ); set( "user.FollowingLink", t2( new Users.FriendController().FollowingList ) ); set( "user.FollowerLink", t2( new Users.FriendController().FollowerList ) ); set( "user.AddFriendLink", t2( new FriendController().AddFriend, ctx.owner.Id ) ); set( "user.AddFollowLink", t2( new FriendController().AddFollow, ctx.owner.Id ) ); String lnkMsg = Link.To( new LinkController().NewMsg, ctx.owner.Id ); set( "sendMsgLink", lnkMsg ); String shareLink = Link.To( ctx.owner.obj, new wojilu.Web.Controller.ShareController().Add ); shareLink = shareLink + string.Format( "?url={0}&title={1}&pic={2}", getFullUrl( toUser( user ) ), "" + user.Name + " �Ŀռ�", user.PicOriginal ); set( "shareLink", shareLink ); bind( "user", user ); }
protected void btnUpdate_Click(object sender, EventArgs e) { User user = new User(); user.setId(Convert.ToInt32(hidUserID.Value)); user.setUsername(txtUsername.Text); user.setFirstName(txtFirstName.Text); user.setLastName(txtLastName.Text); user.setAddress(txtAddress.Text); user.setCity(txtCity.Text); user.setState(txtState.Text); user.setZipCode(txtZipCode.Text); user.setEmail(txtEmail.Text); user.setAccountCreationDate(DateTime.Parse(txtAccountCreationDate.Text)); UsersManager businesslayer = new UsersManager(); Boolean userUpdated = businesslayer.updateUserDetails(user); //ddlAccessLevel.ClearSelection(); Boolean accessLevelUpdated = businesslayer.updateUserAccessLevel(Convert.ToInt32(hidUserID.Value), Convert.ToInt32(ddlAccessLevel.SelectedValue)); if (userUpdated && accessLevelUpdated) { lblMsg.Text = "User updated successfuly!"; } else { lblMsg.Text = "Sorry, there was an error, please try again"; } }
private void _Setup() { User user1 = new User("User1"); User user2 = new User("User2"); User user3 = new User("User3"); _users = new List<User> {user1, user2, user3}; }
public void When(UserAttachedToRegistration e) { if (null == FirstUser) { FirstUser = new User(e.UserId, e.UserDisplay, e.Token); } }
public HistoryWindow() { InitializeComponent(); historial = new Historiales(); medic = new Medic(); user = new User(); history = new History(); medics = medic.GetAll(); users = user.GetAll(); histories = history.GetAll(); foreach (Usuarios user in users) { comboUsers.Items.Add(user.nombre + " " + user.apellidos); } foreach (Medicos medic in medics) { comboMedics.Items.Add(medic.nombre + " " + medic.apellidos); } historialGrid.ItemsSource = histories.ToArray(); }
public Purchase(int puchaseId, Cart cart, User user, DateTime date) { this.PurchaseID = puchaseId; this.articles = cart; this.User = user; this.Date = date; }
/// <summary> /// Adds a user to the system, and sets the <see cref="User.IsActivated"/> to true. /// </summary> /// <param name="email">The email or username.</param> /// <param name="password">The password.</param> /// <param name="isAdmin">if set to <c>true</c> the user is added as an admin.</param> /// <param name="isEditor">if set to <c>true</c> the user is added as an editor.</param> /// <returns> /// true if the user was added; false if the user already exists. /// </returns> /// <exception cref="SecurityException">An NHibernate (database) error occurred while adding the new user.</exception> public override bool AddUser(string email, string username, string password, bool isAdmin, bool isEditor) { try { User user = Users.FirstOrDefault(u => u.Email == email || u.Username == username); if (user == null) { user = new User(); user.Email = email; user.Username = username; user.SetPassword(password); user.IsAdmin = isAdmin; user.IsEditor = isEditor; user.IsActivated = true; NHibernateRepository.Current.SaveOrUpdate<User>(user); return true; } else { return false; } } catch (HibernateException ex) { throw new SecurityException(ex, "An error occurred while adding the new user {0}", email); } }
public void matches_credentials_negative() { var user1 = new User { UserName = "******", Password = theHash.CreateHash("something") }; var user2 = new User { UserName = "******", Password = theHash.CreateHash("else") }; theRepository.Update(user1); theRepository.Update(user2); theMembership.MatchesCredentials(new LoginRequest { UserName = "******", Password = "******" }).ShouldBeTrue(); theMembership.MatchesCredentials(new LoginRequest { UserName = "******", Password = "******" }).ShouldBeTrue(); }
public int CheckRole(User user) { var pass = encrypt(user.Password); var m = db.Users.Where(x => x.UserName == user.UserName && x.Password == pass && x.IdRole == 1).SingleOrDefault(); var n = db.Users.Where(x => x.UserName.Equals(user.UserName) && x.Password != user.Password && x.IdRole == 1).SingleOrDefault(); if (m!=null && m.LoginFail <= 3) { var p = decrypt(m.Password); FormsAuthentication.SetAuthCookie(m.UserName.ToString(), false); return 1; } else if (n != null && n.LoginFail < 3) { n.LoginFail++; db.SaveChanges(); return 0; } else if (m != null && m.LoginFail >= 3) { return 2; } else if (n != null && n.LoginFail >= 3) { return 3; } return 0; }
public void AddUser(FormCollection collection, User user) { UserBLL ub = new UserBLL(); String message=ub.AddNewUser(collection,user); Index(); }
/// <summary> /// Добавление юзера /// </summary> /// <param name="newU">новый юзер</param> /// <returns></returns> public bool AddUser(User newU) { using (var connection = new SqlConnection(ConnectionString())) { if (newU.Photo == null) { var command = new SqlCommand(); command = new SqlCommand( "INSERT INTO dbo.Users (Name, Birthdate, Age) " + "VALUES (@Name, @Birthdate, @Age)", connection); command.Parameters.AddWithValue("@Name", newU.Name); command.Parameters.AddWithValue("@Birthdate", newU.Birthdate); command.Parameters.AddWithValue("@Age", newU.Age); connection.Open(); return command.ExecuteNonQuery() == 1; } else { var command = new SqlCommand(); command = new SqlCommand( "INSERT INTO dbo.Users (Name, Birthdate, Age, Photo) " + "VALUES (@Name, @Birthdate, @Age, @Photo)", connection); command.Parameters.AddWithValue("@Name", newU.Name); command.Parameters.AddWithValue("@Birthdate", newU.Birthdate); command.Parameters.AddWithValue("@Age", newU.Age); command.Parameters.AddWithValue("@Photo", newU.Photo); connection.Open(); return command.ExecuteNonQuery() == 1; } } }
public void CreateRelations(User user, List <Tag> tags) { _usersRepository.CreateRelations(user, tags); }
public IResult Update(User user) { _userDal.Update(user); return(new SuccessResult(Messages.UserUpdated)); }
public IResult Delete(User user) { _userDal.Delete(user); return(new SuccessResult(Messages.UserDeleted)); }
public IResult Add(User user) { _userDal.Add(user); return(new SuccessResult(Messages.UserAdded)); }
public UserViewModel() { user = new User(); }
public UserDetailsViewModel(User user) { User = user; UpdateFriends(); UpdateRequests(); }
/// <summary> /// 更新玩家的当前信息 vip,战斗力,称号,奖章等 /// </summary> public void M_updateUserInfo() { User self = UserManager.Instance.self; int vipLv = self.getVipLevel(); int combat = ArmyManager.Instance.getTeamCombat(ArmyManager.PVP_TEAMID); LaddersTitleSample currentTitle = LaddersManagement.Instance.M_getCurrentPlayerTitle(); if (currentTitle != null) { label_title.text = LaddersManagement.Instance.M_getCurrentPlayerTitle().name; } else { label_title.text = Language("laddersTip_14"); } LaddersMedalSample currentMedal = LaddersManagement.Instance.M_getCurrentPlayerMedal(); if (currentMedal != null) { sprite_medalBg.spriteName = "medal_" + Math.Min(currentMedal.index + 1, 5); } else { sprite_medalBg.spriteName = "medal_0"; } label_userName.text = self.nickname; if (vipLv > 0) { sprite_vip.gameObject.SetActive(true); sprite_vip.spriteName = "vip" + vipLv; } else { sprite_vip.gameObject.SetActive(false); } label_level.text = "Lv." + self.getUserLevel().ToString(); label_rank.text = Language("laddersPrefix_01") + LaddersManagement.Instance.currentPlayerRank.ToString(); label_combat.text = Language("laddersPrefix_02") + combat.ToString(); //获取自身声望值 int myPrestige = UserManager.Instance.self.prestige; //通过自身声望值获取对应称号 LaddersTitleSample currentTitleSample = LaddersConfigManager.Instance.config_Title.M_getTitle(myPrestige); //通过自身称号获取下一级称号 LaddersTitleSample nextTitleSample = LaddersConfigManager.Instance.config_Title.M_getTitleByIndex(currentTitleSample.index + 1); //如果不存在下一级称号 if (nextTitleSample == null) { prestigeExpBar.updateValue(myPrestige, myPrestige); label_prestige.text = myPrestige + "/" + myPrestige; } //存在下一级称号 else { if (LaddersConfigManager.Instance.config_Title.isMaxIndex(currentTitleSample.index + 1)) { prestigeExpBar.updateValue(nextTitleSample.minPrestige, nextTitleSample.minPrestige); label_prestige.text = nextTitleSample.minPrestige + "/" + nextTitleSample.minPrestige; } else { prestigeExpBar.updateValue(myPrestige, nextTitleSample.minPrestige); label_prestige.text = myPrestige + "/" + nextTitleSample.minPrestige; } } label_laddersTimes.text = Language("laddersPrefix_04", (LaddersManagement.Instance.maxFightTime - LaddersManagement.Instance.currentChallengeTimes).ToString(), LaddersManagement.Instance.maxFightTime.ToString()); UserManager.Instance.setSelfHeadIcon(texture_userHead); LaddersRecordInfo lastRecord = LaddersManagement.Instance.Records.M_getLastRecord(); if (lastRecord != null) { label_lastRecord.text = lastRecord.description; } else { label_lastRecord.text = ""; } }
/// <summary> /// Get https://localhost:5001/home/Issue36 /// </summary> public IActionResult Issue36() { User user1; const string user1Name = "User1"; if (!_context.Users.Any(user => user.Name == user1Name)) { user1 = new User { Name = user1Name }; user1 = _context.Users.Add(user1).Entity; } else { user1 = _context.Users.First(user => user.Name == user1Name); } var product = new Product { ProductName = "P981122", IsActive = true, Notes = "Notes ...", ProductNumber = "098112", User = user1 }; product = _context.Products.Add(product).Entity; _context.SaveChanges(); // 1st query, reading from db var debugInfo1 = new EFCacheDebugInfo(); var firstQueryResult = _context.Products .Cacheable(debugInfo1) .FirstOrDefault(p => p.ProductId == product.ProductId); var debugInfoWithWhere1 = new EFCacheDebugInfo(); var firstQueryWithWhereClauseResult = _context.Products.Where(p => p.ProductId == product.ProductId) .Cacheable(debugInfoWithWhere1) .FirstOrDefault(); // Delete it from db, invalidates the cache on SaveChanges _context.Products.Remove(product); _context.SaveChanges(); // same query, reading from 2nd level cache? No. var debugInfo2 = new EFCacheDebugInfo(); var secondQueryResult = _context.Products .Cacheable(debugInfo2) .FirstOrDefault(p => p.ProductId == product.ProductId); // same query, reading from 2nd level cache? No. var debugInfo3 = new EFCacheDebugInfo(); var thirdQueryResult = _context.Products.Where(p => p.ProductId == product.ProductId) .Cacheable(debugInfo3) .FirstOrDefault(); // retrieving it directly from database var p98 = _context.Products.FirstOrDefault(p => p.ProductId == product.ProductId); return Json(new { firstQueryResult, isFirstQueryCached = debugInfo1, firstQueryWithWhereClauseResult, isFirstQueryWithWhereClauseCached = debugInfoWithWhere1, secondQueryResult, isSecondQueryCached = debugInfo2, thirdQueryResult, isThirdQueryCached = debugInfo3, directlyFromDatabase = p98 }); }
public List<OperationClaim> GetClaims(User user) { return _userDal.GetClaims(user); }
public static void ClassInitialize(TestContext context) { _telegramMessagesCount = 0; _config = new ComparisonConfig { CompareChildren = true, CompareFields = false, CompareReadOnly = true, ComparePrivateFields = false, ComparePrivateProperties = false, CompareProperties = true, MaxDifferences = 50, MembersToIgnore = new List<string> { "MessageId", "Date", "ForwardDate", "UpdateId" } }; var rm = new ResourceManager("CoffeeJelly.TelegramBotApiWrapperTests.Token", Assembly.GetExecutingAssembly()); var token = rm.GetString("testToken"); _telegramMethods = new TelegramMethods(token, true); var t = _telegramMethods.DeleteWebhook().Result; _privateChat = new Chat { Id = 170181775, FirstName = "Coffee", LastName = "Jelly", Username = "******", Type = ChatType.Private }; _botUser = new User { Id = 252886092, FirstName = "Gmail control bot", Username = "******" }; _italicTextEntity = new MessageEntity { Type = MessageEntityType.Italic, Offset = 0, Length = 23 }; _urlEntity = new MessageEntity { Type = MessageEntityType.Url, Offset = 0, Length = 21 }; _testUrlButton = new InlineKeyboardButton { Text = "URL Button", Url = "https://www.twitch.tv" }; _testCallbackDataButton = new InlineKeyboardButton { Text = "Callback Button", CallbackData = "Test callback data" }; _testInlineKeyboardMarkup = new InlineKeyboardMarkup { InlineKeyboard = new List<List<InlineKeyboardButton>> { new List<InlineKeyboardButton> { _testUrlButton, _testCallbackDataButton } } }; _testTextKeyboardButton = new KeyboardButton { Text = "Test keyboard button" }; _testContactKeyboardButton = new KeyboardButton { Text = "Test contact keyboard button", RequestContact = true }; _testReplyKeyboardMarkup = new ReplyKeyboardMarkup { Keyboard = new List<List<KeyboardButton>> { new List<KeyboardButton> { _testTextKeyboardButton, _testContactKeyboardButton, }, new List<KeyboardButton> { _testContactKeyboardButton } } }; _testReplyKeyboardRemove = new ReplyKeyboardRemove(); _testForceReply = new ForceReply(); _botStartCommandEntity = new MessageEntity { Type = MessageEntityType.BotCommand, Offset = 0, Length = 6 }; _user = new User { Id = 170181775, FirstName = "Coffee", LastName = "Jelly", Username = "******", LanguageCode = "en" }; _location = new Location { Latitude = 53.901112F, Longitude = 27.562325F }; _photoSize1 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABHFCoFI0_mWuqGEBAAEC", FileSize = 10311, Width = 160, Height = 160 }; _photoSize2 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABII7yIDVjT7yqWEBAAEC", FileSize = 22094, Width = 320, Height = 320 }; _photoSize3 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABEN3DhgGCbBFqmEBAAEC", FileSize = 57644, Width = 640, Height = 640 }; _userProfilePhotos = new UserProfilePhotos { TotalCount = 1, Photos = new List<List<PhotoSize>> { new List<PhotoSize> { _photoSize1, _photoSize2, _photoSize3 } } }; _file = new File { FileId = "CAADAgADLgADk35wS_5j0ImZMegiAg", }; _supergroupChat = new Chat { Id = -1001076966401, Title = "testgrp_new_title", Type = ChatType.Supergroup }; _testChannel = new Chat { Id = -1001114442404, Title = "TestChannel", Type = ChatType.Channel }; _userChatMember = new ChatMember { Status = ChatMemberStatus.Creator, User = _user }; _botChatMember = new ChatMember { Status = ChatMemberStatus.Administrator, User = _botUser }; _githubBot = new User { Id = 107550100, FirstName = "GitHub", Username = "******" }; _githubBotChatMember = new ChatMember { Status = ChatMemberStatus.Administrator, User = _githubBot }; }
protected override bool AuthenticateUser() { return (User.IsInRole(Constants.ROLE_ADMIN, compID)); }
public void ShouldFailWhenIDLessThan1OrGreaterThan4(int id) { Assert.ThrowsException <Exception>(() => { User user = new User(id); }); }
/// <summary> /// Add users to the group (helper for testability reasons) /// </summary> public virtual async void addUsers(string usersToAdd) { if (usersToAdd != "") { // separate input based on space char[] separators = { ' ', '\t', '\n' }; String[] users = usersToAdd.Split(separators); bool newUsers = false; GroupChat updatedGroup = null; // Look at each potential user foreach (String user in users) { // Add user to the group if a valid email address is provided and user is not already in group // possibly perform a different check here? (check database for matching email?) if (isValidEmail(user)) { // Need to perform check to see if email is in db User dbUser = await getUserFromEmail(user); //User dbUser = theUserFromEmail; // Display a dialog stating the user does not exist if (dbUser == null) { displayContentDialogDispatch(contentDialogType.DNE, user); } // Display a dialog stating the user has already been added to the group else if (group.group.GroupMembers.Contains(dbUser.id)) { displayContentDialogDispatch(contentDialogType.RepeatMember, user); } else { group.group.GroupMembers.Add(dbUser.id); //GroupChat updatedGroup = await GroupChatApi.getInstance().updateGroupChat(group); updatedGroup = await updateGroupChat(group.group); // Display a dialog stating the user is already in the group if (updatedGroup == null) { displayContentDialogDispatch(contentDialogType.NoServer, user); group.group.GroupMembers.Remove(dbUser.id); } else { displayContentDialogDispatch(contentDialogType.SuccessfulAdd, user); newUsers = true; } } } // Display a dialog stating the input is not a valid email address form else { displayContentDialogDispatch(contentDialogType.InvalidEmail, user); } } // after all users have been checked, if at least one was successful then we need to update // the views if (newUsers) { string members = await getGroupMemberNames(updatedGroup); GroupsContent updatedContent = new GroupsContent(updatedGroup, members); updatedContent.updateCanvasFrom(group); // call needed to update the group lists in the GroupsViewModel LeftFrameNavigator.Navigate(typeof(GroupsView), updatedContent); } } }
public void Add(User user) { _userDal.Add(user); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null, string loginProvider = null) { if ((!model.IsExistingUser && !(await _siteService.GetSiteSettingsAsync()).As <RegistrationSettings>().UsersCanRegister)) { _logger.LogInformation("Site does not allow user registration."); return(NotFound()); } ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = loginProvider; if (ModelState.IsValid) { IUser user = null; var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { throw new ApplicationException("Error loading external login information during confirmation."); } if (!model.IsExistingUser) { user = new User() { UserName = model.UserName, Email = model.Email }; user = await _userService.CreateUserAsync(user, model.Password, (key, message) => ModelState.AddModelError(key, message)); _logger.LogInformation(3, "User created an account with password."); } else { user = await _userManager.FindByNameAsync(model.UserName); } if (user != null) { var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (!signInResult.Succeeded) { user = null; ModelState.AddModelError(string.Empty, "Invalid login attempt."); } else { var identityResult = await _signInManager.UserManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); if (identityResult.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation(3, "User account linked to {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } AddErrors(identityResult); } } } return(View(nameof(ExternalLogin), model)); }
private async Task <ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model) { var result = new ProcessConsentResult(); var request = await _interaction.GetAuthorizationContextAsync(model.UserCode); if (request == null) { return(result); } ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = ConsentResponse.Denied; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested)); } // user clicked 'yes' - validate the data else if (model.Button == "yes") { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent)); } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.HandleRequestAsync(model.UserCode, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; result.ClientId = request.ClientId; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.UserCode, model); } return(result); }
public CompareExchange() { using (var store = new DocumentStore()) { { #region get_1 CompareExchangeValue<long> readResult = store.Operations.Send(new GetCompareExchangeValueOperation<long>("NextClientId")); long value = readResult.Value; #endregion } { #region get_2 CompareExchangeValue<User> readResult = store.Operations.Send(new GetCompareExchangeValueOperation<User>("AdminUser")); User admin = readResult.Value; #endregion } { #region get_list_2 Dictionary<string, CompareExchangeValue<string>> compareExchangeValues = store.Operations.Send( new GetCompareExchangeValuesOperation<string>(new[] { "Key-1", "Key-2" })); #endregion } { #region get_list_3 // Get values for keys that have the common prefix 'users' // Retrieve maximum 20 entries Dictionary<string, CompareExchangeValue<User>> compareExchangeValues = store.Operations.Send(new GetCompareExchangeValuesOperation<User>("users", 0, 20)); #endregion } { #region put_1 CompareExchangeResult<string> compareExchangeResult = store.Operations.Send( new PutCompareExchangeValueOperation<string>("Emails/[email protected]", "users/123", 0)); bool successful = compareExchangeResult.Successful; // If successfull is true: then Key '*****@*****.**' now has the value of "users/123" #endregion } { #region put_2 // Get existing value CompareExchangeValue<User> readResult = store.Operations.Send( new GetCompareExchangeValueOperation<User>("AdminUser")); readResult.Value.Age++; // Update value CompareExchangeResult<User> saveResult = store.Operations.Send( new PutCompareExchangeValueOperation<User>("AdminUser", readResult.Value, readResult.Index)); // The save result is successful only if 'index' wasn't changed between the read and write operations bool saveResultSuccessful = saveResult.Successful; #endregion } { #region delete_1 // First, get existing value CompareExchangeValue<User> readResult = store.Operations.Send( new GetCompareExchangeValueOperation<User>("AdminUser")); // Delete the key - use the index received from the 'Get' operation CompareExchangeResult<User> deleteResult = store.Operations.Send( new DeleteCompareExchangeValueOperation<User>("AdminUser", readResult.Index)); // The delete result is successful only if the index has not changed between the read and delete operations bool deleteResultSuccessful = deleteResult.Successful; #endregion } } }
public async Task <IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); // lookup our user and external provider info var(user, provider, providerUserId, claims) = await FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user var email = claims.FirstOrDefault(a => a.Type == ClaimTypes.Email); var firstname = claims.FirstOrDefault(a => a.Type == ClaimTypes.GivenName); var surname = claims.FirstOrDefault(a => a.Type == ClaimTypes.Surname); var phone = claims.FirstOrDefault(a => a.Type == ClaimTypes.MobilePhone); var dob = claims.FirstOrDefault(a => a.Type == ClaimTypes.DateOfBirth); var gender = claims.FirstOrDefault(a => a.Type == ClaimTypes.Gender); if (email == null) { return(BadRequest("Please setup an email for this account")); } user = new User { Email = email.Value, NormalizedEmail = email.Value.ToUpper(), UserName = email.Value, NormalizedUserName = email.Value.ToUpper(), SecurityStamp = Guid.NewGuid().ToString(), HasPassword = false }; var umResult = await _identityService.UserManager.CreateAsync(user); if (umResult.Succeeded) { user = await _identityService.UserManager.FindByEmailAsync(user.Email); await _identityService.UserManager.AddToRoleAsync(user, "user"); foreach (var c in claims) { await _identityService.UserManager.AddClaimAsync(user, c); } var userLoginInfo = new UserLoginInfo(provider, providerUserId, email.Value); await _identityService.UserManager.AddLoginAsync(user, userLoginInfo); await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; // issue authentication cookie with subject ID and username await HttpContext.SignInAsync(user.Id.ToString(), user.UserName, props); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl })); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(returnUrl)); } // request for a local page if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else if (string.IsNullOrEmpty(returnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List <Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id.ToString(), user.Email)); await HttpContext.SignInAsync(user.Id.ToString(), user.Email, provider, localSignInProps, additionalLocalClaims.ToArray()); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl })); } } return(Redirect(returnUrl)); }
private void CreateRolesAndUsers() { // Admin role var adminRole = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin); if (adminRole == null) { adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType<RolePermissionSetting>() .Where(p => p.TenantId == _tenantId && p.RoleId == adminRole.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new ASPNetCoreAngularAppAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = _tenantId, Name = permission.Name, IsGranted = true, RoleId = adminRole.Id }) ); _context.SaveChanges(); } // Admin user var adminUser = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == AbpUserBase.AdminUserName); if (adminUser == null) { adminUser = User.CreateTenantAdminUser(_tenantId, "*****@*****.**"); adminUser.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(adminUser, "123qwe"); adminUser.IsEmailConfirmed = true; adminUser.IsActive = true; _context.Users.Add(adminUser); _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id)); _context.SaveChanges(); // User account of admin user if (_tenantId == 1) { _context.UserAccounts.Add(new UserAccount { TenantId = _tenantId, UserId = adminUser.Id, UserName = AbpUserBase.AdminUserName, EmailAddress = adminUser.EmailAddress }); _context.SaveChanges(); } } }
public Deposit(decimal amount, User userFrom) : base(amount, userFrom) { }
/// <summary> /// Cleans up the service after MakeApiCall. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="parameters">The method parameters.</param> protected virtual void CleanupAfterCall(string methodName, object[] parameters) { User.CleanupListeners(); ContextStore.RemoveKey("SoapService"); ContextStore.RemoveKey("SoapMethod"); }
static void Main(string[] args) { Console.WriteLine("-----------------------------------Welcome to the E-Shop!-----------------------------------"); Console.WriteLine("-----------------------Please register , enter your desired username:-----------------------"); string username = Console.ReadLine(); #region Products Dictionary <Vendor, List <Product> > VendorsAndProducts = new Dictionary <Vendor, List <Product> >() { [new Vendor("Nike")] = new List <Product> { new Product("NIKE AIR MAX COMMAND LEATHER", 8000), new Product("NIKE METCON 4", 5000), new Product("NIKE FLYKNIT MAX", 12000), new Product("NIKE ODYSSEY REACT 2 FLYKNIT", 9500), new Product("NIKE AIR MAX 2016", 8500), new Product("NIKE AIR ZOOM PEGASUS 35", 10500) }, [new Vendor("SportVision")] = new List <Product> { new Product("ADIDAS BARRICADE 2018 CLAY", 5000), new Product("UA VERGE 2.0 MID GTX", 4500), new Product("UA CURRY 5", 7000), new Product("UA CHARGED ULTIMATE 3.0", 5700), new Product("UA NEWELL RIDGE LOW", 10000), new Product("NIKE AIR MAX 2018", 8500), new Product("UA SPEEDFORM GEMINI 3", 6000) }, [new Vendor("BuzzShop")] = new List <Product> { new Product("ADIDAS SOLAR BOOST M", 9500), new Product("ADIDAS ULTRABOOST", 8800), new Product("ADIDAS SPRINGBLADE SOLYCE M", 7000), new Product("ADIDAS BARRICADE 2018 CLAY", 7700), new Product("ADIDAS HARDEN VOL. 2", 10000), new Product("ADIDAS PUREBOOST XPOSE", 8500), new Product("ADIDAS CRAZY EXPLOSIVE 201", 6000) } }; #endregion User someUser = Methods.RegisterUser(username); Console.WriteLine("--------------------------Please choose one of the following actions:--------------------------"); Console.WriteLine("1.Get the full list of vendors"); Console.WriteLine("2.Search all products based on Vendors name with name and price"); Console.WriteLine("3.Create a new order by providing product code and quantity and add to user orders"); Console.WriteLine("4.Get state of shopping cart (name / quantity / price)"); Console.WriteLine("5.Remove existing order by index"); Console.WriteLine("6.Finish oreder with order receipt including username , products name quantity and price and total price"); Console.WriteLine("7.Exit shop"); Console.WriteLine("------------------------------------------------------------------------------------------------"); Methods.UsersActions(VendorsAndProducts, someUser); Console.ReadLine(); }
public UserPipeBind(User user) { _user = user; }
public void CanGetListOfDifferentAttachmentsAndRead(int count) { var attachmentDictionary = new Dictionary <string, MemoryStream>(); const string id = "users/1"; const string attachmentName = "Typical attachment name"; var factorials = new List <int>(); using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { var user = new User { Name = "su" }; session.Store(user, id); for (var i = 0; i < count; i++) { var factorial = AttachmentsStreamTests.Factorial(i); factorials.Add(factorial); var rnd = new Random(); var b = new byte[factorial]; rnd.NextBytes(b); var stream = new MemoryStream(b); session.Advanced.Attachments.Store(id, $"{attachmentName}_{i}", stream, "application/zip"); attachmentDictionary[$"{attachmentName}_{i}"] = stream; } session.SaveChanges(); } foreach (var stream in attachmentDictionary.Values) { stream.Position = 0; } using (var session = store.OpenSession()) { var user = session.Load <User>(id); var attachmentsNames = session.Advanced.Attachments.GetNames(user).Select(x => new AttachmentRequest(id, x.Name)); var attachmentsEnumerator = session.Advanced.Attachments.Get(attachmentsNames); int i = 0; while (attachmentsEnumerator.MoveNext()) { var size = factorials[i]; using (var memoryStream = new MemoryStream()) { var attachmentResult = attachmentsEnumerator.Current; Assert.NotNull(attachmentResult); attachmentResult.Stream.CopyTo(memoryStream); memoryStream.Position = 0; var buffer1 = new byte[size]; var buffer2 = new byte[size]; Assert.Equal(attachmentDictionary[$"{attachmentResult.Details.Name}"].Read(buffer1, 0, size), memoryStream.Read(buffer2, 0, size)); Assert.True(buffer1.SequenceEqual(buffer2)); attachmentResult.Stream?.Dispose(); i++; } } } } foreach (var stream in attachmentDictionary.Values) { stream.Dispose(); } }
public virtual async Task <ActionResult> Register(RegisterViewModel model) { try { CheckModelState(); //Create user var user = new User { Name = model.Name, Surname = model.Surname, EmailAddress = model.EmailAddress, IsActive = true }; //Get external login info if possible ExternalLoginInfo externalLoginInfo = null; if (model.IsExternalLogin) { externalLoginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { throw new ApplicationException("Can not external login!"); } user.Logins = new List <UserLogin> { new UserLogin { LoginProvider = externalLoginInfo.Login.LoginProvider, ProviderKey = externalLoginInfo.Login.ProviderKey } }; if (model.UserName.IsNullOrEmpty()) { model.UserName = model.EmailAddress; } model.Password = Authorization.Users.User.CreateRandomPassword(); if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase)) { user.IsEmailConfirmed = true; } } else { //Username and Password are required if not external login if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty()) { throw new UserFriendlyException(L("FormIsNotValidMessage")); } } user.UserName = model.UserName; user.Password = new PasswordHasher().HashPassword(model.Password); //Switch to the tenant _unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed? _unitOfWorkManager.Current.SetTenantId(AbpSession.GetTenantId()); //Add default roles user.Roles = new List <UserRole>(); foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync()) { user.Roles.Add(new UserRole { RoleId = defaultRole.Id }); } //Save user CheckErrors(await _userManager.CreateAsync(user)); await _unitOfWorkManager.Current.SaveChangesAsync(); //Directly login if possible if (user.IsActive) { AbpLoginResult <Tenant, User> loginResult; if (externalLoginInfo != null) { loginResult = await _logInManager.LoginAsync(externalLoginInfo.Login, GetTenancyNameOrNull()); } else { loginResult = await GetLoginResultAsync(user.UserName, model.Password, GetTenancyNameOrNull()); } if (loginResult.Result == AbpLoginResultType.Success) { await SignInAsync(loginResult.User, loginResult.Identity); return(Redirect(Url.Action("Index", "Home"))); } Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result); } //If can not login, show a register result page return(View("RegisterResult", new RegisterResultViewModel { TenancyName = GetTenancyNameOrNull(), NameAndSurname = user.Name + " " + user.Surname, UserName = user.UserName, EmailAddress = user.EmailAddress, IsActive = user.IsActive })); } catch (UserFriendlyException ex) { ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled; ViewBag.ErrorMessage = ex.Message; return(View("Register", model)); } }
/// <summary> /// Initializes the service before MakeApiCall. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="parameters">The method parameters.</param> protected virtual void InitForCall(string methodName, object[] parameters) { ContextStore.AddKey("SoapService", this); ContextStore.AddKey("SoapMethod", methodName); User.InitListeners(); }
public bool CanBeCancelledBy(User user) { return (user.IsAdmin || MadeBy == user); }
public UserPipeBind() { _id = 0; _login = null; _user = null; }
protected override IEnumerable <BaseItem> GetEligibleChildrenForRecursiveChildren(User user) { return(Tracks); }
private void CreateHostRoleAndUsers() { // Admin role for host var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin); if (adminRoleForHost == null) { adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin) { IsStatic = true, IsDefault = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role for host var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType <RolePermissionSetting>() .Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new ABP_CORE_MPAAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = null, Name = permission.Name, IsGranted = true, RoleId = adminRoleForHost.Id }) ); _context.SaveChanges(); } // Admin user for host var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName); if (adminUserForHost == null) { var user = new User { TenantId = null, UserName = AbpUserBase.AdminUserName, Name = "admin", Surname = "admin", EmailAddress = "*****@*****.**", IsEmailConfirmed = true, IsActive = true }; user.Password = new PasswordHasher <User>(new OptionsWrapper <PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe"); user.SetNormalizedNames(); adminUserForHost = _context.Users.Add(user).Entity; _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id)); _context.SaveChanges(); _context.SaveChanges(); } }