Given this bit of code... (role and userName are strings passed in)
string[] existingRoles = Roles.GetRolesForUser(userName);
foreach (string role in existingRoles)
{
if (!newRoles.Contains(role))
{
Authentication.AuthTraceStatic("Removing user {0} from role: {1}",
userName, role);
Roles.RemoveUserFromRole(userName, role);
}
}
I get the following error:
The user 'xxx' is already not in role 'yyy'.
Which is somewhat mystifying given I have just fetched the user's roles and checked that the one I want to remove exists.... Any clues what to do get this to work correctly?
Can't it be a multithreading issue? Have you tried to surround the code with a lock block? What happens if you check for the role existence using Roles.IsUserInRole(username, role) inside foreach loop?
I would try to debug it with a code like that, see what happens.
string[] existingRoles = Roles.GetRolesForUser(userName);
foreach (string role in existingRoles)
{
if (!newRoles.Contains(role))
{
Authentication.AuthTraceStatic("Removing user {0} from role: {1}", userName, role);
lock(o)
{
if(Roles.IsUserInRole(userName, role))
Roles.RemoveUserFromRole(userName, role);
else
Authentication.AuthTraceStatic("Somebody is messing with my roles!!", userName, role);
}
}
}
First Check the context of your user name. I had this same issue myself. Sometimes username is returning the currently logged in user and not the user you're trying to remove roles on.
Second, check to ensure your code isn't removing roles where you aren't expecting it to. These are the two issues I had when I got the same error. Also make sure you're using the membership provider to get the membership user object which you can then use to access the username.
Here's my similar code but I was looping through a checkbox list of roles that was already bound and prepopulated with the selected roles the user already has.
MembershipUser user = Membership.GetUser( txtUserName.Text);
//Update roles
foreach (ListItem role in cbRoles.Items)
{
if (role.Selected)
{
//if user is not in role
if (!Roles.IsUserInRole(user.UserName,role.Value))
{
Roles.AddUserToRole(user.UserName, role.Value);
}
}//role not selected
else
{
//if user is in a role that is no longer selected remove them
if (Roles.IsUserInRole(user.UserName, role.Value))
{
Roles.RemoveUserFromRole(user.UserName, role.Value);
}
}
}
Hope this helps. GS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With