1

I used following method to create two roles and two users when my web app starts (In Application_Start() in Global.asax.cs). However the Administrator role is being created but not the User role. Similar thing happens for user named Admin@admin.com and user named user@user.net. First one is being created but not the second one.

Here is my code.

void create() {
    ApplicationDbContext context = new ApplicationDbContext();
    IdentityResult IdRoleResult;
    IdentityResult IdUserResult;

    var roleStore = new RoleStore<IdentityRole>(context);
    var roleMngr = new RoleManager<IdentityRole>(roleStore);
    if (!roleMngr.RoleExists("Administrator"))
        IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));

    roleStore = new RoleStore<IdentityRole>(context);
    roleMngr = new RoleManager<IdentityRole>(roleStore);
    if (!roleMngr.RoleExists("User"))
        IdRoleResult = roleMngr.Create(new IdentityRole("User"));

    var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    var appUser = new ApplicationUser() { UserName = "Admin@admin.com" };
    IdUserResult = userMngr.Create(appUser, "pa$$word");
    if (IdUserResult.Succeeded) 
        IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");

    userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    appUser = new ApplicationUser() { UserName = "user@user.net" };
    IdUserResult = userMngr.Create(appUser, "user");
    if (IdUserResult.Succeeded)
        IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
}

Can anybody tell me, what I've done wrong or any alternative way to perform this. Thanks in advance.

Updated Code:

void createAdmin() {
    ApplicationDbContext context = new ApplicationDbContext();
    IdentityResult IdRoleResult;
    IdentityResult IdUserResult;

    var roleStore = new RoleStore<IdentityRole>(context);
    var roleMngr = new RoleManager<IdentityRole>(roleStore);

    if (!roleMngr.RoleExists("Administrator")) {
        IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));
        if (!IdRoleResult.Succeeded)
            throw new Exception("Administrator role wasnt created.");
    }

    if (!roleMngr.RoleExists("User")) {
        IdRoleResult = roleMngr.Create(new IdentityRole("User"));
        if (!IdRoleResult.Succeeded)
            throw new Exception("User role wasnt created.");
    }

    var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    ApplicationUser appUser;

    var q = from user in userMngr.Users
            where user.UserName == "Admin@admin.com"
            select user;
    if (q.Count() == 0) {
        appUser = new ApplicationUser() { UserName = "Admin@admin.com" };
        IdUserResult = userMngr.Create(appUser, "pa$$word");
        if (IdUserResult.Succeeded) {
            IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");
            if (!IdRoleResult.Succeeded)
                throw new Exception("Admin user wasn't added to Administrator role.");
        } else
            throw new Exception("Admin user wasn't created.");
    }

    q = from user in userMngr.Users
        where user.UserName == "user@user.net"
        select user;
    if (q.Count() == 0) {
        appUser = new ApplicationUser() { UserName = "user@user.net" };
        IdUserResult = userMngr.Create(appUser, "user");
        if (IdUserResult.Succeeded) {
            IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
            if (!IdRoleResult.Succeeded)
                throw new Exception("User user wasn't added to User role.");
        } else
            throw new Exception("User user wasn't created.");
    }
}

Here I found that, the code is throwing exception with message "User user wasn't created."

Parvez M Robin
  • 154
  • 1
  • 3
  • 16
  • 1
    So what's the value of `IdRoleResult` in the case where the `User` role fails to be created? You need to look at these return values to establish what's going on. – spender Jul 07 '16 at 16:02
  • Why are you creating new `RoleStore` and `RoleManager` instances for each operation? These can be reused. Same with `UserManager`. – spender Jul 07 '16 at 16:04
  • 1
    I would seriously avoid code like `if (IdUserResult.Succeeded) IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");`. Instead, I prefer to implement a `switch` statement with the default case throwing an `ArgumentOutOfRangeException`. That way things never silently fail. – mason Jul 07 '16 at 16:09
  • You don't need to create new instances of `UserManager`, `RoleManager` `RoleStore`, and `UserStore` every time. You can create an instance of each at the start and reuse them. – Bradley Uffner Jul 07 '16 at 16:48
  • Updated code placed in question. Please review. – Parvez M Robin Jul 07 '16 at 17:21
  • 1
    The `IdentityResult` class has a [collection of Errors](https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityresult.errors(v=vs.108).aspx#P:Microsoft.AspNet.Identity.IdentityResult.Errors). You need to look at that collection, e.g. `IdRoleResult.Errors` and find out what those errors are. – spender Jul 07 '16 at 22:10

1 Answers1

0
throw new Exception("User user wasn't created.");

I think you should reading error in object result 'IdUserResult', and insert user with function CreateAsync().

B.Syal
  • 69
  • 2
  • 5