public RoleService(ApplicationRoleStore roleStore, IModuleService moduleService, IPermissionService permissionService, IDbServiceReposity dbServiceReposity) { _roleStore = roleStore; _moduleService = moduleService; _permissionService = permissionService; _dbServiceReposity = dbServiceReposity; }
public AccountController() { _userStore = new ApplicationUserStore(new ApplicationDbContext()); _userManager = new ApplicationUserManager(_userStore); _roleStore = new ApplicationRoleStore(new ApplicationDbContext()); _roleManager = new ApplicationRoleManager(_roleStore); }
private void CreateRole(string roleName, ApplicationContext context) { var store = new ApplicationRoleStore(context); var manager = new RoleManager <IdentityRole>(store); var role = new IdentityRole { Name = roleName }; manager.Create(role); }
static ApplicationDbContext CreateManagers(out WebApiUserManager userManager, out ApplicationRoleManager roleManager) { var context = ApplicationDbContext.Create(); var userStore = new ApplicationUserStore(context, App.Id); var roleStore = new ApplicationRoleStore(context, App.Id); userManager = new WebApiUserManager(userStore); roleManager = new ApplicationRoleManager(roleStore); return(context); }
internal static void SeedRole(this ApplicationDbContext context, string roleName) { if (!context.Roles.Any(r => r.Name == roleName)) { var store = new ApplicationRoleStore(context); var manager = new RoleManager <ApplicationRole>(store); var role = new ApplicationRole { Id = Guid.NewGuid().ToString(), Name = roleName }; manager.Create(role); } }
public void InitializeIdentityForEF() { var context = new ApplicationDbContext(); var roleStore = new ApplicationRoleStore(context); var roleManager = new ApplicationRoleManager(roleStore); var userStore = new ApplicationUserStore(context); var userManager = new ApplicationUserManager(userStore); const string adminUsername = "******"; const string password = "******"; const string adminRoleName = "Admin"; const string userRoleName = "User"; var adminRole = roleManager.FindByName(adminRoleName); if (adminRole == null) { adminRole = new ApplicationRole(adminRoleName); var roleResult = roleManager.Create(adminRole); } var userRole = roleManager.FindByName(userRoleName); if (userRole == null) { userRole = new ApplicationRole(userRoleName); var roleResult = roleManager.Create(userRole); } var adminUser = userManager.FindByName(adminUsername); if (adminUser == null) { adminUser = new ApplicationUser { UserName = adminUsername, Email = adminUsername }; var result = userManager.Create(adminUser, password); result = userManager.SetLockoutEnabled(adminUser.Id, false); } var rolesForUser = userManager.GetRoles(adminUser.Id); if (!rolesForUser.Contains(adminRole.Name)) { var result = userManager.AddToRole(adminUser.Id, adminRole.Name); } }
public static void SeedIdentityForEF(ApplicationDbContext context) { if ((!context.Roles.Any()) && (!context.Users.Any())) { var roleStore = new ApplicationRoleStore(context); //var roleManager = new RoleManager<ApplicationRole, int>(roleStore); var roleManager = new ApplicationRoleManager(roleStore); var role = new ApplicationRole { Name = "Admin", Description = "Super Admin User group" }; roleManager.Create(role); var userStore = new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context); var userManager = new ApplicationUserManager(userStore); var user = new ApplicationUser { Email = "*****@*****.**", UserName = "******", EmailConfirmed = true }; user.FirstName = "Jack"; user.LastName = "Smith"; userManager.Create(user, "P@ssword"); var result = userManager.SetLockoutEnabled(user.Id, false); userManager.AddToRole(user.Id, "Admin"); //added group manager var groupManager = new ApplicationGroupManager(roleManager,userManager); var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All"); groupManager.CreateGroup(newGroup); groupManager.SetUserGroups(user.Id, new int[] { newGroup.Id }); groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name }); } }
protected override void Seed(ApplicationDbContext context) { var rolestore = new ApplicationRoleStore(context); var rolemanager = new RoleManager <ApplicationRole>(rolestore); var userStore = new ApplicationUserStore(context); var usermanager = new ApplicationUserManager(userStore); var id1 = Guid.NewGuid().ToString(); var id2 = Guid.NewGuid().ToString(); var id3 = Guid.NewGuid().ToString(); var id4 = Guid.NewGuid().ToString(); usermanager.Create(new ApplicationUser() { Id = id1, UserName = "******", Email = "*****@*****.**", FirstName = "Admin", LastName = "User", Active = true }, "Developer1!"); usermanager.Create(new ApplicationUser() { Id = id2, UserName = "******", Email = "*****@*****.**", FirstName = "Default", LastName = "User", Active = true }, "Developer1!"); context.SaveChanges(); context.Roles.Add(new ApplicationRole() { Name = "Administrator", Id = Guid.NewGuid().ToString(), }); context.Roles.Add(new ApplicationRole() { Name = "Default User", Id = Guid.NewGuid().ToString(), }); context.SaveChanges(); usermanager.AddToRole(id1, "Administrator"); usermanager.AddToRole(id2, "Default User"); }
public async Task GetAllCoachesAsync_WithCorrectData_ShouldReturnCorrectResult() { var errorMessage = "CoachingService GetAllCoachesAsync() method does not work properly."; // Arrange var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var coachOrdersRepository = new EfRepository <CoachOrder>(context); var userStore = new ApplicationUserStore(context); var roleStore = new ApplicationRoleStore(context); var userManager = new UserManager <ApplicationUser>(userStore, null, null, null, null, null, null, null, null); var roleManager = new RoleManager <ApplicationRole>(roleStore, null, null, null, null); var coachingService = new CoachingService(userManager, coachOrdersRepository); var roleName = GlobalConstants.CoachRoleName; var role = new ApplicationRole { Id = Guid.NewGuid().ToString(), Name = roleName, }; var coach = new ApplicationUser { Id = Guid.NewGuid().ToString(), UserName = "******", }; // Act await roleManager.CreateAsync(role); await userManager.CreateAsync(coach); await userManager.AddToRoleAsync(coach, roleName); var actualResult = await coachingService.GetAllCoachesAsync(); var expectedResult = coach; // Assert Assert.True(actualResult.First().UserId == expectedResult.Id, errorMessage); Assert.True(actualResult.First().Username == expectedResult.UserName, errorMessage); }
public async Task <StatusCode> CreateRoleAsync(CreatePermViewModel model) { ApplicationRole role = new ApplicationRole() { Name = model.Name, Description = model.Description }; try { ApplicationRoleStore roleStore = new ApplicationRoleStore(_db); await roleStore.CreateAsync(role); return(StatusCode.CreateSuccess); } catch (Exception e) { return(StatusCode.ExceptionThrown); } }
public async Task <JsonResult> GetRoleMenusAsync(string roleId) { var store = new ApplicationRoleStore(_db); var role = await store.FindByIdAsync(roleId); if (role == null) { return(null); } var smh = role.MenuItems.Select(b => new MenusMenuItemVM() { MenuItemId = b.Id, MenuItemName = b.MenuTrail }) .ToList(); //Session["userMenus"] = new JavaScriptSerializer().Serialize(Json(smh, JsonRequestBehavior.AllowGet)); var son = Json(smh, JsonRequestBehavior.AllowGet); return(son); }
public async Task <StatusCode> ProcessRoleMenusAsync(string roleId, long[] menus) { try { var store = new ApplicationRoleStore(_db); var role = await store.FindByIdAsync(roleId); var currMenus = role.MenuItems.Select(a => a.Id).ToArray(); var addMenus = menus.Except(currMenus).ToArray(); var remMenus = currMenus.Except(menus).ToArray(); if (remMenus.Count() > 0) { foreach (var id in remMenus) { var mi = _db.MenuItems.Find(id); role.MenuItems.Remove(mi); } await store.UpdateAsync(role); } if (addMenus.Count() > 0) { foreach (var id in addMenus) { var mi = _db.MenuItems.Find(id); role.MenuItems.Add(mi); } await store.UpdateAsync(role); } return(StatusCode.UpdateSuccess); } catch { return(StatusCode.ExceptionThrown); } }
public void MyTestInitialize() { _context = ApplicationDbContext.Create(); _roleStore = new ApplicationRoleStore(_context); _sut = new ApplicationRoleManager(_roleStore); }
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleStore roleStore) { UserManager = userManager; SignInManager = signInManager; _roleStore = roleStore; }
public ApplicationRoleManager(ApplicationDbContext db) { _roleStore = new ApplicationRoleStore(db); }
public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context) { ApplicationRoleStore roleStore = new ApplicationRoleStore(context.Get <ApplicationDbContext>()); return(new ApplicationRoleManager(roleStore)); }
public async Task <RoleDetViewModel> GetRoleDetailsAsync(string id) { var store = new ApplicationRoleStore(_db); var role = await store.FindByIdAsync(id); if (role == null) { return(null); } var rolePerms = role.Permissions.Select(a => new PermsViewModel() { Id = a.Id, Name = a.Name, Checked = "checked" }).OrderBy(b => b.Name).ToList(); var allPerms = _db.Permissions.Select(a => new PermsViewModel() { Id = a.Id, Name = a.Name, Checked = "" }).ToList().Except(rolePerms).ToList(); var permissions = rolePerms.Union(allPerms).ToList(); var roleUsers = role.Users .Select(a => new UserDetViewModel() { Id = a.User.Id, UserName = a.User.UserName, Email = a.User.Email, FirstName = a.User.FirstName, LastName = a.User.LastName, Checked = "checked" }) .OrderBy(b => b.LastName) .ToList(); var allUsers = _db.Users .Select(a => new UserDetViewModel() { Id = a.Id, UserName = a.UserName, Email = a.Email, FirstName = a.FirstName, LastName = a.LastName, Checked = "" }) .ToList() .Except(roleUsers) .ToList(); var users = roleUsers.Union(allUsers).ToList(); var model = new RoleDetViewModel() { Id = role.Id, Name = role.Name, Description = role.Description, Users = users, Perms = permissions, ListUrl = "/Dashboard?sub=Roles" }; return(model); }
public ApplicationRoleManager(ApplicationRoleStore store) : base(store) { }
protected override void Seed(NSG.Identity.ApplicationDbContext context) { // // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. // // AspNet Identity // int _companyId = 1; var _uStore = new ApplicationUserStore(context); var _userManager = new ApplicationUserManager(_uStore); // Using ms default instance, ApplicationRoleManager was returning the following: // The entity type ApplicationRole is not part of the model for the current context. var _rStore = new ApplicationRoleStore(context); var _roleManager = new ApplicationRoleManager(_rStore); try { var _company = new Company() { CompanyShortName = "NSG", CompanyName = "Northern Software Group" }; context.Companies.AddOrUpdate(c => c.CompanyName, _company); context.SaveChanges(); _companyId = _company.CompanyId; // var _server = new ApplicationServer() { CompanyId = _companyId, ServerShortName = "NSG Memb", ServerName = "Members Web-site", ServerDescription = "Public facing members Web-site", WebSite = "Web-site address: www.mimilk.com", ServerLocation = "We are in Michigan, USA.", FromName = "Phil Huhn", FromNicName = "Phil", FromEmailAddress = "*****@*****.**", TimeZone = "EST (UTC-5)", DST = true, TimeZone_DST = "EDT (UTC-4)", DST_Start = new DateTime(2018, 3, 11, 2, 0, 0), DST_End = new DateTime(2018, 11, 4, 2, 0, 0) }; context.Servers.AddOrUpdate(s => s.ServerShortName, _server); context.SaveChanges(); } catch { } // var _rolePub = new ApplicationRole() { Id = "pub", Name = "Public" }; var _roleUsr = new ApplicationRole() { Id = "usr", Name = "User" }; var _roleAdm = new ApplicationRole() { Id = "adm", Name = "Admin" }; var _roleCAdm = new ApplicationRole() { Id = "cadm", Name = "CompanyAdmin" }; try { context.Roles.AddOrUpdate(r => r.Id, _rolePub); context.Roles.AddOrUpdate(r => r.Id, _roleUsr); context.Roles.AddOrUpdate(r => r.Id, _roleAdm); context.Roles.AddOrUpdate(r => r.Id, _roleCAdm); } catch { } // // Network Incident // try { context.NoteTypes.AddOrUpdate(t => t.NoteTypeId, new NoteType() { NoteTypeId = 1, NoteTypeDesc = "Ping", NoteTypeShortDesc = "Ping" }, new NoteType() { NoteTypeId = 2, NoteTypeDesc = "WhoIs", NoteTypeShortDesc = "WhoIs" }, new NoteType() { NoteTypeId = 3, NoteTypeDesc = "Abuse Report to ISP", NoteTypeShortDesc = "ISP Rpt" }, new NoteType() { NoteTypeId = 4, NoteTypeDesc = "Additional Communication from ISP", NoteTypeShortDesc = "ISP Addl" }, new NoteType() { NoteTypeId = 5, NoteTypeDesc = "ISP Response", NoteTypeShortDesc = "ISP Resp" } ); context.SaveChanges(); } catch { } // try { context.NICs.AddOrUpdate(t => t.NIC_Id, new NIC() { NIC_Id = "afrinic.net", NICDescription = "Africian Network Information Centre", NICAbuseEmailAddress = " ", NICRestService = "http://www.afrinic.net/", NICWebSite = "http://www.afrinic.net/" }, new NIC() { NIC_Id = "apnic.net", NICDescription = "Asian-Pacfic Network Information Centre", NICAbuseEmailAddress = "*****@*****.**", NICRestService = "https://wq.apnic.net/whois-search/static/search.html?query=", NICWebSite = " " }, new NIC() { NIC_Id = "arin.net", NICDescription = "Americian (North) Registry of Internet Numbers", NICAbuseEmailAddress = "*****@*****.**", NICRestService = "http://whois.arin.net/rest/ip/", NICWebSite = "https://www.arin.net/" }, new NIC() { NIC_Id = "lacnic.net", NICDescription = "Latin America and Caribbean Network Information Centre", NICAbuseEmailAddress = "*****@*****.**", NICRestService = "https://rdap.lacnic.net/rdap-web/home", NICWebSite = "http://www.lacnic.net/web/lacnic/inicio" }, new NIC() { NIC_Id = "jpnic.net", NICDescription = "Japan", NICAbuseEmailAddress = " ", NICRestService = "https://wq.apnic.net/whois-search/static/search.html?query=", NICWebSite = " " }, new NIC() { NIC_Id = "nic.br", NICDescription = "Brazilian Network Information Center", NICAbuseEmailAddress = "*****@*****.**", NICRestService = "https://registro.br/2/whois?query=", NICWebSite = " " }, new NIC() { NIC_Id = "ripe.net", NICDescription = "Réseaux IP Européens Network Coordination Centre (Europe)", NICAbuseEmailAddress = "*****@*****.**", NICRestService = "https://apps.db.ripe.net/db-web-ui/#/query?searchtext=", NICWebSite = "https://www.ripe.net/" }, new NIC() { NIC_Id = "twnic.net", NICDescription = "Taiwan NIC", NICAbuseEmailAddress = " ", NICRestService = "https://www.twnic.net.tw/en_index.php", NICWebSite = "https://www.twnic.net.tw/" }, new NIC() { NIC_Id = "hostwinds.com", NICDescription = "hostwinds NIC", NICAbuseEmailAddress = " ", NICRestService = " ", NICWebSite = "https://www.hostwinds.com/" }, new NIC() { NIC_Id = "unknown", NICDescription = "Unknown", NICAbuseEmailAddress = " ", NICRestService = " ", NICWebSite = " " }, new NIC() { NIC_Id = "other", NICDescription = "Other", NICAbuseEmailAddress = " ", NICRestService = " ", NICWebSite = " " } ); context.SaveChanges(); } catch { } // try { context.IncidentTypes.AddOrUpdate(t => t.IncidentTypeId, new IncidentType() { IncidentTypeId = 1, IncidentTypeShortDesc = "Unk", IncidentTypeDesc = "Unknown", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "Unknown probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network.\\nPlease contain the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 2, IncidentTypeShortDesc = "Multiple", IncidentTypeDesc = "Multiple Types", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "Network abuse from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network, probing for multiple vulnerabilities.\\nPlease contain the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\nIncident times:", IncidentTypeTimeTemplate = "${IncidentTypeShortDesc}: ${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 3, IncidentTypeShortDesc = "SQL", IncidentTypeDesc = "SQL Injection", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "SQL Injection probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}. This is testing SQL injection vulnerabilities.\\nPlease contain the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\n\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 4, IncidentTypeShortDesc = "PHP", IncidentTypeDesc = "PHP", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "PHP probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network, probing for ${IncidentTypeDesc} vulnerabilities.\\nPlease use the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\n\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 5, IncidentTypeShortDesc = "XSS", IncidentTypeDesc = "Cross Site Scripting", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "XSS probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network, probing for ${IncidentTypeDesc} vulnerabilities.\\nPlease use the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\n\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 6, IncidentTypeShortDesc = "VS", IncidentTypeDesc = "ViewState", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "ViewState probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network, probing for ${IncidentTypeDesc} vulnerabilities.\\nPlease use the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\n\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 7, IncidentTypeShortDesc = "DIR", IncidentTypeDesc = "Directory traversal", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "Directory traversal probe from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\\n\\nStop the intrusion from your IP address ${IPAddress}.\\nThe following IP address probe my network, probing for ${IncidentTypeDesc} vulnerabilities.\\nPlease use the following reference # in all communications: ${IncidentId}\\n\\n${Device}\\n${ServerLocation}\\n\\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" }, new IncidentType() { IncidentTypeId = 8, IncidentTypeShortDesc = "DoS", IncidentTypeDesc = "Denial-of-service attack", IncidentTypeFromServer = true, IncidentTypeSubjectLine = "Denial-of-service attack from ${IPAddress}", IncidentTypeEmailTemplate = "Hi\n\nStop the intrusion from your IP address ${IPAddress}. This is a DoS, affecting by my router.\nPlease contain the following reference # in all communications: ${IncidentId}\n\n${Device}\n${ServerLocation}\n\nIncident times:", IncidentTypeTimeTemplate = "${NetworkLogDate} ${TimeZone}", IncidentTypeThanksTemplate = "\\nThank you,\\n${FromName}\\n================", IncidentTypeLogTemplate = "\\n${Log}\\n--------------------------------", IncidentTypeTemplate = "-" } ); context.SaveChanges(); } catch (DbEntityValidationException _entityEx) { // extension method string _errors = _entityEx.EntityValidationErrors.GetDbValidationErrors(); System.Diagnostics.Debug.WriteLine(_errors); throw new DbEntityValidationException(_errors); } catch (Exception _ex) { throw (_ex); } // // Add a couple of fake network incident logs. // if (context.NetworkLogs.Count() == 0) { try { DateTime _dt = DateTime.Now.AddDays(-1); int _incTypeSql = 3; context.NetworkLogs.AddOrUpdate(n => n.NetworkLogId, new NetworkLog() { ServerId = 1, IncidentId = null, IPAddress = "94.41.54.105", NetworkLogDate = _dt.AddMilliseconds(15), Log = "Fake log 1, Fake log 1, Fake log 1", IncidentTypeId = _incTypeSql }, new NetworkLog() { ServerId = 1, IncidentId = null, IPAddress = "104.42.229.49", NetworkLogDate = _dt.AddMinutes(4), Log = "Fake log 2, Fake log 2, Fake log 2", IncidentTypeId = _incTypeSql }, new NetworkLog() { ServerId = 1, IncidentId = null, IPAddress = "104.42.229.49", NetworkLogDate = _dt.AddMinutes(5), Log = "Fake log 3, Fake log 3, Fake log 3", IncidentTypeId = _incTypeSql }, new NetworkLog() { ServerId = 1, IncidentId = null, IPAddress = "54.183.209.144", NetworkLogDate = _dt.AddMinutes(10), Log = "Fake log 4, Fake log 4, Fake log 4", IncidentTypeId = _incTypeSql } ); context.SaveChanges(); } catch (DbEntityValidationException _entityEx) { // extension method string _errors = _entityEx.EntityValidationErrors.GetDbValidationErrors(); System.Diagnostics.Debug.WriteLine(_errors); } catch (Exception _ex) { System.Diagnostics.Debug.WriteLine(_ex.ToString()); } } // }
public RoleManager(ApplicationRoleStore roleStore) : base(roleStore) { }
protected override void Seed(spsServerAPI.Models.ApplicationDbContext context) { //spsServerAPI.Models.Model spsdb = new Model(); #region setup Roles const string adminName = "*****@*****.**"; const string password = "******"; string[] roleNames = new string[4] { "admin", "student", "tutor", "unapproved" }; var roleStore = new ApplicationRoleStore(context); var roleManager = new ApplicationRoleManager(roleStore); foreach (string roleName in roleNames) { var role = roleManager.FindByName(roleName); if (role == null) { role = new ApplicationRole(roleName); var roleresult = roleManager.Create(role); } } #endregion #region Create Admin Account //Create admin user var userStore = new ApplicationUserStore(context); var userManager = new ApplicationUserManager(userStore); var user = userManager.FindByName(adminName); if (user == null) { user = new ApplicationUser { UserName = adminName, FirstName = "Paul", SecondName = "Powell", Approved = true, ProgrammeStageID = 0, Email = adminName }; var result = userManager.Create(user, password); result = userManager.SetLockoutEnabled(user.Id, false); } //Add user admin to Role Admin if not already added var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(roleNames[0])) { var result = userManager.AddToRole(user.Id, roleNames[0]); } #endregion #region Create student test accounts PasswordHasher p = new PasswordHasher(); string adminPass = p.HashPassword("Admin$1"); // Create 10 test users: Random r = new Random(); // int count = 0; //spsdb.ProgrammeStages.CountAsync().ContinueWith((cont) => { count = cont.Result; }); for (int i = 0; i < 10; i++) { var student = new ApplicationUser() { UserName = string.Format("S000009{0}@mail.itsligo.ie", i.ToString()), PasswordHash = p.HashPassword("S000009" + i.ToString()), Email = string.Format("S000009{0}@mail.itsligo.ie", i.ToString()), Approved = false, FirstName = "Student First name " + i.ToString(), SecondName = "Student Second name " + i.ToString(), //ProgrammeStageID = r.Next(1, count), LockoutEnabled = false }; //spsdb.Students.Add(new Student { SID = string.Format("S000009{0}", i.ToString()) }); IdentityResult studentResult = userManager.Create(student); if (studentResult.Succeeded) { var rolesForStudent = userManager.GetRoles(student.Id); if (rolesForStudent == null || !rolesForStudent.Contains(roleNames[3])) { var result = userManager.AddToRole(student.Id, roleNames[3]); } } } #endregion #region Create Tutors //Create Tutors for (int i = 0; i < 4; i++) { var tutor = new ApplicationUser() { UserName = string.Format("tutor{0}@mail.itsligo.ie", i.ToString()), FirstName = "Tutor First name " + i.ToString(), SecondName = "Tutor Second name " + i.ToString(), PasswordHash = p.HashPassword("Tutor$" + i.ToString()), Email = string.Format("tutor{0}@mail.itsligo.ie", i.ToString()), Approved = true, LockoutEnabled = false }; userManager.Create(tutor); // manager.Create(user, string.Format("S000009{0}", i.ToString())); var rolesForTutor = userManager.GetRoles(tutor.Id); if (rolesForTutor == null || !rolesForTutor.Contains(roleNames[2])) { var result = userManager.AddToRole(tutor.Id, roleNames[2]); } } #endregion if (context.Clients.CountAsync().Result > 0) { return; } context.Clients.AddRange(BuildClientsList()); context.SaveChanges(); } // End Seed
public RoleRepository(DbContext context) : base(context) { _store = new ApplicationRoleStore(context); _manager = new ApplicationRoleManager(_store); }
public RoleRepository() { _store = new ApplicationRoleStore(); _roleManager = new ApplicationRoleManager(_store); }