public AspNetRoleModel(AspNetRole aspNetRole) { this.Id = aspNetRole.Id; this.Name = aspNetRole.Name; this.Level = aspNetRole.Level; this.Discriminator = aspNetRole.Discriminator; }
public ActionResult AddRole(AspNetRole role) { Security1Entities context = new Security1Entities(); context.AspNetRoles.Add(role); context.SaveChanges(); return View(); }
public IHttpActionResult PostAspNetRole(AspNetRole aspnetrole) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.AspNetRoles.Add(aspnetrole); try { db.SaveChanges(); } catch (DbUpdateException) { if (AspNetRoleExists(aspnetrole.Id)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = aspnetrole.Id }, aspnetrole); }
public AspNetRole toAspNetRole() { AspNetRole result = new AspNetRole(); result.Id = string.IsNullOrEmpty(this.Id) ? Guid.NewGuid().ToString() : this.Id; result.Name = this.Name; result.Level = this.Level; result.Discriminator = this.Discriminator; return result; }
public ActionResult AddRole(AspNetRole role) { var roleStore = new RoleStore<IdentityRole>(); var manager = new RoleManager<IdentityRole>(roleStore); var identityRole = new IdentityRole() { Name = role.Name }; IdentityResult result = manager.Create(identityRole); return View(); }
internal static void Create(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("CreateAdmin.Create should not be being used in a production environment - security changes required"); #endif if (!context.Roles.Any()) { var roleStore = new RoleStore<AspNetRole,Guid,AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole,Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessAllData }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessInstitution }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.SiteAdmin }; roleManager.Create(role); var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); foreach(var user in context.Users.Where(u=>u.Department.Institution.Name== "Starship").ToList()) { var result = userManager.AddPassword(userId: user.Id, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.AccessAllData); } else { throw new DbSeedException(result.Errors); } } } }
public bool UpdateRole(AspNetRole role) { try { string query = "update AspNetRoles set Name = @Name where Id = @Id"; int temp = connect.Execute(query, new { role.Name, role.Id }); if (temp > 0) { return(true); } } catch (Exception ex) { LogService.WriteException(ex); } return(false); }
public Task RemoveFromRoleAsync(AspNetUser user, string role) { this.ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException("Value Cannot Be Null Or Empty", "role"); } AspNetRole identityRole = this.Context.AspNetRoles.Where(o => o.Name.ToUpper() == role.ToUpper()).FirstOrDefault(); if (identityRole != null) { this.Context.Delete(identityRole); } return(Task.FromResult <int>(0)); }
public async Task <bool> CreateRoleAsync(string roleName, int createdByUser) { try { using (var db = new FutsalEntities()) { var aspnetrole = new AspNetRole() { Name = roleName, CreatedByUser = createdByUser, LastUpdatedByUser = createdByUser, CreatedDate = DateTime.Now, LastUpdatedDate = DateTime.Now }; db.AspNetRoles.Add(aspnetrole); await db.SaveChangesAsync(); return(true); } } catch (Exception ex) { return(false); } }
public async Task <ActionResult> Edit([Bind(Include = "Id,Name,DisplayName,LevelName,LevelId")] RoleViewModel roleVM) { if (ModelState.IsValid) { roleVM.setRoleName(roleVM.DisplayName, roleVM.LevelName); AspNetRole role = await db.AspNetRoles.FindAsync(roleVM.Id); role.Name = roleVM.Name; role.LevelId = roleVM.LevelId; db.Entry(role).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.Level = db.UserLevels; return(View(roleVM)); }
public int InsertRole(AspNetRole role) { try { string query = "insert into AspNetRoles(" + " Id,Name)" + " values (@Id,@Name)" + " SELECT @@IDENTITY"; int id = connect.Query <int>(query, new { role.Id, role.Name }).Single(); return(id); } catch (Exception ex) { LogService.WriteException(ex); return(0); } }
public IHttpActionResult Create(ApplicationRoleViewModel applicationRoleViewModel) { if (ModelState.IsValid) { var newAppRole = new AspNetRole(); newAppRole.UpdateApplicationRole(applicationRoleViewModel); try { AppRoleManager.Create(newAppRole); return(Ok(applicationRoleViewModel)); } catch (NameDuplicatedException) { return(BadRequest()); } } else { return(BadRequest()); } }
private static void CreateAdministratorAspNetGroup(UserManager <AspNetUser> userManager, RoleManager <AspNetRole> roleManager) { IdentityRepository repo = new IdentityRepository(context, userManager); AspNetGroup aspNetGroup = new AspNetGroup(); aspNetGroup.Name = "Administrator"; aspNetGroup.Description = "Administrator"; aspNetGroup.Active = true; var groupId = repo.AddGroup(aspNetGroup); AspNetRole adminRole = roleManager.FindByNameAsync("Administrator").Result; AspNetRoleGroup aspNetRoleGroup = new AspNetRoleGroup(); aspNetRoleGroup.GroupId = groupId; aspNetRoleGroup.RoleId = adminRole.Id; aspNetRoleGroup.Allow = true; repo.AddRoleToGroup(aspNetRoleGroup); }
public ActionResult Delete(AppUser appUser) { UpdateModel(appUser); AspNetRole role = roleService.GetRoleOfUser(appUser.Id); if (role != null) { if (role.Id == (int)Config.Roles.Student) { studentService.DeleteByUserID(appUser.Id); } else if (role.Id == (int)Config.Roles.Teacher) { teacherService.DeleteByUserID(appUser.Id); } roleService.DeleteAllRoleOfUser(appUser.Id); accountService.DeleteByPrimaryKey(appUser.Id); return(RedirectToAction("Index")); } return(View(appUser)); }
public void Edit(RoleModel roleModel) { try { if (Validate(roleModel)) { return; } AspNetRole aspNetRole = dbContext.AspNetRoles.Where(x => x.Id == roleModel.Id).FirstOrDefault(); if (aspNetRole == null) { base.HandleError(roleModel, CommonLayer.LookUps.ErrorType.Critical, null, Resources.NotFound); return; } //no need for below because cascading applied dbContext.AspNetRoleSiteMapNodes.RemoveRange(aspNetRole.AspNetRoleSiteMapNodes); aspNetRole.AspNetRoleSiteMapNodes.Clear(); RoleMapper.Map(roleModel, aspNetRole); dbContext.Entry(aspNetRole).State = EntityState.Modified; base.SaveChanges(); //remove all roles cache with sitemap nodes cache Common.Helpers.CacheHelper.RemoveCache(new CacheMemberKey() { CacheKey = LookUps.CacheKeys.Roles, ObjectId = LookUps.CacheKeys.Roles.ToString() }); roleModel.AddSuccess(Resources.RoleUpdatedSuccessfully, LookUps.SuccessType.Full); } catch (Exception ex) { base.HandleError(roleModel, CommonLayer.LookUps.ErrorType.Exception, ex); base.UndoUpdates(); } }
void SeedData() { using (var context = new AppDbContext(ContextOptions)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var user1 = new AspNetUser { Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******" }; var user2 = new AspNetUser { Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******" }; var role1 = new AspNetRole { Id = Guid.NewGuid().ToString(), Name = "Production" }; var role2 = new AspNetRole { Id = Guid.NewGuid().ToString(), Name = "Administration" }; var role3 = new AspNetRole { Id = Guid.NewGuid().ToString(), Name = "Development" }; var userRole1 = new AspNetUserRole { RoleId = role1.Id, UserId = user1.Id }; var userRole2 = new AspNetUserRole { RoleId = role2.Id, UserId = user2.Id }; var userRole3 = new AspNetUserRole { RoleId = role3.Id, UserId = user2.Id }; context.AspNetUsers.AddRange(user1, user2); context.AspNetRoles.AddRange(role1, role2, role3); context.AspNetUserRoles.AddRange(userRole1, userRole2, userRole3); context.SaveChanges(); if (context.AspNetUsers.Count() != 2 || context.AspNetRoles.Count() != 3 || context.AspNetUserRoles.Count() != 3) { throw new Exception(" database was not deleted correctly! "); } } }
protected async Task AddUserRoleAsync() { var item = User.AspNetUserRoles.FirstOrDefault(e => e.RoleId == RoleId); if (item != null) { RoleMessage = "Failed to add a new role, cannot be duplicated."; return; } if (!string.IsNullOrEmpty(RoleId)) { AspNetRole role = (await RoleDataService.GetRoleById(RoleId)); AspNetUserRole aspNetUserRole = new AspNetUserRole { UserId = User.Id, RoleId = RoleId, Role = role }; User.AspNetUserRoles.Add(aspNetUserRole); } else { RoleMessage = "Please select a role first before adding!"; } }
// //PartialAcc List public ActionResult _PartialAccList(string AppRoles) { List <AspNetUser> acl; List <AspNetUser> UsrList = new List <AspNetUser>(); if (AppRoles != null) { AspNetRole irole = this.db.AspNetRoles.Find(AppRoles); acl = this.db.AspNetUsers.ToList(); foreach (AspNetUser usr in acl) { if (this.UserManager.IsInRole(usr.Id, irole.Name)) { UsrList.Add(usr); } } } // db.AspNetRoles.FirstOrDefault(c => c.Id == roleID).AspNetUsers.ToList(); return(this.PartialView(UsrList)); }
public override OperationResult Execute(BlogEntities entities) { AspNetUser user = new AspNetUser { Email = this.Dto.Email, UserName = this.Dto.Username, PasswordHash = this.Dto.Password }; foreach (var role in Dto.Role) { AspNetRole r = new AspNetRole { Name = role.Name }; user.AspNetRoles.Add(r); } entities.AspNetUsers.Add(user); entities.SaveChanges(); return(base.Execute(entities)); }
string AddRole(string roleName) { string success = ""; try { using (AspNetContext db = new AspNetContext()) { var newRole = new AspNetRole(); newRole.Id = Guid.NewGuid().ToString(); newRole.Name = roleName; db.AspNetRoles.Add(newRole); db.SaveChanges(); success = "ok"; } } catch (Exception ex) { success = ex.Message; } return(success); }
public ActionResult Create([Bind(Include = "Id,Name")] AspNetRole aspNetRole) { var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>()); //string[] roleNames = { "Admin", "Member", "Moderator", "Junior", "Senior", "Candidate" }; IdentityResult roleResult; if (!RoleManager.RoleExists(aspNetRole.Name)) { roleResult = RoleManager.Create(new IdentityRole(aspNetRole.Name)); return(RedirectToAction("Index")); } //if (ModelState.IsValid) //{ // db.AspNetRoles.Add(aspNetRole); // db.SaveChanges(); // return RedirectToAction("Index"); //} return(View(aspNetRole)); }
public string GetOrganizationAdminRoleID() { //using (var dataContext = new WorkersInMotionDB()) //{ // return (from p in dataContext.AspNetRoles // where p.Name == "Organization Administrator" // select p.Id).SingleOrDefault(); //} SqlParameter[] Param = new SqlParameter[1]; Param[0] = new SqlParameter("@pName", SqlDbType.NVarChar, -1); Param[0].Value = "Organization Administrator"; AspNetRole role = context.Database.SqlQuery <AspNetRole>("Select * from AspNetRoles where Name=@pName", Param).FirstOrDefault(); if (role != null) { return(role.Id); } else { return(string.Empty); } }
//public int UpdateGroupGUID(Guid UserGUID, Guid GroupGUID) //{ // int result = 0; // using (var dataContext = new WorkersInMotionDB()) // { // var qry = from p in dataContext.GlobalUsers where p.UserGUID == UserGUID select p; // if (qry != null && qry.Count() > 0) // { // //var item = qry.Single(); // //item.GroupGUID = GroupGUID; // //result = dataContext.SaveChanges(); // } // } // return result; //} public string GetRoleID(string UserType) { //using (var dataContext = new WorkersInMotionDB()) //{ // return (from p in dataContext.AspNetRoles // where p.UserType == UserType // select p).SingleOrDefault().Id; //} SqlParameter[] Param = new SqlParameter[1]; Param[0] = new SqlParameter("@pUserType", SqlDbType.NVarChar, 10); Param[0].Value = UserType; AspNetRole role = context.Database.SqlQuery <AspNetRole>("Select * from AspNetRoles where UserType=@pUserType", Param).FirstOrDefault(); if (role != null) { return(role.Id); } else { return(string.Empty); } }
public IActionResult UpdateRole([FromBody] AspNetRole role) { if (role == null) { return(BadRequest()); } if (string.IsNullOrEmpty(role.Name)) { ModelState.AddModelError("Name", "The Role Name should not be empty!"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var roleToUpdate = _roleRepository.GetRoleById(role.Id); if (roleToUpdate == null) { return(NotFound()); } _roleRepository.UpdateRole(role); return(NoContent());//success }
/// <summary> /// This method adds a new role /// </summary> /// <param name="dvm"></param> /// <returns></returns> public async Task <bool> AddRole(AspNetRoleDVM dvm) { bool status = false; if (dvm != null) { AspNetRole a = mapper.Map <AspNetRole>(dvm); try { var result = await roleManager.CreateAsync(a); if (result.Succeeded) { status = true; } } catch (Exception ex) { throw ex; } } return(status); }
public Task AddToRoleAsync(AspNetUser user, string role) { this.ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException("Value Cannot Be Null Or Empty", "role"); } AspNetRole identityRole = this.Context.AspNetRoles.Where(o => o.Name == role).FirstOrDefault(); if (identityRole == null) { throw new InvalidOperationException(string.Format("Role not found", role)); } identityRole.AspNetUsers.Add(user); return(Task.FromResult <int>(0)); }
public async Task <IActionResult> CreateRole(AspNetRole role) { string accessToken = await HttpContext.GetTokenAsync("access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); if (ModelState.IsValid) { StringContent httpContent = new StringContent(role.ToJson(), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(_configuration["URLAPI"] + $"api/Admin/CreateRole", httpContent); if (response.StatusCode != HttpStatusCode.NoContent) { return(BadRequest()); } return(RedirectToAction(nameof(Roles))); } return(View()); }
public ActionResult Update(UpdateAccountViewModel model) { var result = new AjaxOperationResult(); try { var service = this.Service <IAspNetUserService>(); AspNetUser user = service.Get(model.Id); user.UserName = model.UserName; user.Email = model.Email; user.FullName = model.FullName; user.PhoneNumber = model.PhoneNumber; user.Address = model.Address; user.City = model.City; user.District = model.District; user.Ward = model.Ward; user.Birthday = model.Birthday; user.Gender = model.Gender; service.Update(user); var roleService = this.Service <IAspNetRoleService>(); AspNetRole newRole = roleService.Get(model.RoleId); var roles = UserManager.GetRoles(user.Id).ToArray(); //var oldRoles = Roles.GetRolesForUser(user.UserName); UserManager.RemoveFromRoles(user.Id, roles); UserManager.AddToRole(user.Id, newRole.Name); result.Succeed = true; } catch (Exception e) { result.Succeed = false; } return(Json(result)); }
public async Task <JsonResult> Editing(string id) { try { Session["RoleID"] = id; var aspNetRole = await db.AspNetRoles.FindAsync(id); AspNetRole rol = new AspNetRole() { Id = aspNetRole.Id, Name = aspNetRole.Name }; return(new JsonResult { Data = rol, MaxJsonLength = int.MaxValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } catch (Exception ex) { throw new Exception(string.Format("Error:[Editing] :: {0} ", ex.Message)); } }
// PUT: api/Roles/5 public IHttpActionResult Put([FromBody] AspNetRole role) { try { if (ModelState.IsValid) { var DbRole = db.Roles.Find(role.Id); if (DbRole == null) { return(NotFound()); } DbRole.Name = role.Name; db.SaveChanges(); return(Ok(role)); } return(BadRequest(ModelState)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
// GET: Role/Details/5 public async Task <ActionResult> Details(int id) { if (id <= 0) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } AspNetRole role = await db.AspNetRoles.FindAsync(id); RoleViewModel roleVM = new RoleViewModel(); if (role == null) { return(HttpNotFound()); } else { roleVM.Id = role.Id; roleVM.Name = role.Name; roleVM.LevelId = role.LevelId; roleVM.setDisplayName(role.Name); roleVM.LevelName = role.UserLevel.LevelName; } return(View(roleVM)); }
// PUT: odata/AspNetRoles(5) public async Task <IHttpActionResult> Put([FromODataUri] string key, Delta <AspNetRole> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } AspNetRole aspNetRole = await db.AspNetRoles.FindAsync(key); if (aspNetRole == null) { return(NotFound()); } patch.Put(aspNetRole); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AspNetRoleExists(key)) { return(NotFound()); } else { throw; } } return(Updated(aspNetRole)); }
public ActionResult AddRole(AspNetRole Ar) { if (ModelState.IsValid) { try { var context = new Models.ApplicationDbContext(); context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole() { Name = Ar.Name }); context.SaveChanges(); ViewBag.Message = "Role created successfully !"; return(RedirectToAction("Index", "Home")); } catch { return(View()); } } return(View(Ar)); }
private async Task <GNContact> InsertMainOrgContact(RegisterAccountViewModel model, AspNetUser aspNetUser, GNOrganization org) { GNContact mainOrgContact = null; try { //find ORG_MANAGER role AspNetRole aspNetRole = base.identityDB.AspNetRoles.Where(r => r.Name == "ORG_MANAGER").FirstOrDefault(); //insert Main Org Contact with ORG_MANAGER role mainOrgContact = new GNContact { AspNetUserId = aspNetUser.Id, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Title = model.Title, Phone = model.Phone, Fax = model.Fax, Website = model.Website, StreetAddress1 = model.StreetAddress1, StreetAddress2 = model.StreetAddress2, City = model.City, State = model.State, Zip = model.Zip, TermsAcceptDateTime = DateTime.Now, PrivacyPolicyAcceptDateTime = DateTime.Now, CreateDateTime = DateTime.Now, GNOrganizationId = org.Id, IsSubscribedForNewsletters = model.SignUpForNewsAndProducts }; mainOrgContact = await contactService.Insert(mainOrgContact); //Update Org org.GNContactId = mainOrgContact.Id; org.CreatedBy = mainOrgContact.Id; org = await organizationService.Update(org); if (org != null) { mainOrgContact.CreatedBy = mainOrgContact.Id; mainOrgContact.GNOrganizationId = org.Id; mainOrgContact.GNContactRoles = new List <GNContactRole>(); mainOrgContact.GNContactRoles.Add(new GNContactRole { AspNetRoleId = aspNetRole.Id, CreatedBy = mainOrgContact.Id, CreateDateTime = DateTime.Now }); mainOrgContact = await contactService.Update(org.OrgMainContact); } } catch (Exception ex) { var ex2 = new Exception("Unable to add Main Organization Contact.", ex); LogUtil.Error(logger, ex2.Message, ex2); throw ex2; } return(mainOrgContact); }
public ActionResult AddRole(AspNetRole role) { DeveloCurityBaseEntities context = new DeveloCurityBaseEntities(); context.AspNetRoles.Add(role); context.SaveChanges(); return View(); }
public ActionResult AddRole(AspNetRole role) { db.AspNetRoles.Add(role); db.SaveChanges(); return View(); }
public AspNetRole Find(string ID) { AspNetRole rol = db.AspNetRoles.Find(ID); return(rol); }
// PUT api/Roller/5 public IHttpActionResult PutAspNetRole(string id, AspNetRole aspnetrole) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != aspnetrole.Id) { return BadRequest(); } db.Entry(aspnetrole).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AspNetRoleExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public static AspNetRole CreateAspNetRole(global::System.Guid applicationId, global::System.Guid roleId, string roleName, string loweredRoleName) { AspNetRole aspNetRole = new AspNetRole(); aspNetRole.ApplicationId = applicationId; aspNetRole.RoleId = roleId; aspNetRole.RoleName = roleName; aspNetRole.LoweredRoleName = loweredRoleName; return aspNetRole; }
public RoleViewModels GetById(string id) { AspNetRole role = Repository.GetById(id); return(role == null ? null : Mapper.DataToModel(role)); }
public void AddToAspNetRoles(AspNetRole aspNetRole) { base.AddObject("AspNetRoles", aspNetRole); }
public ActionResult AddRole(AspNetRole role) { context.AspNetRoles.Add(role); context.SaveChanges(); return View(); }
public static void Seed(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("this should not be being used in a production environment - security changes required"); #endif try { if (!context.Roles.Any()) { //not in production //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, // "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate"); // var roleStore = new RoleStore<AspNetRole, Guid, AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole, Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.Admin }; roleManager.Create(role); } if (!context.Users.Any()) { var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); var user = new AspNetUser { Email = "*****@*****.**", UserName = "******" }; var result = userManager.Create(user, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.Admin); } else { throw new DbSeedException(result.Errors); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }