Advertisement
onzulin

problema actualizando roles

Sep 26th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.57 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Domotica_db.Data;
  6. using Domotica_db.Data.CustomIdentity;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Identity;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.AspNetCore.Mvc.RazorPages;
  11. using Domotica_db.Library;
  12. using Domotica_db.Areas.Usuarios.Models;
  13. using Microsoft.AspNetCore.Http;
  14. using Domotica_db.Areas.Usuarios.Controllers;
  15.  
  16. namespace Domotica_db.Areas.Usuarios.Pages.Editar
  17. {
  18. public class EditModel : PageModel
  19. {
  20. private ListObject objeto = new ListObject();
  21. private static List<ApplicationUser> userList1;
  22.  
  23.  
  24.  
  25. public EditModel(RoleManager<ApplicationRole> roleManager, UserManager<ApplicationUser> userManager, ApplicationDbContext context, IHostingEnvironment environment)
  26. {
  27. //inicializamos todos los objetos que necesitamos a la creación dle objeto EditModel cuando lo llamamos con el
  28. //UsuariosController
  29. objeto._roleManager = roleManager;
  30. objeto._userManager = userManager;
  31. objeto._environment = environment;
  32. objeto._context = context;
  33. objeto._usuarios = new LUsuarios();
  34. objeto._usersRole = new UserRoles();
  35. objeto._image = new UploadImage();
  36. objeto._userRoles = new List<SelectListItem>();
  37. }
  38. //método OnGet importante para recibir los datos que nos manda el usuario cuando hace click en el boton editar
  39. //id en realidad puede ser el email del usuario que queremos editar
  40. public async void OnGetAsync(string id)
  41. {
  42. Input = new InputModel
  43. {
  44. rolesLista = objeto._usersRole.getRoles(objeto._roleManager)
  45. };
  46. if (id != null)
  47. {
  48.  
  49. await editAsync(id);
  50. }
  51. }
  52. [BindProperty]
  53. public InputModel Input { get; set; }
  54. public class InputModel : InputModelRegistrar
  55. {
  56. [TempData]
  57. public string ErrorMessage { get; set; }
  58. public IFormFile AvatarImage { get; set; }
  59. public List<SelectListItem> rolesLista { get; set; }
  60. }
  61. //para mostrar la información de una tupla
  62. private async Task editAsync(string id )
  63. {
  64. //en mi caso id es igual al correo electronico
  65. string Email = id;
  66. userList1 = objeto._userManager.Users.Where(u => u.Email.Equals(Email)).ToList();
  67. //userList2 = objeto._context.Usuarios.Where(u => u.ApplicationUserId.Equals(userList1[0].Id)).ToList();
  68. var userRoles = await objeto._usersRole.GetRole(objeto._userManager, objeto._roleManager, userList1[0].Id);
  69. //vamos básicamente estoy mostrando al usuario esta información tal cual.
  70.  
  71. Input = new InputModel
  72. {
  73. Nombre = userList1[0].Nombre,
  74. Apellido = userList1[0].Apellido,
  75. NIF = userList1[0].NIF,
  76. PhoneNumber = userList1[0].PhoneNumber,
  77. Email = userList1[0].Email,
  78. Password = "*********",
  79. Role = userRoles[0].Text,
  80. RoleUser = userRoles[0].Text,
  81. //aqui se hace una seleccion de rol a User
  82. rolesLista = getRoles(userRoles[0].Text)
  83. };
  84.  
  85. }
  86. public async Task<IActionResult> OnPostAsync(string returnUrl = null)
  87. {
  88. if (Input.Email != null)
  89. {
  90. var valor = await actualizarAsync();
  91. if (valor)
  92. {
  93. return RedirectToAction(nameof(UsuariosController.Index), "Usuarios");
  94. }
  95. else
  96. {
  97.  
  98. return Page();
  99. }
  100. }
  101. else
  102. {
  103. return Page();
  104. }
  105. }
  106. private async Task<bool> actualizarAsync()
  107. {
  108. var valor = false;
  109. try
  110. {
  111. if (ModelState.IsValid)
  112. {
  113. //obtener todos los roles de usuario
  114. //UserRoles userRoles = new UserRoles();
  115. //para obtener todos los roles en el listado
  116. //Input.rolesLista.Where(role => role.Selected == true);
  117. /*
  118. Input.rolesLista.Add(new SelectListItem
  119. {
  120. //aquí tengo que coger el valor de lo que ponga el usuario en el dropDownList no del Input.Role
  121. //obtiene el valor de OnGetAsync().
  122. Text = Input.Role
  123. });
  124. */
  125. // esto es lo que hay que añadir a la base de datos
  126. string role = Input.Role;
  127.  
  128. var identityUser = new ApplicationUser
  129. {
  130. Id = userList1[0].Id,
  131. UserName = Input.Email,
  132. Email = Input.Email,
  133. PhoneNumber = Input.PhoneNumber,
  134. EmailConfirmed = userList1[0].EmailConfirmed,
  135. LockoutEnabled = userList1[0].LockoutEnabled,
  136. LockoutEnd = userList1[0].LockoutEnd,
  137. NormalizedEmail = userList1[0].NormalizedEmail,
  138. NormalizedUserName = userList1[0].NormalizedUserName,
  139. PasswordHash = userList1[0].PasswordHash,
  140. PhoneNumberConfirmed = userList1[0].PhoneNumberConfirmed,
  141. SecurityStamp = userList1[0].SecurityStamp,
  142. TwoFactorEnabled = userList1[0].TwoFactorEnabled,
  143. AccessFailedCount = userList1[0].AccessFailedCount,
  144. ConcurrencyStamp = userList1[0].ConcurrencyStamp,
  145. Nombre = Input.Nombre,
  146. Apellido = Input.Apellido,
  147. NIF = Input.NIF,
  148. Imagen = Input.Imagen,
  149. };
  150.  
  151. //esta linea es la que añade el dato que necesito a cada usuario con identityUser sabremos que usuario
  152. //estamos actualizando.
  153. //ApplicationUser user = await objeto._userManager.FindByIdAsync(userList1[0].Id);
  154. //el tema de los roles a ver como lo resuelvo
  155. //var roleUser = await objeto._userManager.GetRolesAsync(identityUser);
  156. //esto da error loo pongo en issues
  157. //esto quiere decir que ya se le ha asignado un rol al usuario
  158. if (Input.RoleUser != Input.Role)
  159. {
  160. var removeRole = await objeto._userManager.RemoveFromRoleAsync(identityUser, Input.RoleUser);
  161. var addRole = await objeto._userManager.AddToRoleAsync(identityUser, Input.Role);
  162.  
  163. }
  164.  
  165.  
  166. //var result = await objeto._userManager.upda
  167. /*
  168.  
  169. if (!result.Succeeded)
  170. {
  171. var resultRemove = await objeto._userManager.RemoveFromRoleAsync(identityUser, roleUser);
  172. }
  173. */
  174. objeto._context.Update(identityUser);
  175.  
  176. await objeto._context.SaveChangesAsync();
  177.  
  178. //La imagen dijimos que iba a cogerla del nombre que haya
  179. string imageName;
  180. if (Input.Imagen != null)
  181. {
  182. imageName = Input.Imagen;
  183. }
  184. else
  185. {
  186. imageName = "default.png";
  187. }
  188.  
  189. await objeto._image.copiarImagenAsync(Input.AvatarImage, imageName, objeto._environment, "Users");
  190.  
  191. valor = true;
  192. }
  193. else
  194. {
  195. Input = new InputModel
  196. {
  197. ErrorMessage = "Seleccione un role",
  198. rolesLista = objeto._usersRole.getRoles(objeto._roleManager)
  199. };
  200. valor = false;
  201. }
  202. }
  203. catch (Exception ex)
  204. {
  205.  
  206. Input = new InputModel
  207. {
  208. ErrorMessage = ex.Message,
  209. rolesLista = getRoles(Input.Role)
  210. };
  211. valor = false;
  212. }
  213.  
  214.  
  215. return valor;
  216. }
  217. //rellena el listado del combobox que he puesto en la página
  218. private List<SelectListItem> getRoles(String role)
  219. {
  220. objeto._userRoles.Add(new SelectListItem
  221. {
  222. Text = role
  223. });
  224. var roles = objeto._usersRole.getRoles(objeto._roleManager);
  225. roles.ForEach(item => {
  226. if (item.Text != role)
  227. {
  228. objeto._userRoles.Add(new SelectListItem
  229. {
  230. Text = item.Text
  231. });
  232. }
  233. });
  234. return objeto._userRoles;
  235. }
  236.  
  237. }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement