Asp.Net Identity - A network-related or instance-specific error occurred while establishing a connection to SQL Server - sql-server

I have a code first EF application. The database has been created. Now I am trying to implement Login/Registration module using the Asp.Net Identity. I click the Register link but it gives me the above error.
Web.config:
...
<connectionStrings>
<add name="ConnStr_Dev"
connectionString="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;"
providerName="System.Data.SqlClient" />
<!--<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyApp-20170328111628.mdf;Initial Catalog=aspnet-MyApp-20170328111628;Integrated Security=True"
providerName="System.Data.SqlClient" />-->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
...
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Is there something that needs to be set separately?

1- Use below connection string. I am using here SQL express instance. Replace it with the name you use to connect through sql management studio.
<connectionStrings>
<add name="ConnStr_Dev" connectionString="Server=.\SQLEXPRESS;Database=MyDB_Dev;User ID=sa;Password=myPassword;Trusted_Connection=False;Persist Security Info=False;Pooling=True;Min Pool Size=20;Max Pool Size=100;Connection Timeout=300;multipleactiveresultsets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
2- Remove <entityFramework> tag from config file. You dont need it.
3- Make sure you are passing 'ConnStr_Dev' as string to DbContext constructor.

Locate the file IdentityModel.cs in the Models folder. In the ApplicationDbContext constructor the name of the connection string is passed in to the base class constructor - this needs to match the name of the your connection string in your web.config
So in your case
<connectionStrings>
<add name="ConnStr_Dev"
connectionString="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;"
providerName="System.Data.SqlClient" />
</connectionStrings>
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ConnStr_Dev", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}

Related

Web.Config SQL Connection

My Web.Debug.Config code:
<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=DESKTOP-RTOUFCH\\SQLEXPRESS;Database=NextLevel;Integrated Security=True;" />
</connectionStrings>
My CSharp code:
using System.Configuration;
using System.Web.Configuration;
using System.Data.SqlClient;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["NextLevel"].ConnectionString;
I keep getting a null reference error.
When I attempt to iterate through the connection strings, it finds one named "LocalSQLServer" which is not even in my web.Debug.config file.
What am I doing wrong?
That last comment by ThomasArdal:
I would also suggest you to publish web.config, web.debug.config, and web.release.config. If you have those files.
allowed me to figure out my problem.
I was updating web.debug.config when I should have been updating web.config.
<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=NextLevel;Integrated Security=True;" />
</connectionStrings>
Check with this instead!

How to add password connection string

How to add password in below mentioned connection string
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb;Persist Security Info=True "
providerName="System.Data.OleDb" />
</connectionStrings>
Use this
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString=" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb; User ID=*******; Password='*******';Persist Security Info=True "
providerName="System.Data.OleDb" />
</connectionStrings>
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\GateDb.accdb;Persist Security Info=True;User ID=myUsername;Password=myPassword;"
providerName="System.Data.OleDb" />
</connectionStrings>
Access connection strings
Try this,
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb;User Id=id;Password=pass;" providerName="System.Data.OleDb" /

Change the connection strings in MVC3 to publish in IIS

I need to change the connection strings in my mvc proyect because is local and now I need publish in a server but I dont have idea how write the connection strings and they are the next
<add name="cnn" connectionString="Data Source=SISTEMAS-PC\SQLEXPRESS;Initial Catalog=FoodGroups;User ID=FoodGroup; Password=Food" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(SISTEMAS-PC\SQLEXPRES)\v11.0;Initial Catalog=aspnet-MvcApplication1-20130730182253;Integrated Security=SSPI;AttachDBFilename=C:\Users\Sistemas\Desktop\proyectos TI\foodGroup2\foodGroup\App_Data" />
<add name="FoodGroupsEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=SISTEMAS-PC\SQLEXPRESS;initial catalog=FoodGroups;user id=FoodGroup;password=Food;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You have a web.config which should have a section for all your connection string.
What you need to do, is to have a web.release.config that will change the connection string when you build in release mode.
For example, web.config when you are debugging in your dev environment:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<connectionStrings>
<add name="YourConnectionString"
connectionString="Data Source=YourServer; initial catalog=YourDatabase; Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configSections>
And inside the web.release.config
<?xml version="1.0"?>
<connectionStrings>
<add name="YourConnectionString"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
When you are building, you will see that the string "YourConnectionString" will be replaced. This way, you can deploy/publish your application depending of the build mode (debug or release) without having to modify your code and just relying on web.config.

Getting error "The user instance login flag is not supported on this version of SQL Server." but not using this flag

I recently upgraded a SQL Server Express database I was using locally to SQL Server 2012 Developer. I started getting this error. A quick search pulls up tons of posts where the answer seems to be to remove User Instance=True; from your connection strings.
I checked and none of my connection strings have this flag. I tried searching the entire solution for "user instance" just to make double sure and it doesn't show up anywhere. Doubly weird is that I don't get this error right away. The first couple calls to the database work...
Has anyone else had a similar experience?
Here is the exact code that is causing my error:
public class BetterAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
var roleList = Roles.Split(',');
//if the user is in one of the roles in the list
foreach (string r in roleList)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//The error is consistently thrown here the second time this line
//executes...
if (filterContext.HttpContext.User.IsInRole(r.Trim()))
{
Here are the config sections I thought were relevant:
<connectionStrings>
<add name="BioSphereContext"
providerName="System.Data.SqlClient"
connectionString="Server=fake;Database=fake;User ID=fake;Password=fake;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;MultipleActiveResultSets=true;" />
</connectionStrings>
.
.
.
<sessionState mode="InProc" customProvider="DefaultSessionProvider" timeout="15">
<providers>
<add name="DefaultSessionProvider"
type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</sessionState>
.
.
.
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Some more details about my project in case it helps...
VS 2012
Entity Framework 5
Azure SDK 2.0
ASP.NET MVC 3
.net 4.5
This code uses ASP.NET Membership Roles Provider
if (filterContext.HttpContext.User.IsInRole(r.Trim()))
The machine.config shows
<roleManager>
<providers>
<add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>
Pointing to "LocalSqlServer" in the same file
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
There is the User Instance.
TODO: Configure your roleManager to use either another roles provider or the AspNetSqlRoleProvider to use a different connection string.
same goes for session (What is DefaultConnection? i don't see a connection string named like this), membership and profile.
So try:
<sessionState mode="InProc" customProvider="DefaultSessionProvider" timeout="15">
<providers>
<add name="DefaultSessionProvider"
type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="BioSphereContext" applicationName="/" />
</providers>
</sessionState>
Not sure what was wrong, but I deleted and re-cloned my git repository. Error went away.... never getting that day back... lol. I'll leave the post in case any of this is helpful to others.

How to connect to DB on SERVER for Asp.Net membership?

I've just upload my ASPNETDB.mdf using "Generate Scripts" into server.
The problem is, I don't know how can I connect to it for my Membership.(e.g LogIn Controls)
where is the ConnectionString?
update the Data Source tag in web config
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<<PATH Goes Here>>;Persist Security Info=False;
The connectionstring is in the web.config file.
Modify the web.config file for your application to redefine the LocalSqlServer connection string to point to the database.
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="server=.;database=aspnetdb;
integrated security=sspi;"/>
</connectionStrings>
If your Membership provider is not pointing to "LocalSqlServer", then you can modify that in the web.config as well.
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
/>
</providers>
</membership>

Resources