ADO.NET Customer Error System.Data.SqlClient.SqlException (0x80131904) - c#

I've created an application that works perfectly on my PC using C# and SQL Server 2014.
My connection string is:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Youssef\Desktop\gone\gone\gone\gestion_incidents.mdf;Initial Catalog=BG_ONE;Integrated Security=True
I know that the connection string is the problem but how can I create a connection string that works on all computers?

Replace your database file path to a generic path that automatically get the location of the project data folder and it will not cause problem when you move project to another location. Follow below steps:
Step 1: First Add App_Data folder in your project and add database file there.
Step 2: Change your connection string replace path before the database file with |DataDirectory|
Example:
<connectionStrings>
<add name="ConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\nwind.mdb" providerName="System.Data.OleDb" />
</connectionStrings>
If you follow the above steps then your connection replace C:\Users\Youssef\Desktop\gone\gone\gone with |DataDirectory|. See modified connection string as below:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Youssef\Desktop\gone\gone\gone\gestion_incidents.mdf;Initial Catalog=BG_ONE;Integrated Security=True

Related

Publish .mdf file with desktop app setup using C#

I have developed an application that uses SQL database. My challange is to be able to ship the database with the app itself. When i package my mdf file with the setup, it gets deployed. However it is not able to connect to it.
I have made following as prerequisites
When installing, it downloads and installs all the prerequisites.
I am also using following connection string to connect to it.
<connectionStrings><add name="MyDBContext" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=" Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDB.mdf; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
This setup works fine when installed on my machine. Any idea how this will work on simple machines?
Finally I got it working after changing many things. First off, the connection string itself. It was
<connectionStrings><add name="MyDBContext" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=" Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDB.mdf; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
But since only SQL Express 2012 is being installed on the destination machine (See the picture in question above) during setup, this was not going to work. So changed it such that it uses SQLServer Express's default instance name
<connectionStrings><add name="MyDBContext" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=" Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|MyFolder\MyDB.mdf; User Instance=True; Integrated Security=SSPI; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Please note that i have added a folder after |DataDirectory|. Idea is to create a folder within AppData so it would end up creating a folder in C:\users\me\AppData\MyFolder\MyDB.mdf
I also set the User Instance as true because otherwise it wasn't working from AppData folder.
Next I added the code to update the DataDirectory to my desired location, which is in AppData folder as
AppDomain.CurrentDomain.SetData("DataDirectory",Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
I did this change in the main of my program file

How to connect to mdf of local database , which is giving "sql network interfaces error 52"

I have started a new project which i will be displaying the data in the grid view, where i have to consume the .mdf file. Here the problem starts. I am able to open the .mdf file in sql data base, but not by selecting as servertype: "database engine" but by selecting "SQL server compact edition", only then i am able to open the .mdf file in sql studio and create the tables and everything.
I have creted tables and everthing, and now comes the part where i have to give the connection string in the web.config file. I have defined as below.
connstring:
connectionString="Data source=.\SQLEXPRESS\v11.0;Integrated Security=SSPI;AttachDBFilename=C:\Users\usr\Downloads\InterviewSolution\Backup\myproject\App_Data\myproject.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
and i am not able to connect. I have tried to test the connection while configuring the database schema to sqldatasource, but it is failing with below error.
error: "sql network interfaces error 52"
I thought it was permissions issue, and gave full permissions to the file by adding NFS account to it. but still the same, not able to connect through project.
Can anyone pls help me on this, why is the file able to connect to sql studio, but was not able to connect through project.
Is my connection string wrong ??
I always use this template for this case of connection string:
<connectionStrings>
<add name="MyConn"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myproject.mdf;
Integrated Security=True;
User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Formatting MySQL initialization string? [duplicate]

I have an ASP.Net MVC application which runs fine on my local development machine. But when deployed to IIS7 gives the following error when trying to log in:
Format of the initialization string does not conform to specification
starting at index 0
Most people who post this error resolve it by changing their connection string in some way. However my connection string on the local and deployed application are the same. The connection string is like this:
<add name="ApplicationServices" connectionString="Data Source=*server*\*instance*;Initial Catalog=*database*;Integrated Security=True;"
providerName="System.Data.SqlClient" />
What is causing this error in my case?
Format of the initialization string does not conform to specification
starting at index 0
Web.config :
<connectionStrings>
<add name="TestDataConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=TestData;User ID=satest;Password=satest"
/>
</connectionStrings>
In aspx.cs Page the code must be written in the below format :
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["TestDataConnectionString"].ToString());
Web Deployment tool created wrong line in config when I checked Enable CodeFirst Migrations check-box.
In my case I accidentally wrote "password:" instead of "password=" in my conn string
Check to make sure the credentials are correct for the connection string in Web.config. Mine was missing the password for the account with permissions to the database.
I encountered the same error. In my case it was the config transform not working properly.
There is an issue with config transforms when it comes to connection strings.
Some reference:
MSBuild web.config transforms not working by drneel
Replaceable token issue with config ConnectionString transforms by Francis
Also one can write the code in the aspx.cs page as
using (IDbConnection dbConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
// TODO: Write SQL Stored Procedures or SQL Statements using Dapper
}
For those who would like to find out more about Dapper.
Hope this helps.
If you have been using the Visual Studio Publish Wizard for deployment and checked the Execute Code First Migrations check box in Settings, a new ConnectionString is automatically added to the Server Web.config file, similar t to the 2nd line below:
<add name="LCWeb3Context" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LCWeb3;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\LCWeb3.mdf" providerName="System.Data.SqlClient" />
<add name="LCWeb3Context_DatabasePublish" connectionString="LCWeb3Context_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
First, notice the added connection string contains "ConnetionString": I think it should be "ConnectionString"! But that's not the solution.
To avoid the "Format of the initialization string does not conform to specification starting at index 0" error, do the following in the Publish Wizard:
In the Settings, select Configuration: Release
In the Settings,don't forget to paste your Connection String in the
"Remote Connection String" field
In the Settings, check Execute Code First Migrations
When doing the above, the connection string added to the Server Web.config reads:
<add name="LCWeb3Context_DatabasePublish" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LCWeb3.mdf;Initial Catalog=LCWeb3;Integrated Security=True" providerName="System.Data.SqlClient" />
and the "Format of the initialization string does not conform to specification starting at index 0" error no longer occurs.
I has the same issue, when I use command: "Update-Database" in Package Manager Console.
To Fix, make sure set startup project to the project which you want to do update.
E.g. I got Db project and Web project, make sure set startup project on Db project, when run "Update-Database", otherwise, it will try to search inside Web project.
The permissions on the SQL server were not correctly set up. I have now resolved this by properly setting up the server permissions.

setup and deployment with database

I want to create an exe of my c# windows application project. I created the exe. But my problem is that I don't know how to include database with this exe. Because now am taking backup of my database and restore this backup to the system in which I want to install my exe. Database is created in sql server2012.
In my c# code connection string set to my system server name. so if I want to install it in another system, I need to change this connection string as server name of the system in which I want to install my exe. But it is not possible in all the time. so is there any method to done all these without changing in the code? I Created the exe using install shield.
Thanks.
Normally database settings should be configurable i.e. the user sets the settings through the application UI which are then written into a configuration file. If you give the settings through a configuration file with hardcoding, the exe need not be built everytime.
For getting the existing database, your application should be coded to create a blank database if the database in the server doesn't exist. The existing data can be imported through Administrator mode od your application or manually done in the SQL Server.
The following code shows how you can store connection strings in App.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
Once you have saved your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as following code shows.
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
The above code has been taken from this link
For a detailed example check this article on CodeProject

A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

Getting this error when I run my project in new PC. TO avoid this I have to copy paste the new Connection string every time .. Is there any way to avoid that ... I have 3 different database and its very annoying O_O
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\Yoro\\Desktop\\WAPent 3.0 (1)\\WAPent 3.0\\WAPent 3.0\\WAPent 2.0\\WAPent 2.0\\App_Data\\LoginStuff.mdf;Integrated Security=True;User Instance=True");
Web Config code
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\LoginStuff.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
In the web.config you are using |DataDirectory| which is a substitution for the path to the datadirectory. This is set by using
AppDomain.CurrentDomain.SetData("DataDirectory", newpath)
When you do not set |DataDirectory| it defaults to the App_Data folder when it is a web project.
So looking at your code the path represented by DataDirectory probably does not contain the database file.
For more info about datadirectory have a look at this (older) article.
Open server explorer, right-click on your database, select properties on bottom right corner. A property window will appear; copy the connection string there and use it in your application. For example, in my application:
SqlConnection sconnection = new SqlConnection(#"Data Source=(LocalDB)\v11.0;
AttachDbFilename=C:\Users\Taha\Documents\Visual Studio 2013\Projects\Finder\Finder\App_Data\Userdb.mdf;
Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
sconnection.Open();
This issue generally occurs in VS 2012 which I too have faced it.
In order to resolve it,you need to foolow these steps:
1)Right Click on the .mdf file ->Select Modify connections under server Explorer.
2)Popup window will come->Click Advanced Button ->Select (LocalDB)\v11.0 as DataSource value
Also make sure you make changes in webconfig file as well for DataSource=(LocalDB)\v11.0
You are done.Wella!!
First, your Database must be in other location than bin folder from your project;
Then, your connection must be declared like this:
SqlConnection con = new SqlConnection(TABLE1TableAdapter.Connection.ConnectionString);
If you have a DataGridView you can click on Choose Data Scource, and add your table as source from your database.(In my example, the table is named TABLE1.) Then, visual studio automatly create a DataSet, DataBinding, and a TableAdapter. The TableAdapter (TABLE1TableAdapter) contains as property the ConnectionString you need for database.
P.S. I had this problem, and after a lot of work, i find this solution. I hope it helps you too.
You should check your connection string. when you try to attach sql file the connection string should be like that:
DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|PharmacyDB.mdf;Database=PharmacyDB;Integrated Security=True
I get this error when I use two connection string in my same DBContext,for example I try to Connect to sql server in a connection string and connect to sql express file in another connection string:
public MyDBContext(bool autoDetectChangesEnabled)
: base("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDB.mdf;User Instance=false;Integrated Security=True;MultipleActiveResultSets=True")
{
Initialize(autoDetectChangesEnabled);
}
public MyDBContext()
: base("data source=(LOCAL)\\SQLEXPRESS;initial catalog=MyDB;persist security info=True;user id=user;password=pass;MultipleActiveResultSets=True;App=EntityFramework")
{
Initialize(true);
}
Realizing I'm resurrecting an old topic, but my search led me here and the solution that worked for me was not covered in the responses.
I'm using an mdf file as my project's database and by using the Server Explorer in VS I was accurately building my connection string with the following:
string _connectionString = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename={System.IO.Directory.GetCurrentDirectory() + "\\Database.mdf"};Integrated Security=True";
Seemed correct, but I was still receiving this same error. After some trial and error, I found that the issue was not the connection string, but rather the mdf file properties. The setting "Copy to Output Directory" was set to "Do not copy" initially. Setting this to "Copy if newer" fixed the issue for me.
In my case, I just clean the solution and then rebuild it. It works well.
Exit Visual Studio.
Run Visual Studio again.
Do not open your project from last program list, open it using the open project -> browse procedure.
Go to server explorer: if your .mdf file icon has a little red X, then create a new table, no need to enter anything in the table. Just update it.
First you will see a prompt: choose NO.
In the second prompt, choose YES: the little red X should go away.
Delete the table you just created and update.
This solved the problem for me.

Categories