UserManager<ApplicationUser>.Create() is returning null - c#

I have the following code in the Seed method of my Configuration.cs file:
var userStore = new UserStore<ApplicationUser>();
var manager = new UserManager<ApplicationUser>(userStore);
IdentityResult result = manager.Create(new ApplicationUser() { UserName = "test#mail.com", Email = "test#mail.com", Name = "Martin Tracey" }, "password");
if (result.Succeeded) { Console.WriteLine("User created successfully"); }
else {
Console.WriteLine("Something went wrong. result is "+result.ToString());
foreach (var error in result.Errors) Console.WriteLine(error);
}
For whatever reason, the manager.Create call is returning null.
Any idea why this method would ever return null?

I figured it out! It's a very simple solution.
My userStorevariable didn't have a DbContext which would allow it to access and write to the Database. The simple solution is to use the context passed into the Seed method. Works like a charm now! See below:
protected override void Seed(MyFirstWebApplication.Models.ApplicationDbContext context)
{
if( !context.Users.Any( u => u.Email == "test#mail.com" ) )
{
var userStore = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser() { UserName = "test#mail.com", Email = "test#mail.com", Name = "Martin Tracey" };
IdentityResult result = manager.Create(user, "password");}
}
}

Related

How to implement Roles in ASP.NET Identity in webform

I successfully created a new user with this code:
protected void btnRegister_Click(object sender, EventArgs e)
{
// Default UserStore constructor uses the default connection string named: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = txtbxUserName.Text };
IdentityResult result = manager.Create(user, txtbxPassword.Text);
if (result.Succeeded)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity =
manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
Response.Redirect("~/MoneyFly");
}
else
{
litStatusMessage.Text = result.Errors.FirstOrDefault();
}
}
The code created a local database as soon as the user was created.
I want to create roles and add them to users.
I saw a post such as the one below.
https://forums.asp.net/t/2093837.aspx?How+to+implement+Roles+in+ASP+NET+Identity+2+1+in+Webforms
And I struggled to replicate what was done in the code.
That is partially, because it includes an autogenerated class, which I dont have.
ApplicationDbContext context = new ApplicationDbContext();
How do I generate that dbContext. It seems to be vital in the usage of the framework.
For example this line of code uses it to create an instance of RoleStore.
var roleStore = new RoleStore<IdentityRole>(context);
I got the solution.
This solution worked for me.
var roleStore = new RoleStore<IdentityRole>();
var roleMgr = new RoleManager<IdentityRole>(roleStore);
IdentityResult IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Administrator" });
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
IdentityResult IdUserResult = manager.AddToRole( manager.FindByName("vi").Id, "Administrator");
You dont have to provide a DBContext to the RoleStore Constructor.

Seeding admin database Role not adding

I am having some issues with getting my admin user have an admin role. Once I create a user and it succeeds I tried adding the admin role with AddToRoleAsync. But I am not sure why it's not being added. I then tried to have a check so that if the admin has no admin role it would add it. It looks like the command executes but I don't see it added to the database.
This is my code:
public async Task CreateAdmin()
{
// Add roles
string[] roles = new string[] {"Administrator", "User"};
foreach(string role in roles)
{
bool result = await _roleManager.RoleExistsAsync(role);
if(!result)
{
await _roleManager.CreateAsync(new IdentityRole(role));
}
}
// Add admin user
if (!_context.Users.Any(u => u.UserName == "Admin"))
{
var user = new Users
{
Email="admin#admin.com",
NormalizedEmail="ADMIN#ADMIN.COM",
UserName="admin#admin.com",
NormalizedUserName="ADMIN",
EmailConfirmed = true,
};
var result = await _userManager.CreateAsync(user, "Password123");
}
var adminuser = await _userManager.FindByEmailAsync("admin#admin.com");
bool flag = await _userManager.IsInRoleAsync(adminuser, "Administrator");
if(!flag)
{
var role = await _roleManager.FindByNameAsync("Administrator");
await _userManager.AddToRoleAsync(adminuser, "Administrator");
}
}
If you want the full DbIntilizer or more code let me know.
Anyone know what I am doing wrong?
Edit
Reworked it to follow this
http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/
and now it works.
This is how i do it.
public async Task InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
// Create DB
serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
// Add roles
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<long>>>();
if (!roleManager.Roles.Any())
{
foreach (var role in Config.GetTestRolls())
{
await roleManager.CreateAsync(role);
}
}
// Add users
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (userManager.Users.Any()) return;
foreach (var user in Config.GetTestUsers())
{
await userManager.CreateAsync(user, "Password123!");
}
// find first user add to first role (hack)
var adminUser = await userManager.FindByEmailAsync(Config.GetTestUsers().FirstOrDefault()?.Email);
if (adminUser != null)
{
await userManager.AddToRoleAsync(adminUser, Config.GetTestRolls().FirstOrDefault()?.Name);
}
}
Code ripped from my GitHub Project found here

How to create Role and User in ASP.Net identity?

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."
throw new Exception("User user wasn't created.");
I think you should reading error in object result 'IdUserResult', and insert user with function CreateAsync().

Asp.net c# Adding user roles

In my application I am trying to add Roles and then add Users to a particular role. After searching online I have made this snippet
public ActionResult Install1()
{
ClearLocalDev();
RegisterBindingModel model = new RegisterBindingModel();
model.Email = "mohsin#crondale.com";
model.Password = "123Asd?";
model.ConfirmPassword = "123Asd?";
CreateUser(model);
return RedirectToAction("Index", "Home");
}
public void CreateUser(RegisterBindingModel model)
{
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context); // The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("Admin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
identityUserResult = userMgr.Create(appUser, model.Password);
if (!userMgr.IsInRole(userMgr.FindByEmail(model.Email).Id, "Admin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail(model.Email).Id, "Admin");
}
}
This doesn't get. I get an exception. See the comments in the code to see what and where do I get the error.
Does it have something to do with Async?
I am using Azure as my data storage.
This should work for 4.5:
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("SuperAdmin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "SuperAdmin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = "SuperAdminUser#wingtiptoys.com",
Email = "SuperAdminUser#wingtiptoys.com"
};
identityUserResult = userMgr.Create(appUser, "Pa$$word1");
if (!userMgr.IsInRole(userMgr.FindByEmail("SuperAdminUser#xyz.com").Id, "SuperAdmin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail("SuperAdminUser#wingtiptoys.com").Id, "SuperAdmin");
}
Have you created the appropriate database tables for identity provider by running ef migrations? To me it seems that you are trying to invoke a context while the underlying database tables have not yet been created.
I suspect the following line will also cause problems:
identityUserResult = userMgr.Create(appUser, model.Password);
Two things you need to check:
You must hash your password before attempting to save it
The password must adhere to the configured password policy before attempting to save it.

Asp.net Identity Integration Test

I want write test and save user in sql ce.This my test:
using (ApplicationContext context = new ApplicationContext())
{
var email = "Shahrooz#s.s";
var username = "shahrooz";
var customUserStore = SmObjectFactory.Container.GetInstance<IUserStore<ApplicationUser, int>>();
var customRoleStore = SmObjectFactory.Container.GetInstance<IApplicationRoleManager>();
var smsService = SmObjectFactory.Container.GetInstance<IIdentityMessageService>();
var emailService = SmObjectFactory.Container.GetInstance<IIdentityMessageService>();
ApplicationUserManager manager = new ApplicationUserManager(customUserStore, customRoleStore, new DpapiDataProtectionProvider(), smsService, emailService);
context.Database.Connection.Open();
manager.CreateAsync(new ApplicationUser { Email = email, UserName = username }, Guid.NewGuid().ToString()).Wait();
var applicationUser = context.Users.Find(1);
Assert.IsNotNull(applicationUser);
Assert.IsTrue(applicationUser.Email == email);
Assert.IsTrue(applicationUser.UserName == username);
context.Database.Connection.Close();
}
But CreateAsync dont store any thing in database.
What is my problem?
This line:
manager.CreateAsync(.....
this method returns an object IdentityResult that contains boolean for Successful and a list of Errors that you should inspect. Inspect this object for errors and if user was created.

Categories