Get Membership Users and Emails - asp.net-mvc

I find it difficult to understand the structure of the MembershipUserCollection class. For example, I get All Users as a MembershipUserCollection, yet I cannot access MembershipUser to get the users emails. Here is a sample of what I currently do:
MembershipUserCollection AllUsers = Membership.GetAllUsers();
foreach (var user in AllUsers)
{
var userName = user.ToString();
// Is there a better way to get the email within loop without having to call the GetUser method??
var email = Membership.GetUser(user).Email
}

Try using
foreach (MembershipUser user in AllUsers)

Related

Select MVC Membership usernames to list

I am trying to select all usernames in MVC membership provider into a queryable list to plug into a function that checks if a given username exists and modifies it by adding a number at the end if it is so. I am struggling to get the list. I am not sure if what I am trying to achieve is achievable.
So far this is what I have come up with as below
var allusers = (from MembershipUser u in Membership.GetAllUsers()
select new
{
Uname = u.UserName
}).ToList();
But It does not work and gives the error
cannot convert from 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<string>'
I have realised that the error goes away only when the below code is in place.
private string GetUniqueSlug(string Uname, object allusers)
{
throw new NotImplementedException();
}
But this is the function that is supposed to be evaluated
//unique username for autogenerate
private string GetUniqueSlug(string Uname, List<string> allusers)
{
var slug = Uname.ToSeoUrl();
return allusers.Any(s => s == slug)? GetUniqueSlugInternal(slug, allusers) : slug;
}
When the condition is triggered to generate a new uname, the not implemented step gets the focus
It worked with this instead
List<string> allusers = (from MembershipUser c in Membership.GetAllUsers()
select new { UserName = c.ToString() }).Select(t=>t.UserName).ToList();

How to get list of all ApplicationUsers who are in certain Role from database by LINQ expression?

I want to get:
list of ApplicationUsers who are in role "NormalUser" to anybody
list of all ApplicationUsers only to Admins only.
I did this:
// GET: ApplicationUsers
public ActionResult Index() {
// if you are Admin you will get all users
if (User.IsInRole("Admin"))
return View(db.Users.ToList());
//if you are somebody else(not Admin) you will see only list of NormalUsers
//HERE I GET ERROR
var list = db.Users.Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList(); // here I get error
return View(list);
}
UserManager inside code above is: UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
But unfortunately my LINQ expresiion is incorrect. I get error:
LINQ to Entities does not recognize the method 'Boolean IsInRole[ApplicationUser,String](Microsoft.AspNet.Identity.UserManager`2[WebApplication2.Models.ApplicationUser,System.String], System.String, System.String)' method, and this method cannot be translated into a store expression.
Question: How to correctly get list of users who are in role "NormalUser"?
The UserManager.IsInRole function isn't supported at the database, but if your application can bear the weight of pulling the whole User table back from the database before applying your filter then you can just add a ToList between your Users table reference and your Where filter, i.e.
var list = db.Users.ToList().Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList();
I reached here for a good quick answer but could not find one. So decided to put on what I got for any other visitor who comes here. To get the List of Users in any particular Role, one can use this code.
public async Task<ActionResult> Index()
{
List<ApplicationUser> appUsers=new List<ApplicationUser>();
await Task.Run( () =>
{
var roleManager = new RoleManager<IdentityRole>( new RoleStore<IdentityRole>( db ) );
var adminRole=roleManager.FindByName("Admin");
appUsers = db.Users.Where( x => x.Roles.Any( s => s.RoleId == adminRole.Id ) ).ToList();
} );
return View( appUsers );
}
It would be useful to know how Roles and Application users relate.
If the user can only belong to one role, it would be fine for you to do something like this:
var list = db.Users.ToList().Where(x => x.Role == "NormalUser").ToList();
Id the user can be part of multiple roles, it would look something more like this:
var list = db.Users.ToList().Where(x => x.Roles.Contains("NormalUser")).ToList();
Hope this helps.

Using ASP.Net Membership, get all users

I'm trying to use Membership.GetAllUsers() to create a list of all of my users in the database. However, I have a model that I use that maps out the user properties (First Name, Last Name, Email, etc.).
How can I add all of the users into List<ManageUserViewModel>.
I've already tired:
List<ManageUserViewModel> model = Membership.GetAllUsers();
and then
MembershipUserCollection users = Membership.GetAllUsers();
List<ManageUserViewModel> model = new List<ManageUserViewModel>();
foreach (var item in users)
{
model.Add(item);
}
If you're explicit with the object type in the foreach loop, you'll be able to access the user object you're looking for.
For example:
var users = Membership.GetAllUsers();
var userList = new List<MembershipUser>();
foreach (MembershipUser user in users)
{
userList.Add(user);
}
Membership.GetAllUsers() returns a MembershipUserCollection which in practice is a list of MembershipUser, whereas you want a list of ManageUserViewModel which I assume is an internal class to your application.
You can use LINQ for this:
var model = Membership.GetAllUsers()
.Select(m =>
new ManageUserViewModel {/* set properties you need here */ }
)
.ToList();
Which is the equivalent of:
var users = Membership.GetAllUsers();
var model = new List<ManageUserViewModel>();
foreach (var item in users)
{
model.Add(new ManageUserViewModel { /* set properties here */});
}
I had the same challenge. mine was with vb not c# and .NEt version 4.5 using visual studio 2013.
I got all the solution from Microsoft website here
best of luck

Getting all ids and usernames from membership Asp Net MVC

I have no doubt on how to retrieve membership id from 1 single user:
currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
but I can´t find a way to retrieve all users id and usernames.
I tried this way:
MembershipUserCollection AllUsers;
AllUsers = GetAllUsers();
From that point I can´t find a way to retrieve Ids and Usernames from AllUsers.
Could I get some help from here?
I think you're looking for Membership.GetAllUsers()
var users = Membership.GetAllUsers();
foreach (MembershipUser membershipUser in users)
{
// membershipUser.UserName;
}
http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.getallusers.aspx

SimpleMembership MVC 4 get data from UserProfile having role in webpages_Roles

I have the following code. But there must be a more database efficient way to do this, because, correct me if Im wrong the number of database queries is
(1 + (qty of users with admin role))
With a new MVC 4 project the membership defaults are the tables UserProfile, webpages_Roles and webpages_UsersInRoles. I see lots of built in methods for Roles.Get*. If I want to avoid writing code like what I have below do I need to explicitly create a model for webpages_Roles and webpages_UsersInRoles as well as all the code first properties? Getting just the username from Roles.Get* doesnt suffice, I need the full UserProfile.
FYI the "UserRole" object below is just an enum
public ActionResult Admins()
{
var dbContext = new UsersContext();
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = new List<UserProfile>();
foreach (string username in usernames)
{
var adminUser = dbContext.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == username);
adminUser.Roles.Add(UserRole.SiteAdministrator);
adminUsers.Add(adminUser);
}
return View(adminUsers);
}
Yes, you don't want to do it that way. That's a very inefficient way.
Instead, use the tools as they were designed. For example, something like this:
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = dbContext.UserProfiles
.Where(x => usernames.Contains(x.Username)).ToList();
return View(adminUsers);

Resources