Search code examples
c#winformsdeploymentconnection-stringapplication-settings

Changing ConnectionString


When i installed myProg.exe into Client computer, I have to adapt the connectionString.

So i open the file MyProg.exe.config, and modified the connectionString, but it not work.

Then I found this article . The problem now when I modified access into public, I can not compile / deploy it.

my App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="FrontEnd_Offline.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.windows.forms jitDebugging="true" />
  <connectionStrings>
    <add name="Soft8Exp_ClientConnStr" connectionString="Data Source=xxxxx;Initial Catalog=xxxxx;User ID=sa;Password=xxxxx" providerName="System.Data.SqlClient" />
    <add name="Soft8Exp_ClientEntities" connectionString="metadata=res://*/Domain.Entite_T.csdl|res://*/Domain.Entite_T.ssdl|res://*/Domain.Entite_T.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=xxxxx;initial catalog=xxxxx;user id=sa;password=xxxxx;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="FrontEnd_Offline.Properties.Settings.Soft8Exp_ClientConnectionString" connectionString="Data Source=xxxxx;Initial Catalog=xxxxx;User ID=sa;Password=xxxxx" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <applicationSettings>
    <FrontEnd_Offline.Properties.Settings>
      <setting name="NO_ORDRE" serializeAs="String">
        <value />
      </setting>
    </FrontEnd_Offline.Properties.Settings>
  </applicationSettings>
</configuration>

and class to connect:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

using System.Data;
using System.Configuration;

namespace FrontEnd_Offline.Domain
{
    class Connexion : IDisposable 
    {
        public SqlConnection conn;
        public SqlConnection GetConnected()
        {
            try
            {
                String strConnectionString = ConfigurationManager.ConnectionStrings["Soft8Exp_ClientConnStr"].ConnectionString;
                conn = new SqlConnection(strConnectionString);
            }
            catch (Exception excThrown)
            {
                conn = null;
                throw new Exception(excThrown.InnerException.Message, excThrown);
            }

            // Ouverture et restitution de la connexion en cours
            if (conn.State == ConnectionState.Closed) conn.Open();
            return conn;
        }

        public Boolean IsConnected
        {
            get { return (conn != null) && (conn.State != ConnectionState.Closed) && (conn.State != ConnectionState.Broken); }
        }

        public void CloseConnection()
        {
            // Libération de la connexion si elle existe
            if (IsConnected)
            {
                conn.Close();
                conn = null;

            }

        }

        public void Dispose()
        {
            CloseConnection();
        }
    }
}

Solution

  • You didn't say you were using ClickOnce in the beginning. Things are different there: The configuration file is stored in the user's profile. You can not change the file afterwords (only user settings through your application).

    To update a ClickOnce program with a new connection string I suggest the following:

    1. Create a new user setting called "SettingsUpgradeNeeded" and set it to true in the settings designer
    2. Add the following code to your application's startup code (Program.cs or App.cs)

      if (Properties.Settings.Default.SettingsUpgradeNeeded)
      {
          Properties.Settings.Default.Upgrade();
          Properties.Settings.Default.SettingsUpgradeNeeded = false;
          Properties.Settings.Default.Save();
      }
      
    3. Publish a new update.

    Another way to change the connection is (and this is even more preferrable seeing that you only use SqlConnection in your code):

    1. Stop using the ConnectionStrings section
    2. For every connection parameter, create a setting (for example: Database server, Database name, etc.)
    3. Use the SqlConnectionStringBuilder to generate a connection string from these setting

    EDIT
    You want the user to be able to change the connection parameters:

    1. Create a user setting for each parameter you need to connect to the database (for example: server, database, failover partner, user name, authentication method, etc.)
    2. Create a dialog where you can configure these values
    3. Use the SqlConnectionStringBuilder to create a connection string from these values
    4. Use that connection string for all your database connections

    Example:

    SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
    sb.DataSource = Properties.Settings.Default.DBServerName;
    sb.InitialCatalog = Properties.Settings.Default.DBDatabaseName;
    sb.IntegratedSecurity = Properties.Settings.Default.DBUseIntegratedSecurity;
    if (!sb.IntegratedSecurity)
    {
        sb.UserId = Properties.Settings.Default.DBUserName;
        sb.Password = Properties.Settings.Default.DBPassword;
    }
    
    
    using (SqlConnection conn = new SqlConnect(sb.ConnectionString))
    {
        ...
    }
    

    I'd generate a static property either in Program.cs or the App class that can return the connection string from the SqlConnectionStringBuilder.