Ikawa Afue
Ikawa Afue

Reputation: 39

VS 2010 C# Create Setup File with SQL Server database

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:

enter image description here

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?

Upvotes: 0

Views: 772

Answers (1)

rene
rene

Reputation: 42414

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.

Upvotes: 1

Related Questions