Visual Studio 2015 cannot connect to SQL Server LocalDB - sql-server

I'm just starting to learn C# and Entity Framework 6 ... and it's already far worse than I expected.
I have created a simple new project, and added EF6, while creating to database with Update-Database, I get:
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)
I haven't changed any config or anything, just created some classed and wanted to generate the database, here is the default connection factory:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="MSSQLLocalDB" />
</parameters>
</defaultConnectionFactory>
I even checked if the instance is running by running this command:
sqllocaldb info
which resulted in:
MSSQLLocalDB
ProjectsV13
and same for this:
SqlLocalDB.exe start
LocalDB instance "MSSQLLocalDB" started.
I have even tried to disable the firewall ... but nothing.
EDIT:
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="MSSQLLocalDB" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>

after i saw your project you just need change the app.config connectionStrings
<connectionStrings>
<add name="masterEntities"
connectionString="data source=(localdb)\MSSQLLocalDB;initial catalog=master;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework;"
providerName="System.Data.SqlClient" /></connectionStrings>

Related

SQL connection string from ASP.NET app does not work in WPF

Several ASP.NET applications are running on the server of our company.
Connections strings in web.config look like this:
<add name="somename"
connectionString="Data Source=SERVER\INSTANCE; Initial Catalog=DbName;User Id=user; Password=*******; MultipleActiveResultSets=True; Integrated Security=true"
providerName="System.Data.SqlClient"/>
and work perfectly with no errors.
But when I copy this connection string from web.config to app.config of my WPF app, I get the following errors:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
Or (if I remove Integrated Security from string)
Login failed for user 'username'.
Also I cannot log in via SQL Server Management Studio (causes the same errors).
My app.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="somename"
connectionString="Data Source=SERVER\Instance;Initial Catalog=DbName; User Id=user;Password=******;MultipleActiveResultSets=True;Integrated Security=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
</configuration>
Both username and password are 100% correct, SQL Server uses mixed authentication.
Managed to log in with sa login of SQL Server
Edit the registry using regedit. (Start –> Run > Regedit )
Navigate to: HKLM\System\CurrentControlSet\Control\LSA
Add a DWORD value called “DisableLoopbackCheck”
Set this value to 1

Change connection string in Entity Framework from localDB to Microsoft SQL Server

I'm trying to use SQL Server 2016 instead of localdb. When I try to change it in the web.config file from mssqllocaldb to v13.0
it gives me the following error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code.
Additional information: 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
You can read about the configuration at MSDN: Entity Framework Config File Settings
An example web.config could be:
<?xml version="1.0"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=MySqlServerInstance;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
</configuration>

Connection to SQL server with EnitityFramework 6 code first

Okay my project has a separate class library that has all the EnitityFramework version 6.1.3 code and settings.
I can not get this to connect to anything other than my local sql db
I can connect to my sql box 192.111.111.111\sql_box with SQL manager, SQL server object explorer and LINQpad. so it is there and connection string is correct.
I think I am now meant to be doing code based configuration
so my App.cong looks like this
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<entityFramework codeConfigurationType="MyProject.CodeConfig, MyProject">
</entityFramework>
</configuration>
and I have also create and class that derives from DbConfiguation
public class CodeConfig : DbConfiguration
{
public CodeConfig()
{
this.SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
but where do I put 192.111.111.111\sql_box
every time I run Update-Database in the package manager I get
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)
In the web.config or in the app.config.
<configuration>
<connectionStrings>
<add name="YOURDBCONTEXTNAME" connectionString="data source=SERVER;initial catalog=DATABASE;Integrated Security=false;persist security info=True;user id=USER;password=PASSWORD;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Your connection string needs to be in the web/app config file in the startup project.
The connection string in the class library (assuming it is not the startup project) is used when making model changes, migrations, etc.

How do I not use the App_Data folder in an ASP MVC4 application?

Everything works fine locally, but when I publish, I get the error below. I am using forms authentication, but I define my own connection string to a non-sqlexpress database. I don't understand why my application would need access to create a database (or anything else) in the App_Data folder, because my database is not/will not be there. Any help is appreciated.
Connection String:
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog={my db};Integrated Security=SSPI;MultipleActiveResultSets=True" />
</connectionStrings>
Error:
Access denied creating App_Data subdirectory
Description: For security reasons, the identity 'IIS APPPOOL\ASP.NET v4.0' (under which this web application is running), does not have permissions to create the App_Data subdirectory within the application root directory. ASP.NET stores the Microsoft SQL Express Database file used for services such as Membership and Profile in the App_Data subdirectory of your application.
Edit: It tells me how to fix the error by adding the App_Data folder and providing the correct permissions, but I don't understand why I need this folder at all, and if I can avoid changing permissions, I'd like to.
I think I finally figured out how to stop ASP from trying to create the ASPNETDB.MDF database in the App_Data folder automatically. What I found worked combined two existing stackoverflow answers:
Disable SQL Membership Provider (ASP.Net Forms Authentication)
It turns out that, on the production machine, the SQL membership provider was defined in machine.config. I don't think the ops team changed anything from the default Windows 2008 install, so that's probably generally the case for that platform.
To remove references to any SQL providers defined at a higher level include the following in your web.config
<membership>
<providers>
<clear />
</providers>
</membership>
<roleManager enabled="false">
<providers>
<clear />
</providers>
</roleManager>
<profile>
<providers>
<clear />
</providers>
</profile>
AspNet Role provider kicking in and it shouldn't be
To disable 'SimpleMembership' you can add app setting enableSimpleMembership with value="false" (web.config). This will prevent webmatrix from reconfiguring RoleManager.
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="enableSimpleMembership" value="false" />
</appSettings>
</configuration>
Check if the 'connectionStringName' property of the 'membership' node in your web.config is set to your connectionstring, like this:
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider"
type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DataContext"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
*<membership>
<providers>
<clear />
</providers>
</membership>
<roleManager enabled="false">
<providers>
<clear />
</providers>
</roleManager>
<profile>
<providers>
<clear />
</providers>
</profile>*

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.

Resources