How to check user role in MVC 5 identity? - asp.net-mvc

I create a EF code first database identity system with custom roles. When i register a user i put him in a role, and in the database i can see that works on the AspNetUserRoles table.
But when i try to check the user role using User.IsInRole("admin") i.e, it always return false( i tried with low, upper, all the way case).
I need to put something in the webconfig? Or what im missing here? Its my first time developing with this new Identity system and i think that is a bit confuse.
In my immediate window:
User.Identity.Name
"teste06"
User.Identity.IsAuthenticated
true
User.IsInRole("admin")
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Exception:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

It seems that the role Manager Is Activated
and it is trying to create an SQL Express Database
to validate roles, i 've had the same issue i solve it by adding this code to my
web.config file
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>

You have to make sure you have this in your startup class
app.UseSignInCookies();
Also, I'm guessing your DbContext class is derived from IdentityDbContext<ApplicationUser>or IdentityDbContext.
If not, make sure you do.
Look this article for reference.
Similar post relating to your problem can be found here

Related

How to use existing SQL database in my separate project under one solution in ASP.NET MVC application

I have created 2 separate projects under one solution where one project is a class library. I have created an ADO.NET Entity Model from my existing database into this. Another project is an ASP.NET MVC web app.
I have used Individual User Authentication and wanted to use registration and login facility provided by this.
Now I am unable to use my existing database as this project is creating new database by itself when first runs.
Please guide me how to use existing database. I have given reference to my ASP.NET MVC project. These are my connection strings. Please help me.
<connectionStrings>
<add name="LAPTOP-71D4QMB6"
connectionString="Data Source=LAPTOP-71D4QMB6;Initial Catalog=VCAdvertiserDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="HBDBEntities"
connectionString="metadata=res://*/Data.HBModel.csdl|res://*/Data.HBModel.ssdl|res://*/Data.HBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=LAPTOP-71D4QMB6;initial catalog=VCAdvertiserDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Error thrown is:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
You have to copy the connection string from the app.config of your class library to the web.config of the MVC project. You need to put it in both the root web.config and also have to put it in the shared web.config under the shared views folder. That last may not be needed but it also doesn't hurt.
That worked for me.
Joey

Login failed for user 'sa' ASP.NET MVC page

I'm trying very hard to go from Entity Framework 5 to 6. After solving a SimpleMembership issue that was in my Web.config I have the following error :
Login failed for user 'sa'
Anytime I try to reach a tab (on my page) that requires SQL Data display.
Here is my connectionStrings (the relevant one being DefaultConnection) :
<connectionStrings>
<add name="DefaultConnection" connectionString="packet size=4096;Data Source=MMSDEVNEW\SQL2008;Initial Catalog=CRAV34;User ID=sa;Password=*****;" providerName="System.Data.SqlClient" />
<add name="CRAV34Entities"
connectionString="metadata=res://*/Models.CRA.csdl|
res://*/Models.CRA.ssdl|
res://*/Models.CRA.msl;
provider=System.Data.SqlClient;
provider connection string="data source=MMSDEVNEW\SQL2008;
initial catalog=CRAV34;
persist security info=True;
user id=sa;
multipleactiveresultsets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
I read that this may be a permission issue or changing the security properties from the SQL Server Management Studio to "SQL Server and Windows Authentication mode". All of this has been done. The login and password are valid in the connectionString.
What could possibly cause this issue?
Just add Integrated security=true in your connection string
<add name="DbConnectionString" connectionString="Data Source=LENOVO\SQL2K12;Initial Catalog=EFCodeFirst;User ID=sa; Password=xxxxx;Integrated security=true" providerName="System.Data.SqlClient" />
If you are sure the SQL Server is in "mixed mode", and that the password is correct for the "sa" account, I can only suggest it to be that the "sa" user doesn't have access to the named database.
In SQL Management Studio, expand the database branch, then security, then users, and check if the "sa" user appears in the list.
The best way to diagnose this error is to try and connect to the database server using SQL Management studio, logging in AS the user in the connection string.
If you can log in, see if you can see your target database in the tree on the left.
If you can, try and open the database node and see if you can see all the tables.
If you can, see if you can run a select query against one of those tables.
If you can do ALL of the above, then it's NOT an issue with SQL server, but rather your connection string.
However, I've never seen that error come up when it's NOT a SQL configuration issue.
Try it with SQL Management Studio from the same machine you're code is running and it should give you more information about what's wrong.
Edit your post / reply to this answer if this doesn't solve it, explain what you tried and what the result(s) were, and I'll update the answer to reflect what I'd try next!
edit 1:
Try changing your connection string to the following:
packet size=4096;Server=MMSDEVNEW\SQL2008;Database=CRAV34;User ID=sa;Password=*****;
edit 2:
If this connection string is valid, it could actually be the second one that is causing a problem, as EF would likely choose that one unless explicitly told to use the "default" one.
As this second connection string doesn't have a password specified, it might be this that's causing the error.
Can you try it again with a password specified?
If you are using Integrated security=true, it could be the account you are running under does not have permission.
Try opening Visual Studio running as a different User. ( the user has permission on the database).
Use Shift and right click on the pinned Visual Studio menu.

Trouble deploying EF CodeFirst to server

I have a CodeFirst web application that originally used LocalDb. I changed the connection string to:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SqlExpress;Initial Catalog=aspnet-BatchFindings;Integrated Security=True" />
And I created the appropriate database using Server explorer.
I am using WebDeploy to publish to a Windows Server 2012 instance running IIS8.
After publishing, I was unable to use the application; it did not have permissions for the database. I then changed the identity to a user account, and now I do not get database errors. Except the application does not appear to save any data to the database. I am at a complete loss - any help is appreciated!
Recap:
Entity Framework, Code First
Web Deploy to IIS 8
Custom Application Pool, identity set to a user account
Data not being stored in database.
EDIT: I would love to be able to simply use Web Deploy and have it use its own database (so it does not get test data from mine) but this is just so frustrating! I am publishing, the connection string should work, not sure where I am going wrong.
Stupid question but are you calling DbContext SaveChanges() method after data manipulation - data saving works when testing?
Also you can use different web.config files when testing (Debug) and deploying (Release version).
So I inadvertently figured out the reason why it was not saving. For some reason in my test environment everything worked, but when it was pushed out, I needed to add the following line:
db.Entry(obj).State = System.Data.EntityState.Added;
I checked out the tutorial, which seemed to work until it went into that Grant.sql file. There is no option in Visual Studio to connect.
What I ended up doing in that case to get the database working was set my Application Pool to run under a user identity I created for this purpose, while setting Load User Profile to True. You can also run as LocalSystem (as long as you create the following folder: C:\Windows\SysWOW64\config\systemprofile\Desktop - this tricks the system into thinking the LocalSystem account is interactive).

Firebird and ASP.NET MVC

Have just started converting an existing job tracking system into an ASP.NET MVC application. I'm failing miserably at getting this thing off the ground. I'm getting this error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
With the following connection string
<add name="ApplicationServices"
connectionString="User ID=sysdba;Password=masterkey;Database=localhost:C:\\USINGFIREBIRD.FDB;"
providerName="FirebirdSql.Data.FirebirdClient" />
FirebirdClient has been added to windir\assembly using gcutil
This is probably a very dumb question, but does USINGFIREBIRD.FDB have to exist? Or will it be automatically created? Regardless, with the file created it does not work.
Edit:
Ok so in the end I was having so much trouble that I decided to start fresh.
First thing I discovered was that the .NET 4 assembly cache has moved to windows\Microsoft.NET\assembly. I saw that FirebirdClient was not in here so I had to figure out how to get it in there. I used Visual studio 2010 command prompt to add the assembly with GCUTIL.
Then I followed the information here
Then create a new asp.net mvc project, register your database in the server explorer, then add add an ado.net model class and have it auto generated from your database.
I'm writing this rather hastily as I'm about to leave work, hope it helps someone.
The file must exist and it must be a proper Firebird database, ie you can't just create an empty file named "USINGFIREBIRD.FDB". To create an Firebird database you can use the isql command line tool installed with Firebird.
BTW the error message says The server was not found or was not accessible - are you sure the Firebird service is running?
Your connection string part "Database=localhost:C:\\USINGFIREBIRD.FDB;" is wrong. If you database is a file you don't need the "localhost" just the db file path.
Here you can see valid connection strings for Firebird.

Web Site Administration Tool Not Working with ASP.NET MVC

I'm just starting with ASP.NET MVC and I was trying the Authentication with this new architecture.
So, I started following a tutorial in the official site and, while I was trying to add some users through the Web Site Administration Tool, I found this error:
There is a problem with your selected data store. This can be caused by
an invalid server name or credentials, or by insufficient permission.
It can also be caused by the role manager feature not being enabled.
Click the button below to be redirected to a page where you can choose
a new data store.
The following message may help in diagnosing the problem: Could not load type
'MyMvcApp.MvcApplication'.
Now, the only thing I changed in the web.config was the connection string and, I'm sure the connection string is not the problem (is the same I'm using in other project).
EDIT: Here is the connection string: "Data Source=myMachine\SqlExpress;Initial Catalog=TestDB;User ID=TestUser;Password=123456"
I tried several things and googled a lot, but nothing worked.
So, any ideas? as I said, I did not change anything in the web.config besides the connection string.
Thanks in advance,
Found the problem: I just need to COMPILE the solution BEFORE starting the WSAT.
Thanks to everyone for your answers.
Well, like the message says, this feature requires real management enabled, and the default MVC web site template has this disabled. Go into Web.config and change:
<roleManager enabled="false">
to
<roleManager enabled="true">
One other thing to check: Make sure that when you create the SQL Membership Provider metadata you connect as a user who will be useful at runtime. In other words, if you connect as sa, then the metadata will be in the dbo schema. But if you connect as yourself, then the metadata will be in your schema, which isn't necessarily useful to other applications. You should run SQL Server Management Studio in order to verify in which schema the metadata is placed.

Resources