3

I have developed an application in Visual Studio 2012 with a SQL Server 2012 database. When I try to publish the application to test it, it works correctly on my machine (that includes the database in a SQL Server data folder), but when I move that published app to another machine it doesn't work.

I want to know the simplest way to deploy the project together with its database. I have seen a solution to integrate the SQL database with my application is to use a localdb but I don't understand the steps to use it. I need all the steps to deploy an application with a SQL Server 2012 database in order to install the application on another PC without having to install SQL Server 2012 on that PC.

TobyLL
  • 2,098
  • 2
  • 17
  • 23
Mohammed
  • 41
  • 1
  • 7
  • 3
    You can use/deploy SQL Server Compact Edition. See: https://msdn.microsoft.com/en-us/library/aa983326%28v=vs.140%29.aspx – SteveFerg Jun 09 '15 at 18:54
  • 1
    the extension of SQL Server Compact Edition is .sdf so how to export the sql server 2012 into .sdf ? – Mohammed Jun 09 '15 at 19:32
  • 1
    SQL Server Compact Edition is not going to be updated and has limited to no built-in support in newer versions of Visual Studio. LocalDb is the new push for that type of deployment. You will need to install the runtime on the target machine and deploy the files you need. – crashmstr Jun 09 '15 at 19:53

3 Answers3

3

Your app doesn't work on the other machine because you deployed it with the same configuration on your local machine without a database.

  • If you don't have SQL server on the machine you can use SQL Server Express (it's installed by default with Visual Studio unless you explicitly tell it not to do) and update web.config:

    <connectionStrings>
        <add name="testCon" 
             connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
    
  • Deploy database to server and change the connection string

    <connectionStrings>
        <add name="testCon" 
             providerName="System.Data.SqlClient" 
             connectionString="Data Source=Server_Name;Initial Catalog=DB_Name; User Id=User_Name;Password=Password;" /> 
    </connectionStrings>
    
Ahmed Al Jabry
  • 1,367
  • 13
  • 9
  • 1
    I am new to visual studio and sql server Please I need step by step (I did not understand what you said. ) . – Mohammed Jun 09 '15 at 19:59
  • 1
    the type of my app is windows (winform) is connected with a database in sql server 2012 now i need to create a .exe of my application (contain the database) in order to install the application with database in other pc without install sql server in the other pc . thanks – Mohammed Jun 09 '15 at 20:11
  • 1
    after you deployed your app on the new machine you need to take your database also or deploy database to server (take copy from current database ) and change the connection to let your app connect with the server your current databases not accessible from outside your local machine so when the app on the new machine try to connect it failed – Ahmed Al Jabry Jun 09 '15 at 20:21
  • 1
    now i need to deploy my application with the database in order to install directly the application (contain the database) in the other pc . – Mohammed Jun 09 '15 at 20:26
  • 1
    you can use SQLEXPRESS it installed by default with visual studio all you need to do is to take "Database.mdf" you will find it on "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA" from your local machine and connect to it as i declared in my answer – Ahmed Al Jabry Jun 09 '15 at 20:29
  • 1
    look you need to separate between app and database it's totally different and managed by different IDEs, deploying the app doesn't mean deploye DB with it – Ahmed Al Jabry Jun 09 '15 at 20:38
  • 1
    my database name is DevEssai , i change the connection into visual studio 2012 (sqlConnection cn=new SqlConnection ("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\DevEssai.mdf;Initial Catalog=DevEssai;Integrated Security=True"); but when i run my project i have an error (Impossible d'ouvrir la base de données "DevEssai" demandée par la connexion. La connexion a échoué. Échec de l'ouverture de session de l'utilisateur 'A-PC\A'.) – Mohammed Jun 09 '15 at 20:43
  • 1
    With SQL Server express you still have to install a light weight sql server express server service on the destination computer(s). With SQL Server compact edition, you do not. You have to include about 8 dlls with your installer. The downside is that the all the C# calls that start with Sql... would have to be changed to SqlCe... but the call are pretty much the same for all the basic sql calls. – SteveFerg Jun 10 '15 at 02:54
1

It seems not too long ago I faced the same problem. I looked at SQL Server, MySQL, SQL Server Express and SQL Server Compact edition. I wanted a simple database for a standalone application. SQL Server Compact fit the bill for a standalone, self-contained database. SQLite is another excellent choice for a standalone database, but that is another answer. SQL Server Express pros/cons is covered in another answer already.

To deploy SQL Server Compact (CE) you would could either include the installer of SQLCE40Runtime_x86-ENU.exe or you include the needed directories and Dlls manually that the installer creates for you. For more deployment information see: https://msdn.microsoft.com/en-us/library/aa983326%28v=vs.140%29.aspx

The connection string I would use is

ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\DevEssai.sdf;Persist Security Info=False";

For additional ideas for a connection string see: http://www.connectionstrings.com/

Any choice you ultimate make, there are pros and cons to each choice that you will have to make. Either way it will require you to do some research to choose the best choice for your application. Don't be intimidated. Once you research it further, it is not as hard as you might think initially. It is simply a learning curve that everyone has to go through.

SteveFerg
  • 3,466
  • 7
  • 19
  • 31
  • if i chose SQL Compact Edition i need to export the database from sql server 2012 with extension (.sdf) , i have the solution of code project (http://www.codeproject.com/Articles/25685/SQL-Server-to-SQL-Server-Compact-Edition-Database) to convert .mdf to .sdf but I do not understand how to use . – Mohammed Jun 10 '15 at 12:34
  • Aaahhhh, maybe not on that project. It requires older versions of SQL compact and would require a lot of work for questionable results. My suggestion would be roll your own. Create a conversion routine to read the existing SQL database records and immediately write them to SQL compact records. It would be a good exercise to get comfortable with using SQL CE and should be a relatively simple read-then-write routine. – SteveFerg Jun 11 '15 at 17:13
  • See my example in the next answer I have created. – SteveFerg Jun 11 '15 at 18:31
  • but i need to change the name of table and the query and the name of database in the solution – Mohammed Jun 11 '15 at 20:30
  • Yes, this is just an example for you to use or learn from. Your existing table names and database names can stay the same. The SQL CE database has a .sdf extension where the SQL database has a .mdf extension. Other than that there is very little coding difference. – SteveFerg Jun 11 '15 at 20:35
  • the SQL CE not working to me , if I use SqlLite , is that this type of database is used by Visual Studio 2012 ? if yes, how can be deployed, add this type of database with my application ? thanks – Mohammed Jun 14 '15 at 11:30
  • I added another button to the example to convert to SQLite. in VS 2012, go to Tools->Nuget Package Manager->Manage NuGetPackages for Solution. expand Online and click on nuget.org. In the search box enter sqlite. Install the System.Data.SQLite (x86/x64).Similar to SQLCE, you will need to add a reference to System.Data.SQLite just like you did for System.Data.SqlServerCe if you wanted to to use SQL CE. There is a faq file you might find helpful on sqlite: https://system.data.sqlite.org/index.html/doc/trunk/www/faq.wiki – SteveFerg Jun 14 '15 at 19:12
  • i'am creating sqlite db connected with application (visual studio 2012) the application works with the database , now i need how to deploye the application with the database (create the .exe file ),in order to install the application in other machine. thank you. – Mohammed Jun 14 '15 at 20:12
  • Here are a couple of links for deploying that you might find helpful: https://stackoverflow.com/questions/2689628/deploying-winform-application-with-embedded-sqlite and https://www.youtube.com/watch?v=Wwne0zILe6g – SteveFerg Jun 14 '15 at 20:28
  • - my database is mydata - connection string is : data source=C:\\Users\\A\\Documents\\dd when i deploy my application , is what I need to change the path of the database – Mohammed Jun 14 '15 at 20:43
  • Your connection string is **wrong** - if you want to use SQL Server **CE**, that's a `.sdf` file - not a `.mdf` (that's a full, server-based SQL Server version) – marc_s Sep 21 '15 at 08:09
1

I have created a simple conversion program to convert one of my SQL Server tables into a SQL Server Compact Edition table. I just created a Windows form with a single button that says "Convert". It will create the SQL Server CE database and then read each record from the SQL Server database table and write it to the equivalent table record in the SQL Server Compact database.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.Data.SQLite;

namespace SampleConversion
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            string cmd = "";
            int count = 0;

            create_SQLCE_database(); // Create the SQL Server CE database file and a table within it

            string SQLconnectionString = "server=(local); database=PTHData; Trusted_Connection=True;"; // open PTHData.mdf
            string SQLCEconnectionString = "Data Source=" + Application.StartupPath + "\\pthData.sdf;Persist Security Info=False"; // open PTHDATA.sdf

            // open the input and output database
            SqlCeConnection SQLCEconnection = new SqlCeConnection(SQLCEconnectionString);

            try
            {
                SQLCEconnection.Open();
            }
            catch (SqlCeException ex)
            {
                string errorMessages = "A SQL Server CE exception occurred on open.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
                return;
            }
            SqlConnection SQLconnection = new SqlConnection(SQLconnectionString);
            try
            {
                SQLconnection.Open();
            }
            catch (SqlException ex)
            {
                string errorMessages = "A SQL exception occurred on open.\n" + ex.Message;
                MessageBox.Show( errorMessages, "Convert");
                return;
            }

            //Databases are not open, time to convert
            SqlCommand cmdread = new SqlCommand();
            cmdread.Connection = SQLconnection;
            cmdread.CommandText = "Select * from USTimeZones";
            SqlDataReader drread = null;

            SqlCeCommand cmdwrite = new SqlCeCommand();
            cmdwrite.Connection = SQLCEconnection;

            try
            {
                drread = cmdread.ExecuteReader();
                while (drread.Read())
                {
                    drread["timezone"].ToString();
                    cmd = "Insert into USTimeZones values ('" + drread["state"].ToString() + "','" +
                        drread["city"].ToString() + "','" + drread["county"].ToString() + "','" +
                        drread["timezone"].ToString() + "','" + drread["timetype"].ToString() + "','" +
                        drread["latitude"].ToString() + "','" + drread["longitude"].ToString() + "')";
                    cmdwrite.CommandText = cmd;
                    try
                    {
                        cmdwrite.ExecuteNonQuery();
                        count++;
                    }
                    catch (SqlCeException ex)
                    {
                        string errorMessages = "A SQL exception occurred on writing the SQL Server CE record.\n" + ex.Message;
                        MessageBox.Show(errorMessages, "Convert");
                        SQLCEconnection.Close();
                        SQLconnection.Close();
                        return;
                    }

                }
            }
            catch (SqlException ex)
            {
                string errorMessages = "A SQL exception occurred reading records.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
            }
            catch (Exception ex)
            {
                string errorMessages = "A General exception occurred reading records.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
            }

            MessageBox.Show("Records written: " + count.ToString(), "Conversion complete");
            drread.Close();
            SQLconnection.Close();
            SQLCEconnection.Close();
        }

        private void create_SQLCE_database()
        {
            string connectionString = "Data Source=" + Application.StartupPath + "\\pthData.sdf;Persist Security Info=False";

            try
            {
                SqlCeEngine en = new SqlCeEngine(connectionString);
                en.CreateDatabase();
            }
            catch (SqlCeException ex)
            {
                MessageBox.Show("Unable to create the SQL Server CE pthData database\n" + ex.Message, "Create SQL Server CE file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to create the SQL Server CE pthData database\n" + ex.Message, "Create SQL Server CE file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }

            // file created, now create tables
            SqlCeConnection cn = new SqlCeConnection(connectionString);
            if (cn.State == ConnectionState.Closed)
                cn.Open();

            SqlCeCommand cmd;
            string commandString = "Create table USTimeZones\n";

            // create USTimeZones file
            commandString = "Create table USTimeZones\r\n";
            commandString += "(state nvarchar(30), city nvarchar(100), county nvarchar(50), timezone nvarchar(10), ";
            commandString += "timetype int, latitude nvarchar(10), longitude nvarchar(10),  ";
            commandString += "PRIMARY KEY(state, city, county, timezone, timetype))";
            cmd = new SqlCeCommand(commandString, cn);

            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlCeException sqlexception)
            {
                MessageBox.Show(sqlexception.Message + "\n Command string: " + commandString, "Error creating USTimeZoness", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error creating USTimeZones", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }

            cn.Close();
        }

    private void btnSQLiteConvert_Click(object sender, EventArgs e)
    {
        string cmd = "";
        int count = 0;

        create_SQLite_database(); // Create the SQLite database file and a table within it

        string SQLconnectionString = "server=(local); database=PTHData; Trusted_Connection=True;"; // open PTHData.mdf
        string SQLiteconnectionString = "Data Source=" + Application.StartupPath + "\\pthData.sqlite;Version=3;";

        // open the input and output database
        SQLiteConnection SQLiteconnection = new SQLiteConnection(SQLiteconnectionString);

        try
        {
            SQLiteconnection.Open();
        }
        catch (SQLiteException ex)
        {
            string errorMessages = "A SQLite exception occurred on open.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
            return;
        }

        SqlConnection SQLconnection = new SqlConnection(SQLconnectionString);

        try
        {
            SQLconnection.Open();
        }
        catch (SqlException ex)
        {
            string errorMessages = "A SQL exception occurred on open.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
            return;
        }

        //Databases are not open, time to convert
        SqlCommand cmdread = new SqlCommand();
        cmdread.Connection = SQLconnection;
        cmdread.CommandText = "Select * from USTimeZones";

        SqlDataReader drread = null;

        SQLiteCommand cmdwrite = new SQLiteCommand();
        cmdwrite.Connection = SQLiteconnection;

        try
        {
            drread = cmdread.ExecuteReader();

            while (drread.Read())
            {
                drread["timezone"].ToString();
                cmd = "Insert into USTimeZones values ('" + drread["state"].ToString() + "','" +
                    drread["city"].ToString() + "','" + drread["county"].ToString() + "','" +
                    drread["timezone"].ToString() + "','" + drread["timetype"].ToString() + "','" +
                    drread["latitude"].ToString() + "','" + drread["longitude"].ToString() + "')";
                cmdwrite.CommandText = cmd;

                try
                {
                    cmdwrite.ExecuteNonQuery();
                    count++;
                }
                catch (SQLiteException ex)
                {
                    string errorMessages = "An SQL exception occurred on writing the SQLite record.\n" + ex.Message;
                    MessageBox.Show(errorMessages, "Convert");
                    SQLiteconnection.Close();
                    SQLconnection.Close();
                    return;
                }

            }
        }
        catch (SqlException ex)
        {
            string errorMessages = "A SQL exception occurred reading records.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
        }
        catch (Exception ex)
        {
            string errorMessages = "A General exception occurred reading records.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
        }

        MessageBox.Show("Records written: " + count.ToString(), "Conversion complete");
        drread.Close();
        SQLconnection.Close();
        SQLiteconnection.Close();
    }

    private void create_SQLite_database()
    {
        string connectionString = "Data Source=" + Application.StartupPath + "\\pthData.sqlite;Version=3;";

        try
        {
            SQLiteConnection.CreateFile("pthData.sqlite");
        }
        catch (SQLiteException ex)
        {
            MessageBox.Show("Unable to create the SQLite database\n" + ex.Message + "\nConnection string: " + connectionString, "Create SQLite file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to create the SQLitedatabase\n" + ex.Message + "\nConnection string: " + connectionString, "Create SQLite file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        // file created, now create tables
        SQLiteConnection cn = new SQLiteConnection(connectionString);
        if (cn.State == ConnectionState.Closed)
            cn.Open();

        SQLiteCommand cmd;
        string commandString = "Create table if not exists USTimeZones\n";

        // create time zones file
        commandString += "(state nvarchar(30), city nvarchar(100), county nvarchar(50), timezone nvarchar(10), ";
        commandString += "timetype int, latitude nvarchar(10), longitude nvarchar(10),  ";
        commandString += "PRIMARY KEY(state, city, county, timezone, timetype))";

        cmd = new SQLiteCommand(commandString, cn);

        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (SQLiteException sqlexception)
        {
            MessageBox.Show(sqlexception.Message + "\n Command string: " + commandString, "Error creating USTimeZones", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\n Command string: " + commandString, "Error creating USTimeZoness", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SteveFerg
  • 3,466
  • 7
  • 19
  • 31