Ok I have seeded some roles which can be found in the SQL database in the table AspNetRoles
and the users can be found AspNetUsers.
I have also found a bunch of aspnet_ tables (I think they are old WebForm ones). Within a view I am calling #Roles.GetAllRoles() which is returning no results. the aspnet_Roles table has no records. So it may be checking there. But that seems unlikely as the seeded roles are being created thusly:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
Which in my little knowledge of MVC5 would suggest that Roles.GetAllRoles() would return the correct result.
I am using this #model EUWebRole.Models.IdentityManager also tried ApplicationUser with no change in results.
So to the questions:
1) How do I get the list of Roles?
2) If I am using the wrong "tables" how do I set it so that it is using the correct tables?
Any ideas would be greatly appreciated.
You're aspnet_tables are old from either the default MembershipProvider or the SimpleMembershipProvider (either way it doesn't matter they should be removed).
MVC 5 uses Identity 2.0 by default. If you need to do anything with roles you need to use the RoleManager.
Related
Currently I'm doing a check :
#if(this.User.Identity.Name=="DOMAIN\\USERID"){
This works great but I'd like to have multiple users(2-3) to check for. I'd also like to not have it hard coded. Is there a way to do this in the web.config or in a database?
You could add a list in the config...User1,User2 etc and then use linq and .Any() against this list?
var users = "user1,user2,user3".Split(','); //list will come from your config
bool result = users.Any(u => u == this.User.Identity.Name);
Also, since you're using MVC, if you want to use authorization for controllers etc, you can use the [Authorize] attribute. See this SO link too Authorize attribute in ASP.NET MVC
Maybe use roles instead then add the relevant users to that role? This would make it easier to expand on in the future, plus you don't have to hard code a list of users.
I'm having problems getting Google OAuth to work with the default MVC4 Internet Application project template in Visual Studio 2012.
After redirection to Google and subsequently registering a username I'm getting a MembershipCreateUserException thrown on line 276 in the AccountController with the message:
The username supplied is invalid.
The failing line of code is:
OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
I've checked the database and the UserProfiles table contains the username I enter as expected and I've tried with various combinations of username.
Have I missed something as none of the linked articles within the source code suggest anything else needs configuring?
I think I figured it out. The OAuthWebSecurity.CreateOrUpdateAccount needs to have a user in the Users table.
The thing is, the method will "create" a new record in the webpages_OAuthMembership table, which has a foreign key to the users table.
Thus, in order to make your call work either create a new user first via WebSecurity.CreateAccount or write some manual code to add a user to the table.
I went for the WebSecurity.CreateAccount and used the GeneratePassword method to work around that bit.
Hope it helps.
First i would like to leave my experience here. (asp.net mvc4)
Change the dbcontext for the SimpleMembership provider. Go for Filter folder-> Open InitializeSimpleMembershipAttribute. then do changes like this. So it will includ membership tables in your database.
WebSecurity.InitializeDatabaseConnection("ChangeYourDbContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
Go for AccontController. Find the UserContext, which is by default using the defaultConnection string. Go for UserContext Declartion (f12).
and override the UserContext Connectionstring to your actualDbcontext
public UsersContext(): base("YourAcutalDbContext")
{
}
OK so I've created a new table within the existing aspnetdb.mdf database aspnet_Groups, and added and related a foreign key to the aspnet_Users table GroupId.
So users table now goes:
ApplicationId
UserId
UserName
LoweredUserName
MobileAlias
IsAnonymous
LastActivityDate
GroupId //<--- Added by me, and related to aspnet_Groups table
Groups table only has GroupId and GroupName so it's pretty simple actually.
What I wanna know, is how do I save and get data for this field/table from within MVC application. Or does this have to be done another way?
Edited
I would not recommend intervining into aspnetdb working ...
If you need to - create your own table and link it to aspnetdb.
More control, more customization, less bugs introduced to internal MS authentication...
Great posting about this Storing data in a Custom table within ASPNETDB.mdf vs. storing information about a user in a profile
But again, there's no right answer to your question - as long as it works and having good usability and readability - its fine.
If you can use Roles as your groups - this can do the trick, but if not, I'd define additional table, rather than intervining into prebuilt one. This is my opinion.
Edit 2
There are many ways you can work with aspnetdb. You can even embed it into your own database. Like this: Configuring ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005
Answering your particular question: you can access aspentdb via authentication API:
string userName = Membership.GetUserNameByEmail(emailToCheck);
if (userName != null)
or override membershipprovider, roleprovider and securityprovider or even access directly like described here
Membership, Role, and Security
Hope this helps!
I am relatively new to MVC. I am trying to just display the contents of a remote SQL Server table on a page. It is READ ONLY, and nearly everything I find online is utilizing the Entity Framework or something similar which is overkill for what I am after. I just need to print all the rows from a table out to a view.
So my questions are:
should I just hack the sqlconn and everything into the view that I want the data printing out to?
Or should I add the sql in that view's controller?
Create a model and somehow get that data back into the view?
I know step #3 is the 'correct' way to do it, however I am looking for something simple and quick. :)
Thanks everyone!
You say EF is overkill, but that's the easiest way to do this. Maybe use Linq to SQL, since that's more lightweight. This is all there is to it:
Generate the EF / L2S entity classes
Instantiate the database context in the controller, and get all records
Return the IEnumerable records to the view
In the view, use #Html.DisplayForModel()
Here's a simple example. Note that returning the database entity classes is considered bad practice, you should map / automap them to a View Model type class first.
Home Controller
public ActionResult Index()
{
MyEntityModel[] items = MyDatabaseContext.GetAllRows();
return View(items);
}
Home/Index View
#model IEnumerable<MyEntityModel>
#foreach (MyEntityModel item in Model)
{
#Html.DisplayFor(m => item)
}
Without EF / L2S it's almost as easy, but you'd have to create your own entity / wrapper class for the database records and populate them manually.
There are also scaffolding projects for MVC that will generate repository and controller classes, as well as Razor views. See for example MVC Scaffolding on NuGet.
Once you get used to forcing yourself to use Entity Framework for even your "small" applications then and only then will you truly understand that is it the simplest way.
Sure, if you come from a background of memorized ADO.NET dataset/datatable/datareaders etc.. then sure you have projects with "canned" operations that you port over and modify but it is truly just old and cost you more time in the long run.
Use EF
Use multiple projects in a solution
Use a repository pattern if you can, it pays off in dividends for reasons you will discover
Keep your controllers "skinny"
Dont' use a "ViewModel" just to use / do it.
The SOC of having View and Controller are critical, but the Models folders does not need to be used, you can wire things up without it if you want, just pay attention to where your "model" is and abiding by SOLID principle etc..
I'm using NerdDinner as a guide for my first MVC/LINQ to SQL project. It discusses the use of the ViewModel pattern when a View needs data from multiple sources - in their example: Dinners and Countries (serves as the drop down list).
In my application, the problem is a bit different. It's not so much different data, rather data linked via a key constraint. I have a Story table that links to aspnet_users via the UserId key. I would like to have easy access to the UserName for each story.
Since I'm using the repository pattern and returning IQueryable in some cases for deferred execution, I'm struggling with the correct way to shape the data. So I'm using this VideModel pattern right now to make it work but not sure if it's the right way.
Instead of returing IQueryable Story (which wouldn't work since I need the UserName), I'm returning a new custom class UserStory, which has a Story property and a string Username property.
What are your thoughts?
It seems like your question has less to do with MVC as it is simply a question about how to access the story data based on the username string.
Would it be possible to create a view in your database with all the UserStory data, the username, along with userid in it? That way, you could select from the view based on the username you have.
To create the view, you would simply have to do a join between the user table and the userstory table based on the userid.
After that, you could still use the repository pattern with the IQueryable being returned.
If you are wanting to do updates, it would be simple to do since you still have the userid, and would be able to link back to the actual table which would need the update.
If you look at Kigg, you will see that they mess about with the initial model to create custom ViewModels. That's the thing that NerdDinner doesn't cover in any detail. You could create a StoriesWithUserName class that inherits from Stories, but adds a new property - UserName. Then you return that to your View which would inherit from IEnumerable<StoriesWithUserName>
[EDIT]
Oops. Didn't spot that you already did this :o)
Using the repository pattern and returning an IQueryable of Stories is fine. The relationship allows you to access the the username value something like this >>
Assuming you are returning the IQueryable in your model object:
foreach(Story story in Model.Stories)
{
// do something with the value
response.write(story.aspnet_user.UserName);
};
Your Repository method would look like this:
public List<Stories> GetStories(Guid UserId)
{
return datacontext.Stories.Where(u => u.UserId = UserId).ToList();
}
The relationship will automatically provide you with access to the UserName value in the foreach loop i first mentioned. nothing more is required.
I'm not sure why your pagination control failed on Count() though??
Hope this helps