Dynamic Connection EF C# Windows Forms Mysql

Question:

I have the following problem:

EF creates a connectionString in the application's app.config and uses this connection always, but if I need to change the bank's server I'll have to change the app.config.

I've already tried a way to make the server ip exchange work, but when I run the same it takes the & from the symbol &quote and looks like this: &quote; then when I start the application it automatically gives an error because it doesn't recognize the proper information. Here's the app.config code and code I made via C# to change this property.

app.config

<connectionStrings>   
  <add name="ref_bdEntities" connectionString="metadata=res://*/ModeloDados.csdl|res://*/ModeloDados.ssdl|res://*/ModeloDados.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=127.0.0.1;user id=sa;password=master;persistsecurityinfo=True;database=ref_bd&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

change code

string _ipservidor = string.Empty;
            _ipservidor = LerIni.LerINI(@"C:\Motion Software\bin\config.ini", "[IPServidor]");
            connectionString = "metadata=res://*/ModeloDados.csdl|res://*/ModeloDados.ssdl|res://*/ModeloDados.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server="+_ipservidor+";user id=sa;password=master;persistsecurityinfo=True;database=ref_bd&quot;";
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings["ref_bdEntities"].ConnectionString = connectionString;
            config.Save(ConfigurationSaveMode.Modified); // Salva o que foi modificado
            ConfigurationManager.RefreshSection("connectionStrings"); // Atualiza no app o bloco connectionStrings
            Properties.Settings.Default.Reload(); // Recarrega os dados de conexão

Help me pfv. I'm using Mysql as a database and I'll probably use a hosting for the database (ignore the fact that it's Windows forms).

Update – I am using Database First

Update 2 – The code above does not change the value of the physical config file, when I place the files necessary for the application to work and take the menu.exe.config settings file (In this case the exe name is Menu) it does not change this file and I want to be able to change this file, is it possible?

Update 3 – On the website http://www.codeproject.com/Tips/411013/Configuring-a-Connection-String-in-the-App-Config I found an example that uses the xml change in the .config file, so I could also see it uses a StringBuilder, the only part of the code I didn't understand was: xElement.FirstChild.Attributes[2].Value = con; , can someone help me understand? I'm almost reaching a solution just need some help.

Answer:

After much searching and analyzing I managed to solve the problem. As described in update 3 I found a method to change the app.config xml file and put the code with the solution to the problem below:

public void Servidor()
        {
            string _ipservidor = string.Empty;
            _ipservidor = LerIni.LerINI(@"C:\Motion Software\bin\config.ini", "[IPServidor]");
            connectionString = "metadata=res://*/ModeloDados.csdl|res://*/ModeloDados.ssdl|res://*/ModeloDados.msl;provider=MySql.Data.MySqlClient;provider connection string='server="+_ipservidor+";user id=sa;password=master;persistsecurityinfo=True;database=ref_bd'";
            updateConfigFile(connectionString);

            /* Altera app.config */
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings["ref_bdEntities"].ConnectionString = connectionString;
            config.Save(ConfigurationSaveMode.Modified); // Salva o que foi modificado
            ConfigurationManager.RefreshSection("connectionStrings"); // Atualiza no app o bloco connectionStrings
            Properties.Settings.Default.Reload(); // Recarrega os dados de conexão   

            /* Altera connection Entity Framework */
            EntityConnectionStringBuilder conEntity = new EntityConnectionStringBuilder();
            conEntity.Provider = "MySql.Data.MySqlClient";
            conEntity.ProviderConnectionString = "'server=" + _ipservidor + ";user id=sa;password=master;persistsecurityinfo=True;database=ref_bd'";
            conEntity.Metadata = "res://*/Modelo.csdl|res://*/Modelo.ssdl|res://*/Modelo.msl";
            ref_bdEntities BDEntidades = new ref_bdEntities(conEntity.ToString());
        }

        public void updateConfigFile(string con)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in xmlDoc.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    xElement.FirstChild.Attributes[1].Value = con;
                }

            }
            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

As you can see I also updated through configuration and EntityConnection. This was just to make sure it would work, if anyone thinks there will be a drop in performance please let me know.

But what really ended my problem was changing the connectionString value in the app.config xml, I tested it in a separate folder with Menu.exe.config and it worked.

The only problem I registered is that as I was testing with the ip of the local machine 127.0.0.1, when changing only the last number to anything else it continued to connect but I think this is because of port 3306, but when I put a different ip type 192.168.12.145 it doesn't find the same port then the connection error.

Any suggestions you have and want to share with me, I appreciate it!

Thanks for listening.

Scroll to Top