C # App.config - Change DB address at installation time

5

I have a C # desktop application that when installed on a pc, should access a Mysql DB that is on another machine. The DB server address is configured in the App.config file. At the client's request, at the time of installation I need to allow the user to configure the DB access parameters. How can I generate a dialog at the time of installation, so that the user can enter the server address, the user and the password that should be used to access the database? With these values, I need to change the App.config file so that the application after being installed correctly accesses the DB. I created an installation project (InstallShield), but I did not find where I can create this functionality

    
asked by anonymous 31.07.2015 / 20:13

1 answer

1

In my applications on login screen has a Combobox where it selects between connections registered in the app.config of the application. Next to the ComboBox I have a button that gives access to a screen where the person can register "Connections", being these connections are read / written directly in the app.config of the application. I use a class that accomplishes this access by adding and retrieving ConnectionStrings. Below this class:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;

/// <summary>
///   Classe de manipulaçao do arquivo app.config
/// </summary>
public class AppConfigConStrings
{
    #region Instancias

    private const string strCaminhoExecutavel = "[caminho do executável]";

    private readonly Configuration pcfgConfiguration =
        ConfigurationManager.OpenExeConfiguration(strCaminhoExecutavel);

    #endregion

    #region Metodos

    /// <summary>
    ///   Alimentar componente ICM_Combobox com as conexões existentes no App.config
    /// </summary>
    /// <param name="cboComboBox"> Componente a ser alimentado </param>
    /// <returns> </returns>
    public bool AlimentarComboConexoes(ComboBox cboComboBox)
    {
        try
        {
            ConnectionStringSettingsCollection lcscConexoesDisponiveis =
                ConfigurationManager.OpenExeConfiguration(strCaminhoExecutavel).
                    ConnectionStrings.ConnectionStrings;
            if (lcscConexoesDisponiveis.Count > 0)
            {
                cboComboBox.Items.Clear();
                foreach (ConnectionStringSettings lcssconexao in lcscConexoesDisponiveis)
                {
                    cboComboBox.Items.Add(lcssconexao.Name);
                }

                if (cboComboBox.Items.Count > 0)
                    cboComboBox.SelectedIndex = 0;
                return true;
            }
            return false;
        }
        catch (Exception lex)
        {
            MessageBox.Show(lex.Message);
            return false;
        }
    }

    /// <summary>
    ///   Quebrar string de conexão para recuperar valores.
    /// </summary>
    /// <param name="strNomeConexao"> Nome da string de conexão </param>
    public bool RecuperarValoresStringConexao(string strNomeConexao)
    {
        try
        {
            if (ConfigurationManager.OpenExeConfiguration(strCaminhoExecutavel).
                    ConnectionStrings.ConnectionStrings[strNomeConexao] != null)
            {
                string lstrConexao =
                    ConfigurationManager.OpenExeConfiguration(strCaminhoExecutavel).
                        ConnectionStrings.ConnectionStrings[strNomeConexao].ConnectionString;

                List<String> lstDadosConexao = new List<string>(lstrConexao.Split(new[] { '=', ';' }));
                for (int lintIndice = 0; lintIndice < lstDadosConexao.Count; lintIndice += 2)
                {
                    lstDadosConexao[lintIndice] = "";
                }

                lstDadosConexao.RemoveAll(predicate => predicate == "");

                // Tratamento a se realizar com os dados da conexão.
            }
            return true;
        }
        catch (Exception lex)
        {
            MessageBox.Show(lex.Message);
            return false;
        }
    }

    /// <summary>
    ///   Salvar Conexão
    /// </summary>
    /// <param name="strDatasource"> Fonte de dados </param>
    /// <param name="strBancoDados"> Banco de dados </param>
    /// <param name="strUserId"> Usuario </param>
    /// <param name="strSenha"> Senha </param>
    /// <param name="strNomeConexao"> Nome Conexão </param>
    /// <returns> </returns>
    public bool SalvarConnectionStringSQLServer(string strDatasource, string strBancoDados, string strUserId,
                                       string strSenha, string strNomeConexao)
    {
        try
        {
            SqlConnectionStringBuilder lsqlsbconnectionBuilder = new SqlConnectionStringBuilder
            {
                DataSource = strDatasource,
                InitialCatalog = strBancoDados,
                UserID = strUserId,
                Password = strSenha,
                IntegratedSecurity =
                    string.IsNullOrEmpty(strUserId.Trim())
            };

            if (RecuperaValorConexao(strNomeConexao) != null)
                return false;

            // Criar Conexão
            pcfgConfiguration.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings
                {
                    Name = strNomeConexao,
                    ConnectionString = lsqlsbconnectionBuilder.ConnectionString,
                    ProviderName = "System.Data.SqlClient"
                });

            // Salvar Conexão
            pcfgConfiguration.Save(ConfigurationSaveMode.Modified);
            return true;
        }
        catch (Exception lex)
        {
            throw new Exception(lex.Message);
        }
    }

    /// <summary>
    /// Exclua a conexão com o nome informado do arquivo de configuração.
    /// </summary>
    /// <param name="strNomeConexao">Nome da Conexão</param>
    /// <returns></returns>
    public bool RemoverConexao(string strNomeConexao)
    {
        if (pcfgConfiguration.ConnectionStrings.ConnectionStrings[strNomeConexao] != null)
        {
            pcfgConfiguration.ConnectionStrings.ConnectionStrings.Remove(strNomeConexao);
            pcfgConfiguration.Save();
            return true;
        }
        return false;
    }

    /// <summary>
    /// Retorna o Numero de Conexões do App.config
    /// </summary>
    /// <returns></returns>
    public int RetornaNumeroConexoes()
    {
        return pcfgConfiguration.ConnectionStrings.ConnectionStrings.Count;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="strNomeConexao"></param>
    /// <returns></returns>
    public string RecuperaValorConexao(string strNomeConexao)
    {
        try
        {
            return pcfgConfiguration.ConnectionStrings.ConnectionStrings[strNomeConexao].ToString();
        }
        catch (Exception)
        {
            return null;
        }

    }

    #endregion
}

With the connection selected, simply configure my access to use the ConnectionString you want. This will depend a lot on how the connection is made.

In my case I use EntityFramework, so I include the code:

Database.Connection.ConnectionString = strConexaoAtiva;

If you are using ADO.NET, you are probably using the MySQLConnection class, so the code should be something like:

try
{
    conn = new MySql.Data.MySqlClient.MySqlConnection();

    //Setando a ConnectionString
    conn.ConnectionString = strConexaoAtiva;

    conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
    MessageBox.Show(ex.Message);
}

See documentation on the site: link

    
04.09.2015 / 17:16