Exception when connecting to database on client machine - c#

I have created a WPF application which used entity framework and SQL server 2012 for database. It runs fine on my machine. But when I ran this on client machine I received exception. This happens when I am trying to add a record in database.
Exception: The underlying provider failed on Open
Inner 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, ........
Connection string:
<connectionStrings><add name="SchoolModelContext"
connectionString="metadata=res://*/SchoolModel.csdl|res://*/SchoolModel.ssdl|res://*/SchoolModel.msl;
provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;
initial catalog="SCHOOLDB.MDF"
integrated security=True;MultipleActiveResultSets=True;
App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>

The error message ... it gives hints that are sometimes rabbit-trails. Basically the error is saying "I can't connect to sql Server, there is something wrong".
But.. you say you "installed SqlLocalDB" on the client.
Did you "wire up" the new database (SCHOOLDB)?
http://msdn.microsoft.com/en-us/library/hh212961.aspx
A. Creating an Instance of LocalDB
The following example creates an instance of SQL Server Express LocalDB named SCHOOLDB using the SQL Server 2012 binaries and starts the instance.
SqlLocalDB.exe create "SCHOOLDB" 11.0 -s
Aka, did you run something like that?
(Other info from the MSDN article that may not be relevant to this question)
B. Working with a Shared Instance of LocalDB
Open a command prompt using Administrator privileges.
SqlLocalDB.exe create "SCHOOLDB"
SqlLocalDB.exe share "SCHOOLDB" "SchoolSharedLocalDB"
SqlLocalDB.exe start "SCHOOLDB"
SqlLocalDB.exe info "SCHOOLDB"
REM The previous statement outputs the Instance pipe name for the next step
sqlcmd –S np:\\.\pipe\SCHOOLDB#<use your pipe name>\tsql\query
CREATE LOGIN NewLogin WITH PASSWORD = 'Passw0rd!!#52';
GO
CREATE USER NewLogin;
GO
EXIT
Execute the following code to connect to the shared instance of LocalDB using the NewLogin login.
sqlcmd –S (localdb)\.\SchoolSharedLocalDB -U NewLogin -P Passw0rd!!#52
EDIT ::: (only read above this line for a general understanding...see below on steps I actually did)
Ok, the above is a little confusing because its hard to know if you're dealing with the ~instance or the database.
Let's try this:
SqlLocalDB.exe create "MySuperCoolLocalExpressInstance"
SqlLocalDB.exe share "MySuperCoolLocalExpressInstance" "MySuperCoolLocalExpressInstanceSHARED"
SqlLocalDB.exe start "MySuperCoolLocalExpressInstance"
SqlLocalDB.exe info "MySuperCoolLocalExpressInstance"
NOW, very important, get YOUR very unique "named pipe" value.
np:\\.\pipe\LocalDB#<use your pipe name>\tsql\query
Copy your SchoolDB.mdf and SchoolDB.ldf to :
c:\MyCoolLocalDatabaseFiles\
Now set your connection string to this:
<connectionStrings>
<add name="SchoolModelContext"
connectionString="metadata=res://*/SchoolModel.csdl|res://*/SchoolModel.ssdl|res://*/SchoolModel.msl;
provider=System.Data.SqlClient;provider connection string="data source=np:\\.\pipe\LOCALDB#MYUNIQUEPIPENAME\tsql\query;attachdbfilename=C:\MyCoolLocalDatabaseFiles\SchoolDB.mdf;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
But substitute "MYUNIQUEPIPENAME" for your value.
The key is "attachdbfilename". This is how to "on the fly" attach a database.
You have some alternates for using the named pipe syntax. See:
http://www.connectionstrings.com/sql-server-2012
"User Instance on local SQL Server Express"
enter code here

Related

I can't connect to a local SQL Server instance via Entity Framework using Windows authentication

I can't connect to my local SQL Server Express instance via Entity Framework. When I try to run the update-database command, I get this error message.
Login failed for user ''. Reason: An attempt to login using SQL authentication failed.
Server is configured for Integrated authentication only.
Error: 18456, Severity: 14, State: 58.
From what I understand, Visual Studio is attempting to log in to SQL Server via a user account even though I've requested that Windows authentication is used in the connection string.
I can still access the server via SSMS.
What I've tried. None of which helped
Different variations of the connection string
Opened port 1433
Created a test UDL file to test the connection.
A clean reinstall of SQL Server Express (not sure I managed to clean up all the files)
Checked the SQL Server browser is running
Checked server instance is running
Enabled TCP/IP & named pipes
Tried connecting via tcp which works
Added Integrated Security=SSPI to connection string
Changed server to accept Windows authentication and SQL Server authentication.
Restarting PC
This is a new laptop on windows 11, I don't know if that is causing any issues as I've never had an issue with this process on Windows 10.
I seem to have two instances; .\SQLEXPRESS & (localdb)\\MSSQLLocalDB I'm not sure if this is causing some conflict or if this is the intended behaviour.
Here is the connection string, I pulled this from the server explorer within Visual Studio so I am pretty sure this is correct. On top of that, I have tried numerous variations of this to attempt to fix the issue
"DefaultConnection": "Data Source=LAPTOP-51LB4QTQ\\SQLEXPRESS;Initial Catalog=MicroBlog;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
This is where I get the connection string in my Program.cs file
builder.Services.AddDbContext<BlogContext>(opt => opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
At this point I'm completely lost, I've read a lot of articles but have not come across any fixes. I'm not a dba just a programmer so have limited knowledge of this side of SQL Server.
You may try like below:
In Web.config file:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=SUBRATATALUKDER;Initial Catalog=MyDB;Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
In appsettings.json file:
"ConnectionStrings": {
"DefaultConnection": "Server=SUBRATATALUKDER;Database=MyDB;Trusted_Connection=True;TrustServerCertificate=True;",
}
Note:
Server Name = SUBRATATALUKDER
Database Name = MyDB
100% tested.

ASP.NET connectionString for mdf file not working

I am using I am using Visual Studio 2017. I just created a brand new mdf file in my project (Right click on App Data -> Add New Item -> SQL Server Database) and I called the file TestDatabase.mdf
Now I am trying to connect to it via a connection string:
<add name="TestConnection" connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|TestDatabase.mdf;Database=TestDatabase; Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
Next I created a Model and then Created a EntityFramework Controller, but now when I goto the controller index method I get 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. 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)
What am I doing wrong?
Make sure you testDatabase.mdf available in App_Data folder.
<connectionStrings>
<add name="ConnectionName"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
This connection string that you have written is incorrect.
<add name="TestConnection" connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|TestDatabase.mdf;Database=TestDatabase; Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
I assume that you have SQL Express installed in your system. This will provide a local instance of SQL to run on your machine.
As you said you are using Visual Studio 2017, you can follow these steps to get the correct connection string
Open Server Explorer
Right Click on your Database and click Properties
A property window will open, copy the ConnectionString and make sure it looks like this:
<add name="YourDbName" connectionString="Data Source=YourComputerName\SQLEXPRESS;Initial Catalog=YourDbName;Integrated Security=True" />
And now talking about this:
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 are getting this error because it is not getting the instance name to connect to the database. In my example, SQLEXPRESS serves as an instance name. If you don't have SQLEXPRESS you can download it from here:
https://www.microsoft.com/en-in/sql-server/sql-server-editions-express
You can follow the prompt and install this package in your system.
Once you install this, your instance will get activated. Connect your Db once again.I am sure it will work.
In case, if this error comes again, you can follow these steps:
Hit Windows + R and type services.msc and hit OK
From the given lists, search for SqlServer (SQLEXPRESS) and click start the service. This will activate your instance once again and your database is now ready to connect to your application.
Hope this helps.

SQL suddenly fails to generate a user instance

I have an application deployed to Windows Server 2016 VM on IIS, using SQL Express.
It has been working perfectly all day, but suddenly I am seeing this error when trying to log in:
Failed to generate a user instance of SQL Server due to a failure in copying database files. The connection will be closed.
This is after making no changes to the code or web.config whatsoever.
I have tried these solutions already:
Restart SQL service and Delete all contents in C:\Users\SKotze\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
Add User Instance=true to the connection string
Ran this bit of SQL before restarting the service:
exec sp_configure 'user instances enabled', 1.
GO
Reconfigure
This is driving me crazy I just dont't understand why it suddenty stopped working.
Please let me know if I can provide any further details.
My connection string:
<add name="WebEntities1" connectionString="Data Source=ServerName\SQLEXPRESS;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient" />

Connection String to SQL Server 2014 Failing

A developer friend and I could not get a connection string to work on my PC.
I'm calling to a local db instance which is Management Studio 2014 (one of the free editions).
It fails on connection.Open();
The Code is:
string conn = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ToString();
IDbConnection connection = new SqlConnection(conn);
connection.Open();
App.Config is:
<connectionStrings>
<add name="DatabaseConnection"
connectionString="data source=MIKE-PC; initial catalog=dbname;integrated security =True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The Error is:
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll
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 Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
There are many possible issues that you can check to correct this:
Make sure your database server is running: open run or shortcut Window + R, type services.msc, hit enter. Make sure the SQL Server (SQLEXPRESS) service is running.
Open your SQL Management Studio. Try to connect to your database from there to make sure your server name (data source) and database name (initial catalog) are correct.
Make sure your database can be accessed using Integrated Security. You can tell that it does if you can connect to your database using "Windows Authentication" from your MS SQL Server Management Studio.
Hope this help.

Entity Framework Connection to localDb

I am trying to follow the pluralsight course ASP.NET MVC 4 Fundamentals. But can't have my database connected.
Here is the error I got:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
I have visual studio 2013 professional and SQL server 2012 installed on my machine. When I installed my SQL server, I created a server name "ABC" on my computer.
I have also installed sql localdb 11.0 separately, but it seems VS can't find the localDb connection. When I check Server Explorer -> add Connection, under server name list, only "ABC" is shown up.
Here is the connection string.
I also tried to use "Data Source = ABC; ...." it doesn't work either.
Update
Here is my connection string
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-eManager.Web-20141223223418;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-eManager.Web-2014122322341‌​8.mdf" providerName="System.Data.SqlClient" />
You could try this
In server explorer, right click, Choose Add Connection
enter (localdb)\v11.0 in as the server name
Choose your database and press connect
Right click properties on your new connection
Use that connection in string in your default connection
I.e.
<add name="DefaultConnection" connectionString="<Paste-connection-string-here>" providerName="System.Data.SqlClient" />
If that doesn't work, lets try starting it from the command line
Open command prompt
Run SqlLocalDB.exe start v11.0
Follow original steps , use the named pipe as your server name
If that doesn't work, lets try and connect via named pipes
Open command prompt
Run SqlLocalDB.exe info v11.0
Copy the Instance pipe name that starts with np:...
Follow original steps , use the named pipe as your server name
e.g
Run this command to make sure what is the version of your LocalDB
sqllocaldb info
So in my case the version is MSSQLLocalDB then the connection string will look like this
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=IdentityManagerDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
To add on to TheGeneral use view - SQL Server Object Viewer and look immediately under the "SQL Server" object. You'll see the name of the connect looking something like "(localDB)\ProjectsV13" Hand enter that into the connection box then you can browse the server for the database you want to use.

Categories

Resources