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

Asked

Viewed 1,426 times

5

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

  • Does the system have a "login" screen? If yes, you can do this setting on this screen, that is, add fields for the user to inform the parameters or a menuzinho to do this.

  • I expected someone to give a better hint, but the only way I could imagine would be to run a program after the installation to make the configuration.

  • Does it need to be on App.Config? It can’t be somewhere simpler, like a. ini file?

1 answer

1

In my applications the login screen has a Combobox where it selects between connections registered in the app.config. Next to Combobox I have a button that gives access to a screen where the person can register "Connections", and these connections are read/written directly in the app.config. I use a class that performs this access by adding and recovering the 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, just configure my access to use the desired Connectionstring. This will depend a lot on how the connection is made.

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

Database.Connection.ConnectionString = strConexaoAtiva;

If you are using ADO.NET, probably Voce is using the Mysqlconnection class, so the code must 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 website: http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.