I'm trying to create a working installer or setup file for an application I created using C# in VS 2010.
I used InstallShield and also the built-in one and they do created the setup files and I installed the app with no problem.
But when I ran the program, this thing pops up:
My database connections:
On the forms:
SqlConnection cn = new SqlConnection(#"SERVER=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;DATABASE=Database;Integrated Security=True;User Instance=True");
App.Config:
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
What could be wrong? Should my connection string on the form the same as the one in the app.config file?
Visual Studio 2010 Ultimate
SQL Server 2008 Express
It looks like you ran the installer on your development box.
If you use AttachDbFilename in the connection string and you omit the option Database from the connection string the sqlclient will try to create a database with the filename as the name of the database. This fails if the database already exists.
You need to make sure that your SqlConnection uses the connection string from the app.config:
SqlConnection cn = new SqlConnection(
ConfigurationManager.
ConnectionStrings["MyDatabaseNameInConfig"].
ConnectionString);
In your app.config you'll need:
<connectionStrings>
<add name="MyDatabaseNameInConfig"
connectionString="Database=PRODUCTION;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf; ...."/>
</connectionStrings>
A way to fix this is to add a Database parameter to your connectionstrings for release builds:
connectionString="Database=PRODUCTION;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf; ...."
You can automate that in Visual Studio with XML Document Transform
Another option is to change your setup to make these changes on install but I'm not sure how easy that is.
A final solution might be to have your application accept a special startup argument to update the connectionstrings. The installer can start your application with that special argument at the end of the setup.
Related
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
I am using Visual Studio 2015, Entity Framework v6, and SQL Server 2016 Express. In the past I created a database using a SqlConnection and SqlCommand and stuff the SQL into a string.
Now, I am teaching myself EF6 on Entity Framework Tutorial. On the simple code-first example (very simple), I literally copy and paste my code but still do not see the database created in SSMS. Neither does my code throw me any error.
Instead of pasting the code, I did a screenshot. I hope someone can point out what I am or the tutorial is missing.
[EDIT]
Following Sampath's suggestion, I end up getting the following error:
[EDIT - Solved, sort of]
I apply the same code to another machine of same setup and the code works. So I suspect there are some corruption in the SQL Server or perhaps some registry is incorrect. I uninstall EVERY SQL Server version and related tools, delete all folders and files manually, then freshly reinstall SQL Server Express 2016 and tools. Then my code works.
I don't see this as a solution, but if someone can suggest what may have cause this problem I will try to recreate it or post a real solution to it.
You have to give the connection string name on the web.config file as shown below.
Context :
public SchoolContext(): base("MySchoolDB")
{
}
App.config file
<add name="MySchoolDB" connectionString="Server=localhost;
Database=YourDBName;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
You can get more details here : Database Initialization
You have to add entity to your database after configuring connection string, then DBContext will create database. Here is a connection string example:
<add name="Name" connectionString="Data Source=.; Initial Catalog=yourdbName; Integrated Security=True; MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />
I'm going through the ASP.NET "Contoso University" Tutorial found here.
The problem starts when i try to view the database. Following directly from the tutorial, when i go to open the database (SchoolContext), i get this error mesage.
Cannot open database "ContosoUniversity1" requested by the login. The login failed.Login failed for user 'machine\user'.
So on the DB i went to "Modify Connection" and hit OK without changing anything. Then I was able to view the database, tables, views, etc. But there was no info available, so continuing from the tutorial I should have seen the Student entity, but it was not there. And when i run the program and try go to website/students, i get a 404 saying the resource cannot be found.
The connection string i'm using from the tutorial
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
I'm running VS 2013 Community Express. I do not have SQL Server Management Studio installed or any related programs.
I'm on the admin user for the computer.
Is this a problem with my machine or user rights? Do i need to install another program?
I think you are using the sqlserver express edition which comes with Visual Studio installation. Try adding AttachDBFilename='path of .mdf file of database' also in your connection string.
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\ContosoUniversity1.mdf" providerName="System.Data.SqlClient"/>
</connectionStrings>
Go to that connection in Server Explorer. Go to Properties and use the connection string from there.
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
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.