For some reason my Task.WaitAny line is hanging and I have no idea why. I am trying to create new user in the problem line of code. Here is the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditUser([Bind(Include = "UserID, Email, UserName, Roles, RoleID, RoleName")] ManagerUserViewModel model)
{
if (ModelState.IsValid)
{
using (var context = new ApplicationDbContext())
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
ApplicationUser user = new ApplicationUser();
user.Email = model.Email;
user.UserName = model.UserName;
if (model.UserID == null || model.UserID == "" || model.UserID == "0")
{
// Since it didn't have a UserID, we assume this is a new User
Task.WaitAny(manager.CreateAsync(user, "Changeitasap!2"));
Related
I am trying to create a user for a mixed authentication project. I am using MixedAuthExtension.cs.
I encounter a problem when I reach this line
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
but the system user is created and the AspNetUser.
Thanks in advance for your help
The current code creates both the system user and ASP.NET user but it fails to sync identity
[ValidateAntiForgeryToken]
[HttpPost]
public async Task<ActionResult> CreateSystemUser(RegisterViewModel model, string key)
{
var _context = new RequestToFillDbContext();
#region Initialise
Initialise(_context);
var password = SecurityHelper.GeneratePassword();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(_context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
model.Password = password;
model.ConfirmPassword = password;
ModelState.Clear();
#endregion
string serviveNumber = model.ServiceNumber;
if (!_context.SystemUsers.Any(s => s.EmailAddress == model.EmailAddress)
&& !_context.SystemUsers.Any(s => s.UserName == model.UserName))
{
if (ModelState.IsValid)
{
var emp = new RequestToFillApplicationHelper().GetEmployeeByServiceNumber(serviveNumber);
model.Designation = emp.Designation;
//TODO: Query Db for Id
//var identityManager = new IdentityManager();
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.EmailAddress,
EmailConfirmed = true,
SystemUser = new SystemUser()
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.UserName,
CompanyName = model.CompanyName,
Designation = model.Designation,
EmailAddress = model.EmailAddress,
IsTemporaryPassword = true,
//TempPasswordExpiryDateTime = DateTime.Now.AddHours(24),
SystemUserTypeId = model.SystemUserTypeId,
ServiceNumber = model.ServiceNumber,
IsActive = true,
IsDeleted = false,
IsLocked = false,
CreatedDateTime = DateTime.Now,
IsPasswordReset = false
}
};
//db.SaveChanges();
try
{
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
//Assign user to role
I get a
"Property set method not found."Line 258
which is below
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
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().
I'm building a simple application where a user can edit their profile including adding/deleting a brand image. This seems to be working fine and is updating the database no problem, however when refreshing the page and retrieving the user details via Membership.GetUser() the result includes the old results and not those from the updated database.
Here is my MembershipUser GetUser override:
public override MembershipUser GetUser(string query, bool userIsOnline)
{
if (string.IsNullOrEmpty(query))
return null;
var db = (AccountUser)null;
// ...get data from db
if (query.Contains("#")){
db = _repository.GetByQuery(x => x.Email == query).FirstOrDefault();
}
else
{
string firstName = query;
string lastName = null;
if (query.Contains(" "))
{
string[] names = query.Split(null);
firstName = names[0];
lastName = names[1];
}
// ...get data from db
db = _repository.GetByQuery(x => x.FirstName == firstName && x.LastName == lastName).FirstOrDefault();
}
if (db == null)
return null;
ToMembershipUser user = new ToMembershipUser(
"AccountUserMembershipProvider",
db.FirstName + " " + db.LastName,
db.ID,
db.Email,
"",
"",
true,
false,
TimeStamp.ConvertToDateTime(db.CreatedAt),
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue);
// Fill additional properties
user.ID = db.ID;
user.Email = db.Email;
user.FirstName = db.FirstName;
user.LastName = db.LastName;
user.Password = db.Password;
user.MediaID = db.MediaID;
user.Media = db.Media;
user.Identity = db.Identity;
user.CreatedAt = db.CreatedAt;
user.UpdatedAt = db.UpdatedAt;
return user;
}
Note I am using a custom MembershipProvider and MembershipUser. Here is where I am calling that method:
public ActionResult Edit()
{
ToMembershipUser toUser = Membership.GetUser(User.Identity.Name, true) as ToMembershipUser;
Now when I do a separate query just under this line of code straight to the database, not invoking MembershipUser, I get the updated result which in turn updates the MembershipUser result?!
It seems it may be caching the results? Anyway around this? I hope this is clear enough. Thanks
Edit:
It appears that when I set a breakpoint just after :
// ...get data from db
db = _repository.GetByQuery(x => x.FirstName == firstName && x.LastName == lastName).FirstOrDefault();
'db' retrieves the outdated results though surely this is talking to the database? If need be I'll update with my repository pattern
I managed to find a workaround though I'm not happy with this solution, so if anyone can improve upon this please post.
I decided to manually update the MembershipUser instance manually each time I update the image. My controller now looks like this:
private static ToMembershipUser MembershipUser { get; set; }
// GET: Dashboard/AccountUsers/Edit
public ActionResult Edit()
{
if(MembershipUser == null)
MembershipUser = Membership.GetUser(User.Identity.Name, true) as ToMembershipUser;
}
[HttpPost]
[ValidateJsonAntiForgeryToken]
public JsonResult UploadMedia(IEnumerable<HttpPostedFileBase> files, int id)
{
var images = new MediaController().Upload(files);
if (images == null)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("File failed to upload.");
}
AccountUser accountUser = db.AccountUsers.Find(id);
db.Entry(accountUser).State = EntityState.Modified;
accountUser.UpdatedAt = TimeStamp.Now();
accountUser.MediaID = images[0];
db.SaveChanges();
MembershipUser.Media = accountUser.Media;
MembershipUser.MediaID = accountUser.MediaID;
return Json(new { result = images[0] });
}
[HttpPost]
[ValidateJsonAntiForgeryToken]
public JsonResult DeleteMedia(int id)
{
bool delete = new MediaController().Delete(id, 1);
if (!delete)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error. Could not delete file.");
}
MembershipUser.Media = null;
MembershipUser.MediaID = null;
return Json("Success");
}
I have installed asp.net identity sample https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples and trying to create a new role "SAdmin" with the user "Sadmin#example.com". The user is created but "Sadmin" gets the same role as "Admin"
I have modified IdentityConfig.cs to
//Create User=Admin#Admin.com with password=Admin#123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db) {
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin#example.com";
const string password = "Admin#123456";
const string roleName = "Admin";
const string Sname = "Sadmin#example.com";
const string Spassword = "SAdmin#123456";
const string SroleName = "SAdmin";
//Create Super if it does not exist
var Srole = roleManager.FindByName(SroleName);
if (Srole == null)
{
Srole = new IdentityRole(roleName);
var roleresult = roleManager.Create(Srole);
}
var Suser = userManager.FindByName(Sname);
if (Suser == null)
{
Suser = new ApplicationUser { UserName = Sname, Email = Sname };
var result = userManager.Create(Suser, Spassword);
result = userManager.SetLockoutEnabled(Suser.Id, false);
}
// Add Suser to Role Admin if not already added
var SrolesForUser = userManager.GetRoles(Suser.Id);
if (!SrolesForUser.Contains(Srole.Name))
{
var result = userManager.AddToRole(Suser.Id, Srole.Name);
}
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null) {
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null) {
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = userManager.AddToRole(user.Id, role.Name);
}
}
The problem is in the code... The following code block is responsible
if (Srole == null)
{
**Srole = new IdentityRole(roleName);**
var roleresult = roleManager.Create(Srole);
}
Change the highlighted line to
**Srole = new IdentityRole(SroleName);**
That should solve it
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.