Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using Microsoft.AspNet.Identity;
  6. using Microsoft.AspNet.Identity.EntityFramework;
  7. using ProjekatRad.Models;
  8.  
  9. namespace ProjekatRad.Logic
  10. {
  11. internal class Roles
  12. {
  13. internal void AddUserAndRole()
  14. {
  15. // Access the application context and create result variables.
  16. Models.ApplicationDbContext context = new ApplicationDbContext();
  17. IdentityResult IdRoleResult;
  18. IdentityResult IdUserResult;
  19.  
  20. // Create a RoleStore object by using the ApplicationDbContext object.
  21. // The RoleStore is only allowed to contain IdentityRole objects.
  22. var roleStore = new RoleStore<IdentityRole>(context);
  23.  
  24. // Create a RoleManager object that is only allowed to contain IdentityRole objects.
  25. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
  26. var roleM = new RoleManager<IdentityRole>(roleStore);
  27.  
  28. // Then, you create the "canEdit" role if it doesn't already exist.
  29. if (!roleM.RoleExists("Admin"))
  30. {
  31. IdRoleResult = roleM.Create(new IdentityRole { Name = "Admin" });
  32. }
  33.  
  34. if (!roleM.RoleExists("Registrovan"))
  35. {
  36. IdRoleResult = roleM.Create(new IdentityRole { Name = "Registrovan" });
  37. }
  38.  
  39. // Create a UserManager object based on the UserStore object and the ApplicationDbContext
  40. // object. Note that you can create new objects and use them as parameters in
  41. // a single line of code, rather than using multiple lines of code, as you did
  42. // for the RoleManager object.
  43. var userM = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
  44. var appUser = new ApplicationUser
  45. {
  46. UserName = "canEditUser@wingtiptoys.com",
  47. Email = "canEditUser@wingtiptoys.com"
  48. };
  49. IdUserResult = userM.Create(appUser, "Pa$$word1");
  50.  
  51. // If the new "canEdit" user was successfully created,
  52. // add the "canEdit" user to the "canEdit" role.
  53. if (!userM.IsInRole(userM.FindByEmail("canEditUser@wingtiptoys.com").Id, "Admin"))
  54. {
  55. IdUserResult = userM.AddToRole(userM.FindByEmail("canEditUser@wingtiptoys.com").Id, "Admin");
  56. }
  57.  
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement