I am trying to create a user using claim identity asp.net
I get this error while creating claims identity user.
ApplicationUser user = new ApplicationUser {
EmailConfirmed = true,
UserName = model.myUser.Email,
Email = model.myUser.Email ,
PhoneNumber = model.myUser.PhoneNumber,
PhoneNumberConfirmed = true,
UserImagePath = model.myUser.UserImagePath,
FirstName= model.myUser.FirstName,
LastName = model.myUser.LastName,
DateOfBirth = model.myUser.DateOfBirth,
Culture = model.myUser.Culture,
Role = model.myUser.Role
};
but when the code was
var user= new ApplicationUser {
UserName = model.myUser.Email,
Email = model.myUser.Email ,
};
it worked perfectly, so i want to know what is wrong
You have a statement (if or while, for example), right before the code you posted, without curly braces.
For example:
if (somethingIsTrue)
{
var user= new ApplicationUser {
UserName = model.myUser.Email,
Email = model.myUser.Email ,
};
}
is correct, but the code below:
if (somethingIsTrue)
var user = new ApplicationUser {
UserName = model.myUser.Email,
Email = model.myUser.Email ,
};
will result in CS1023: Embedded statement cannot be a declaration or labeled statement.
UPDATE
The reason, according to #codefrenzy, is that the newly declared variable will immediately go out of scope, unless it is enclosed in a block statement, where it can be accessed from.
The compilation will pass in the following cases though.
If you only initialize a new instance of a type, without declaring a new variable:
if (somethingIsTrue)
new ApplicationUser {
UserName = model.myUser.Email,
Email = model.myUser.Email ,
};
or if you assign a value to an existing variable:
ApplicationUser user;
if (somethingIsTrue)
user = new ApplicationUser {
UserName = model.myUser.Email,
Email = model.myUser.Email ,
};
I just had this error, and the fix was to add a curly brace to the if immediately preceding my code, and then remove it again. Visual Studio facepalm OTD.
Related
I need to create a controller that will get and delete all users and a certain user, respectively and I've figured out the part to get the users, add them to a list and return the list. But I struggle with the get roles part. Initially I tried a Linq Select and that works just fine (and looks decent) for simply getting the roles but doesn't work for getting the roles for that specific user as well. I've also tried a much worse methods: getting all the users from db in a list, foreach the list and for every iteration in the foreach, create a new object of the type I want to return and assign the role for that user to the respective object property. Doesn't work AND it's ugly.
TL;DR : is this the proper way to get roles in a select and does the 'Role' property need to be IList 100%?
Here's my GetRoles method:
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult GetUsers()
{
var userDbList = _userManager.Users.ToList();
if (userDbList is null) return BadRequest(AppResources.UsersDoNotExist);
// my initial select. GetUsersModel is just a model for the object
// I return and contains Name, Email, UserName and Role. As you can see,
// the method is async but I get a cannot implicitly convert System.Collections
// .Generic.IList<string> to string (I suspect I need to set Role as a List<string>?)
var userList = userDbList.Select(async user => new GetUsersModel
{
Name = $"{user.FirstName} {user.LastName}",
UserName = user.UserName,
Email = user.Email,
Role = await _userManager.GetRolesAsync(user)
});
/*var userList = new List<GetUsersModel>();
foreach (var user in userDbList)
{
userList.Add(new GetUsersModel
{
Name = $"{user.FirstName} {user.LastName}",
UserName = user.UserName,
Email = user.Email,
Role = await _userManager.GetRolesAsync(user)
});
}*/
return Ok(userList);
}
I have a similar method for deleting a user, only I first check request data and remove the user if everything's ok and then create a list to include in an object (along with a message if the removal was successful) to return.
When you use async lambda in a select, this return IEnumerable<Task<T>>. In you case, the variable userList is type of IEnumerable<Task<GetUsersModel>>. You need to wait all tasks and get the result like :
public IActionResult GetUsers()
{
var userDbList = _userManager.Users.ToList();
if (userDbList is null) return BadRequest(AppResources.UsersDoNotExist);
IEnumerable<Task<GetUsersModel>> userListTasks = userDbList.Select(async user => new GetUsersModel
{
Name = $"{user.FirstName} {user.LastName}",
UserName = user.UserName,
Email = user.Email,
Role = await _userManager.GetRolesAsync(user)
});
IEnumerable<GetUsersModel> userList = userListTasks.Select(t => t.Result);
return Ok(userList);
}
If the method UserManager.GetRolesAsync isn't thread safe, then :
public IActionResult GetUsers()
{
var userDbList = _userManager.Users.ToList();
if (userDbList is null) return BadRequest(AppResources.UsersDoNotExist);
IEnumerable<GetUsersModel> userList = userDbList.Select(user => new GetUsersModel
{
Name = $"{user.FirstName} {user.LastName}",
UserName = user.UserName,
Email = user.Email,
Role = _userManager.GetRolesAsync(user).Result
});
return Ok(userList);
}
I'm trying to add users in an Azure AD B2C using the Microsoft Graph API. My code works just fine when I add a User, but I tried to add it a second time with the same info given to the API (mail, names, etc...) and expected an error like
User already exists
or something similar.
My API call is done like this :
var result = await graphClient.Users.Request().AddAsync(new User()
{
AccountEnabled = true,
Mail = "example#example.onmicrosoft.com",
MailNickname = "example",
UserPrincipalName = "example#example.onmicrosoft.com",
Surname = "TEST",
DisplayName = "test",
GivenName = "TEST test",
PasswordProfile = new PasswordProfile
{
ForceChangePasswordNextSignIn = true,
Password = "tmpPwd"
}
});
Keeping in mind that my first call correctly add the user to the AD, why the API would return me this message :
Microsoft.Graph.ServiceException : 'Code: Request_BadRequest
Message: One or more properties contains invalid values.
Thank you in advance.
According to the document Create the user using the below property without mail .so that when a user has already existed then you will get the error as below
Code: Request_BadRequest
Message: Another object with the same value for property userPrincipalName already exists.
code:
var result = await graphClient.Users.Request().AddAsync(new User()
{
AccountEnabled = true,
MailNickname = "example",
UserPrincipalName = "example665#XX.live",
Surname = "TEST",
DisplayName = "test",
GivenName = "TEST test",
PasswordProfile = new PasswordProfile
{
ForceChangePasswordNextSignIn = true,
Password = "password#1234"
}
});
Console.WriteLine(JsonConvert.SerializeObject(result));
}
Using additional property may change the error context as you are receiving currently
This is truly one of the strangest issues I've run into.
I have a Web API which uses EF. I have an audit table which takes an ApplicationUser. I create the new object, add it to the collection and then call SaveChangesAsync(). The weird part is, I get "User name MyUserName is already taken." error.
using (var context = new ApplicationDbContext())
{
var user = context.Users.Single<ApplicationUser>(x => x.UserName == model.UserName);
var sid = context.SessionIds.FirstOrDefault(x => x.Id == model.SessionId);
var audit = new Audit
{
Data = model.Data,
User = user,
IpAddress = Helper.GetClientIp(Request),
Session = sid != null ? sid : ItsMyChance.Entities.Entities.SessionId.Create(scoreModel.UserName, scoreModel.GameId)
};
context.Audits.Add(audit);
await context.SaveChangesAsync();
}
Update
This code has been working for years. The difference is I upgrade from .NET 4.5 to .NET 4.61
Update 2
I also tried the following but still receive the same error
[ForeignKey("User")]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
Update 3
Trying to track this issue down I call
var entries = context.ChangeTracker.Entries();
It returns several entries, 1 for each object, including User. User shows Added and another as Unchanged. I can't figure out how this is happening.
In addition, I added the following before making any changes but there's no effect.
context.Configuration.AutoDetectChangesEnabled = false;
Since You are adding the complete user object in Audit , so SaveChangesAsync will save a new Entry for Audit and User also and since a user with same username already exists that's why you are getting this error. What you should do is just assign just the UserId (Whatever is referral key in Audit table for User) in Audit object
var audit = new Audit
{
Data = model.Data,
UserId = user.Id,
IpAddress = Helper.GetClientIp(Request),
Session = sid != null ? sid : ItsMyChance.Entities.Entities.SessionId.Create(scoreModel.UserName, scoreModel.GameId)
};
I am having trouble figuring out how to seed additional users and roles into my MVC5 application, using EF6 code first. In order to debug the Seed method from the Configure.cs since update-database was not working, I wrote this controller,
public ActionResult test() {
var context = new ApplicationDbContext();
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
roleManager.Create(new IdentityRole { Name = "basic" });
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var adminthere = context.Users.Any(n => n.UserName == "Admin");
var basicthere = context.Users.Any(n => n.UserName == "Basic");
// Create Dummy basic account
if (!basicthere) {
var basicUser = new ApplicationUser { UserName = "Basic" };
userManager.Create(basicUser, "test");
var _id = basicUser.Id;
userManager.AddToRole(basicUser.Id, "basic");
}
return View();
}
The debugger throws an exception at the userManager.AddToRole(basicUser.Id, "basic"); call saying "UserID not found"? Here is a screenshot including variable values from the debug session:
What is the problem? Also, the exact same code (changing the words "basic" for "Admin") works for seeding the database with the Admin user in role "admin". Why?
EDIT EDIT: moved edit I posted here previoulsy to a real answer below.
As the comments suggested I will post my this as an answer:
The line of code userManager.Create(basicUser, "test"); didn't succeed - the passwort must at least have 6 characters. So while creating the basicUser ApplicationUser instance worked (and hence the _id was not null) I didn't have an IdentityUser of that _id. On admin it succeeded previously bc. I had a different pwd that I didn't want to post here ...
I am using VS 2013 and the Neo4j client in an MVC application and can't get past building the query.
In the following code, I can connect to my server but on the var newUser line I get an error over the new User statement saying it's a property but used like a type, that can bee seen in this screen shot:
var client = new GraphClient(new System.Uri("http://localhost:7474/db/data"));
client.Connect();
var newUser = new User { Id = 456, Name = "Jim" };
client.Cypher
.Merge("(user:User { Id: {id} })")
.OnCreate("user")
.Set("user = {newUser}")
.WithParams(new
{
id = newUser.Id,
newUser
})
.ExecuteWithoutResults();
I think I need to add or remove a reference but I a not sure what it is.
If you read the error, you'll see User is a property of Controller, so it's not recognized as a type.
You'll need to prefix the namespace, like new Neo4j.User() or whatever its documentation states it uses.