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
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.
– Thiago Silva
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.
– RSinohara
Does it need to be on App.Config? It can’t be somewhere simpler, like a. ini file?
– Leonel Sanches da Silva