Publish application Windows Form C #

0

I have an application developed with Windows Form C # + Entity Framework v6.1.3, where I use an existing database. The application works correctly, in Visual Studio 2013, where I'm developing.

My App.config has ConnectionStrings as follows:

 <connectionStrings>
    <add name="RHContext" providerName="System.Data.SqlClient"
           connectionString="Server=SERVER;Database=BASE; 
     Trusted_Connection=false;Persist Security Info=True;User Id=USUARIO;
     Password=SENHA;MultipleActiveResultSets=True"
  </connectionStrings>

And like I said, it works normally.

The problem is that I need to take to the production environment, that is, publish. Using the Publish option of Visual Studio itself, it generates the executable along with other files, which are these:

AndwithintheApplicationFilesfolderIhavetheseothers:

Note that I have a .condif file, however if I change the connectionStrings directly in this file, I get this error when running .exe

  

The application can not be downloaded. Not all files required by the application are available.

When I return to connectionStrings to original, it works normally.

This application will "run" on different machines, so I need a way for the technician to change the connectionStrings , not needing the programmer.

And here's my question: How do I change the connectionStrings of the application after publishing it?

I thought about creating a file txt and reading the connectionStrings of it, but I do not know if it is feasible, or if there is a better way to do it.

    
asked by anonymous 08.04.2015 / 19:10

2 answers

1

The ideal thing is that you already publish the version with the Production Connection, or, give an alternative for the user to change.

But if you want to change the Connction String after the publication, this must be done after installing the program ... From what I saw you are using ClickOnce to publish .. Then you should look for the following folder after the installation. .. c: \ user \ $ UserName $ \ AppData \ Local \ Apps \ 2.0 \ $ Estername $ \ $ OtherExternalName $ \ and fetch the application folder. Finding the folder will see the .config file with your connection ..

I hope I have helped;

Abs. Augusto Cordeiro

    
08.04.2015 / 22:01
0

There are several ways to do it. The simplest way is to map the connectionString tags to a class and index them from Windows Forms to create the connection string.

You can make a mask using String.Format and encapsulate the assembly of the new string. (It's up to you how you go about setting it up)

Note: Make sure the context is pointing to string with the name of the connection in .config in this case RHContext, because it is through it that the context works.

ConfigurationManager.ConnectionStrings["RHContext"].ConnectionString

Enter this string in your DbContext and it will respond even if it is changed.

To edit the app.config you can use the Configuration class, here is a very trivial example:

public class AppConfigManager {

    //Objeto para manipular o App.config
    private static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    #region Singleton

    private static AppConfigManager instance;

    public static AppConfigManager Configuration
    {
        get
        {
            if (instance == null)
                instance = new AppConfigManager();
            return instance;
        }
    }

    private AppConfigManager()
    {
        this.ConnectionString = GetConnectionString("RHContext");
    }
    #endregion

    /// <summary>
    /// Retorna a string do App.config.
    /// </summary>
    public string ConnectionString { get; private set; }


    /// <summary>
    /// O path do arquivo de configuração de conexão
    /// </summary>
    public string ConnectionConfigPath
    {
        get
        {
            return Application.ExecutablePath + ".config";
        }
    }


    /// <summary>
    /// A string de conexão
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string GetConnectionString(string key)
    {
        try
        {
            return ConfigurationManager.ConnectionStrings[key].ConnectionString;
        }
        catch (Exception)
        {

            throw new Exception("Não foi possivel obter a conexão do nome" + key);
        }

    }      

    /// <summary>
    /// Altera a string de conexão do nome informado.
    /// </summary>
    /// <param name="connectionString">String a ser utilizada</param>
    public void ChangeConnectionString(string connectionString, string name)
    {
        //setando a string a ser alterada
        var cfg = config.ConnectionStrings.ConnectionStrings[name];

        //altera a string de conexão
        cfg.ConnectionString = connectionString;

        // Salva o que foi modificado
        config.Save(ConfigurationSaveMode.Modified);

        // Atualiza no app o bloco connectionStrings
        ConfigurationManager.RefreshSection("connectionStrings");

        // Recarrega os dados de conexão
        Properties.Settings.Default.Reload();
    }

     /// <summary>
    /// Add uma string de conexão.
    /// MeuAppConfig é a classe onde será mapeados os atributos da connectionString
    /// </summary>
    public static void AddConnectionString(MeuAppConfig app)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(app.User))
                app.User = "";
            if (string.IsNullOrWhiteSpace(app.Password))
                app.Password = "";

            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder
            {
                DataSource = app.ServerName,
                InitialCatalog = app.Database,
                UserID = app.User,
                Password = app.Password,
                IntegratedSecurity = "False"
            };

            // add a conexão
            config.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings
                {
                    Name = app.ConnectionName,
                    ConnectionString = scsb.ConnectionString,
                    ProviderName = "System.Data.SqlClient"
                });

            // salva conexão
            config.Save(ConfigurationSaveMode.Modified);
        }
        catch (Exception ex)
        {
            //Entrada já existe ou outro ...
        }
    }

    #endregion

}

You can also read and edit .config directly through Windows Forms. Just map the connection tag of the connectionString.

    
30.07.2017 / 01:15