public async Task <IActionResult> OnPostAsync(string id) { if (id == null) { return(NotFound()); } AspNetRoles = await _context.AspNetRoles.FindAsync(id); if (AspNetRoles != null) { _context.AspNetRoles.Remove(AspNetRoles); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public override OperationResult execute(CimetEntities entities) { AspNetRoles role = entities.AspNetRoles.Where(r => r.Id == Role.Uuid).FirstOrDefault(); if (role != null) { role.Name = Role.Name; entities.SaveChanges(); return(base.execute(entities)); } OperationResult result = new OperationResult(); result.Status = false; result.Message = "Uloga ne postoji."; return(result); }
public ActionResult Create(AspNetRoles aspNetRoles) { try { using (DbModels dbModels = new DbModels()) { dbModels.AspNetRoles.Add(aspNetRoles); dbModels.SaveChanges(); } return(RedirectToAction("Index")); } catch { return(View()); } }
public bool UpdateTask(AspNetRoles objUpdate) { StackFrame stackFrame = new StackFrame(); MethodBase methodBase = stackFrame.GetMethod(); int rowEffected = 0; try { if (objUpdate != null) //Definsive Programming { OpenEntityConnection(); AspNetRoles ObjForUpdate = (from objLinq in objPharmaEntities.AspNetRoles where objLinq.Id == objUpdate.Id select objLinq).FirstOrDefault(); if (ObjForUpdate != null) { ObjForUpdate.Name = objUpdate.Name; ObjForUpdate.AppearAllEmp = objUpdate.AppearAllEmp; rowEffected = objPharmaEntities.SaveChanges(); } } } catch (Exception ex) { catchEntityvalidation((System.Data.Entity.Validation.DbEntityValidationException)ex, System.Runtime.InteropServices.Marshal.GetExceptionCode().ToString(), this.UserNameProperty.ToString(), this.GetType().Name.ToString(), methodBase.Name.ToString()); rowEffected = -1; ex.InnerException.Message.ToString(); } finally { CloseEntityConnection(); } if (rowEffected > 0) { return(true); } else { return(false); } }
/* EFECTO: Muestra la vista para crear una solicitud de cambio * REQUIERE: Selecionar un requerimiento previamente (id y version) * MODIFICA: N/A */ public ActionResult Create(string id, int version) { var cambio = new CAMBIOS(); var correoUsuario = db.CORREOS.Where(s => s.CORREO == User.Identity.Name).Single(); USUARIOS actual = correoUsuario.USUARIOS; int v = db.REQUERIMIENTOS.Where(s => s.ID == id).Select(s => s.VERSION_ID).Max() + 1; REQUERIMIENTOS rEQUERIMIENTOS = db.REQUERIMIENTOS.Find(id, version); rEQUERIMIENTOS.VERSION_ID = v; rEQUERIMIENTOS.ESTADO_CAMBIOS = "Pendiente"; cambio.USUARIOS = actual; cambio.CEDULA = actual.CEDULA; cambio.FECHA = DateTime.Now; cambio.REQUERIMIENTOS1 = rEQUERIMIENTOS; cambio.VIEJO_REQ_ID = id; cambio.VIEJO_VER_ID = version; cambio.NUEVO_REQ_ID = id; cambio.NUEVO_VER_ID = v; ViewBag.PRYCTOID = new SelectList(db.PROYECTO, "ID", "NOMBRE", rEQUERIMIENTOS.PRYCTOID); ViewBag.ENCARGADO = new SelectList(db.USUARIOS.Where(s => s.PRYCTOID == rEQUERIMIENTOS.PRYCTOID), "CEDULA", "NOMBRE", rEQUERIMIENTOS.ENCARGADO); var fg = new AspNetUsers(); //instancia AspNetUser para usuario actual var listauser = db.AspNetUsers.ToArray(); for (int i = 0; i < listauser.Length; i++) { //de todos los AspNetUser del sistema, encuentra el usuario activo actualmente if (listauser[i].Email == User.Identity.Name) { fg = listauser[i]; //obtiene el AspNetUser actual } } AspNetRoles rol = fg.AspNetRoles.First(); if (rol.Name == "Desarrollador" || rol.Name == "Administrador") { TempData["Desarrollador"] = "display:true"; } else { TempData["Desarrollador"] = "display:none"; } return(View(cambio)); }
public async Task <IActionResult> Index([FromRoute] string id) { AspNetRoles dbItem = null; if (!string.IsNullOrWhiteSpace(id)) { dbItem = await _context.AspNetRoles.AsNoTracking().FirstOrDefaultAsync(h => h.Id == id); if (dbItem == null) { return(NotFound()); } } ViewData["ParentItem"] = dbItem; ViewData["ControllerNameForGrid"] = nameof(RoleController).Replace("Controller", ""); return(View()); }
// GET: AspNetRoles/Edit/5 public ActionResult Edit(int id) { if (id == 0) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } AspNetRoles aspNetRoles = db.AspNetRoles.Find(id); if (aspNetRoles == null) { return(HttpNotFound()); } AspNetRoles role = new AspNetRoles(); role.Id = aspNetRoles.Id; role.Name = aspNetRoles.Name.Trim(); return(View(role)); }
/// <summary> /// Bặt tắt quyền /// </summary> /// <param name="roleID"></param> /// <param name="check"></param> /// <returns></returns> public object ApprovedRole(string roleID, bool check, string userName) { try { AspNetRoles aspNetRole = dbContext.AspNetRoles.Where(x => x.Id == roleID && !x.IsDeleted).FirstOrDefault(); if (aspNetRole != null) { aspNetRole.IsEnable = check; aspNetRole.UpdatedBy = userName; aspNetRole.UpdatedDate = DateTime.Now; dbContext.SaveChanges(); } return(MP_AjaxError.OK); } catch (System.Exception ex) { return(ex); } }
public override OperationResult execute(CimetEntities entities) { base.criteria.Uuid = Uuid; AspNetRoles role = entities.AspNetRoles.Where(r => r.Id == Uuid && r.AspNetUsers.Count() == 0).FirstOrDefault(); if (role != null) { entities.AspNetRoles.Remove(role); entities.SaveChanges(); return(base.execute(entities)); } else { OperationResult result = new OperationResult(); result.Status = false; result.Message = "Uloga ne postoji ili sadrzi korisnike!"; return(result); } }
private AspNetRoles GetRoleById(string id) { AspNetRoles aux = new AspNetRoles(); using (var cl = new HttpClient()) { cl.BaseAddress = new Uri(baseurl); cl.DefaultRequestHeaders.Clear(); cl.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage res = cl.GetAsync("api/AspNetRoles/" + id).Result; if (res.IsSuccessStatusCode) { var auxres = res.Content.ReadAsStringAsync().Result; aux = JsonConvert.DeserializeObject <AspNetRoles>(auxres); } } return(aux); }
public List <AspNetRoles> GetAll() { StackFrame stackFrame = new StackFrame(); MethodBase methodBase = stackFrame.GetMethod(); List <AspNetRoles> objlist = new List <AspNetRoles>(); try { OpenEntityConnection(); List <AspNetRoles> objectList = (from objLinq in objPharmaEntities.AspNetRoles select objLinq).ToList(); if (objectList != null) { foreach (var obj in objectList) { AspNetRoles obj1 = new AspNetRoles(); obj1.Id = obj.Id; obj1.Name = obj.Name; obj1.AppearAllEmp = obj.AppearAllEmp; objlist.Add(obj1); } } return(objlist); } catch (Exception ex) { catchEntityvalidation((System.Data.Entity.Validation.DbEntityValidationException)ex, System.Runtime.InteropServices.Marshal.GetExceptionCode().ToString(), this.UserNameProperty.ToString(), this.GetType().Name.ToString(), methodBase.Name.ToString()); ex.InnerException.Message.ToString(); return(null); } finally { CloseEntityConnection(); } }
// GET: AspNetRoles/Delete/5 public ActionResult DeleteRole(string id) { if (User.Identity.IsAuthenticated) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } AspNetRoles aspNetRoles = db.AspNetRoles.Find(id); if (aspNetRoles == null) { return(HttpNotFound()); } return(View(aspNetRoles)); } else { return(RedirectToAction("Login", "Account")); } }
// Creates roles in DB if not exists, roles are in appsettings.json public void CreateRoles() { List <AspNetRoles> roles = context.AspNetRoles.ToList(); var obj = Configuration.GetSection("Roles"); var rolesArr = obj.Get <string[]>(); for (int i = 0; i < rolesArr.Length; i++) { if (roles.Where(x => x.Name == rolesArr[i]).ToList().Count() == 0) { AspNetRoles role = new AspNetRoles(); role.Name = rolesArr[i]; role.NormalizedName = rolesArr[i].ToUpper(); role.ConcurrencyStamp = Guid.NewGuid().ToString(); role.Id = Guid.NewGuid().ToString(); context.Add(role); } } context.SaveChanges(); }
public bool DeleteRoles(string id, AspNetRoles st) { try { var Entity = _entities.AspNetUsers.FirstOrDefault(n => n.Id == id); var EntityRoles = _entities.AspNetRoles.FirstOrDefault(n => n.Name == st.Name); if (Entity.AspNetRoles.Contains(EntityRoles)) { Entity.AspNetRoles.Remove(EntityRoles); _entities.SaveChanges(); } logger.Debug("Удаление роли пользователя"); } catch (System.ServiceModel.CommunicationException ex) { logger.Error("Ошибка: ", ex); return(false); } return(true); }
/// <summary> /// spremi item /// insert ako nema Id /// update ako ima Id /// </summary> /// <param name="item">instanca entity objekta</param> /// <returns></returns> public bool Save(AspNetRoles item) { bool uspjelo = false; using (Entities data = new Entities()) { data.AspNetRoles.Add(item); //ako ima Id onda je update if (item.Id != null) { data.Entry <AspNetRoles>(item).State = System.Data.EntityState.Modified; } data.SaveChanges(); uspjelo = true; } return(uspjelo); }
public ActionResult CreateRole(AspNetRoles Role) { if (Role.Name != String.Empty) { var roleManager = new RoleManager <Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); if (!roleManager.RoleExists(Role.Name)) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = Role.Name; roleManager.Create(role); NotificationExtensions.AddNotification(this, "Role Saved", NotificationType.SUCCESS); } else { NotificationExtensions.AddNotification(this, "Role Exist", NotificationType.WARNING); } return(RedirectToAction("ViewRoles")); } NotificationExtensions.AddNotification(this, "Εrror Save!!!", NotificationType.ERROR); return(RedirectToAction("CreateRole")); }
/// <summary> /// Returns the role Id given a role name /// </summary> /// <param name="roleName">Role's name</param> /// <returns>Role's Id</returns> public string GetRoleId(string roleName) { ConnectionService.ThreadVanityUrl = ConnectionName; string roleId = null; AspNetRolesQuery q = new AspNetRolesQuery(); q.Select(q.Id); q.Where(q.Name == roleName); AspNetRoles role = new AspNetRoles(); SetConnection(role); if (role.Load(q)) { roleId = role.Id; } return(roleId); }
/// <summary> /// Brugt for at indsætte admin rollen, ikke brugbar metode /// </summary> private void SortRoles() { var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService <nillertron_com_dbContext>(); using (dbContext) { var role = new AspNetRoles { Id = "1", Name = "Admin", NormalizedName = "ADMIN" }; dbContext.Add(role); dbContext.SaveChanges(); role = dbContext.AspNetRoles.Where(x => x.Name == "Admin").FirstOrDefault(); var user = dbContext.AspNetUsers.Where(x => x.UserName == "*****@*****.**").FirstOrDefault(); var roleLine = new AspNetUserRoles { Role = role, User = user, RoleId = role.Id, UserId = user.Id }; dbContext.Add(roleLine); dbContext.SaveChanges(); } }
public async Task <ActionResult> Create([Bind(Include = "Id,Name")] AspNetRoles aspNetRoles) { if (ModelState.IsValid) { using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); await roleManager.CreateAsync(new IdentityRole { Name = aspNetRoles.Name }); return(Json(new { ok = 1, mensaje = "" })); } } return(View(aspNetRoles)); }
public static string CreateRole(string roleName) { try { using (TopMusicEntities db = new TopMusicEntities()) { var role = new AspNetRoles { Name = roleName, Id = Guid.NewGuid().ToString() }; db.AspNetRoles.Add(role); db.SaveChanges(); return(role.Name); } } catch (Exception error) { throw; } }
public ActionResult AddOrUpdateRoles(RolesDTO dto) { try { using (MABRUKLISTEntities dbcontext = new MABRUKLISTEntities()) { Guid gid = Guid.NewGuid(); AspNetRoles rols = new AspNetRoles() { Id = gid.ToString(), Name = dto.Roles }; dbcontext.AspNetRoles.Add(rols); dbcontext.SaveChanges(); return(Json(new { key = true, value = "Roles added successfully" }, JsonRequestBehavior.AllowGet)); }; } catch (Exception ex) { return(Json(new { key = false, value = "Unable to save the Address" }, JsonRequestBehavior.AllowGet)); } }
public async Task <ActionResult> Edit([Bind(Include = "Id,Name")] AspNetRoles aspNetRoles) { if (ModelState.IsValid) { //db.Entry(aspNetRoles).State = EntityState.Modified; //db.SaveChanges(); //return RedirectToAction("Index"); using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); var currentRol = roleManager.FindById(aspNetRoles.Id); currentRol.Name = aspNetRoles.Name; await roleManager.UpdateAsync(currentRol); return(RedirectToAction("Index")); } } return(View(aspNetRoles)); }
public async Task <bool> UpdatePost(AspNetRoles model) { bool result = false; if (db != null) { try { //Delete that warna db.AspNetRoles.Update(model); //Commit the transaction await db.SaveChangesAsync(); result = true; } catch (Exception ex) { throw ex; } } return(result); }
public async Task <IHttpActionResult> Post([FromBody] AspNetRoles md) { ResultInfo r = new ResultInfo(); try { if (!await roleManager.RoleExistsAsync(md.Name)) { var result = await roleManager.CreateAsync(new IdentityRole(md.Name)); if (result.Succeeded) { var item = await roleManager.FindByNameAsync(md.Name); r.result = true; r.aspnetid = item.Id; } else { r.result = false; r.message = string.Join(":", result.Errors.ToArray()); } } else { r.result = false; r.message = "The role " + md.Name + " has exist!"; } return(Ok(r)); } catch (Exception ex) { r.result = false; r.message = ex.Message; return(Ok(r)); } }
public IHttpActionResult GetDepartmentHeadListEmployees(string id) { AspNetUsers user = _context.AspNetUsers.FirstOrDefault(m => m.Id == id); AspNetRoles depHeadRoleList = _context.AspNetRoles.FirstOrDefault(m => m.Name == RoleName.ActingDepartmentHead); AspNetUsers delegatedDepHead = depHeadRoleList.AspNetUsers.FirstOrDefault(m => m.DepartmentId == user.DepartmentId); DelegateDepHeadApiModel apiModel = new DelegateDepHeadApiModel(); apiModel.DepartmentName = user.Department.DepartmentName; IEnumerable <AspNetRoles> employeesInDepartment = _context.AspNetRoles.Where(m => m.Name == RoleName.ActingDepartmentHead || m.Name == RoleName.Employee).ToList(); List <AspNetUsers> employeesForDelegate = new List <AspNetUsers>(); foreach (var currentRole in employeesInDepartment) { employeesForDelegate.AddRange(currentRole.AspNetUsers.ToList()); } List <AspNetUsers> employeesForDelegateFilterDepartment = employeesForDelegate.Where(m => m.DepartmentId == user.DepartmentId).ToList(); List <EmployeeDto> employeeDtos = new List <EmployeeDto>(); foreach (AspNetUsers current in employeesForDelegateFilterDepartment) { EmployeeDto tempEmployeeDto = new EmployeeDto { Name = current.EmployeeName, Id = current.Id }; employeeDtos.Add(tempEmployeeDto); apiModel.Employees = employeeDtos; } if (delegatedDepHead != null) { apiModel.DelegatedDepartmentHeadName = delegatedDepHead.EmployeeName; } return(Ok(apiModel)); }
/// <summary> /// 编辑一个AspNetRoles /// </summary> /// <param name="validationErrors">返回的错误信息</param> /// <param name="entity">一个AspNetRoles</param> /// <returns>是否编辑成功</returns> public bool Edit(ref ValidationErrors validationErrors, AspNetRoles entity) { try { using (TransactionScope transactionScope = new TransactionScope()) { if (Edit(ref validationErrors, db, entity)) { transactionScope.Complete(); return(true); } else { Transaction.Current.Rollback(); } } } catch (Exception ex) { validationErrors.Add(ex.Message); ExceptionsHander.WriteExceptions(ex); } return(false); }
public HashSet <string> obtienePermisos() { var fg = new AspNetUsers(); //instancia AspNetUser para usuario actual HashSet <string> permisos = new HashSet <string>(); var listauser = db.AspNetUsers.ToArray(); for (int i = 0; i < listauser.Length; i++) { //de todos los AspNetUser del sistema, encuentra el que tenga el email activo actualmente if (listauser[i].Email == User.Identity.Name) { fg = listauser[i]; //obtiene el AspNetUser actual } } AspNetRoles role = fg.AspNetRoles.First(); //consigue el rol del usuario var per = role.PERMISOS; //copia los permisos que tiene asignado foreach (PERMISOS p in role.PERMISOS) { //los copia a un HashSet<string> permisos.Add(p.ID); } return(permisos); }
//[Authorize(Roles = "Admin")] //[HttpPost] public ActionResult Inactivar(string id) { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); try { if (id == "d3ed6b54-fc9e-4dee-9787-9f78ecb37cab") { throw new Exception(); } //var Role = new AspNetRoles { Id = rol.Id }; AspNetRoles rol = context.AspNetRoles.FirstOrDefault(x => x.Id == id); context.Entry(rol).State = EntityState.Deleted; context.SaveChanges(); } catch { return(RedirectToAction("Index", new { cod = 1 })); //PseudoCodigo/Chvrli3 } return(RedirectToAction("Index")); }
// Calling the method of using Async public int InsertTask(AspNetRoles objInsert) { StackFrame stackFrame = new StackFrame(); MethodBase methodBase = stackFrame.GetMethod(); //int result = Insert(objInsert).Result; //return result; int RowEffected = 0; try { if (objInsert != null) { OpenEntityConnection(); objInsert.Id = GetNewHeaderId().ToString(); objPharmaEntities.AspNetRoles.Add(objInsert); RowEffected = objPharmaEntities.SaveChanges(); } } catch (Exception ex) { catchEntityvalidation((System.Data.Entity.Validation.DbEntityValidationException)ex, System.Runtime.InteropServices.Marshal.GetExceptionCode().ToString(), this.UserNameProperty.ToString(), this.GetType().Name.ToString(), methodBase.Name.ToString()); RowEffected = -1; ex.InnerException.Message.ToString(); } finally { CloseEntityConnection(); } return(RowEffected); }
public async Task <string> aj_MasterInsert(AspNetRoles md) { ResultInfo rAjaxResult = new ResultInfo(); try { if (!await roleManager.RoleExistsAsync(md.Name)) { var result = await roleManager.CreateAsync(new IdentityRole(md.Name)); if (result.Succeeded) { var item = await roleManager.FindByNameAsync(md.Name); rAjaxResult.result = true; rAjaxResult.aspnetid = item.Id; } else { rAjaxResult.result = false; rAjaxResult.message = String.Join(":", result.Errors.ToArray()); } } else { rAjaxResult.result = false; rAjaxResult.message = "the role " + md.Name + " has exist!"; } } catch (Exception ex) { rAjaxResult.result = false; rAjaxResult.message = ex.Message; } return(defJSON(rAjaxResult)); }