Publish Windows Form C#

Asked

Viewed 1,539 times

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 am developing.

My App.config owns the 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 production environment, ie publish. Using the option Publish from Visual Studio itself, it generates the executable, along with other files, which are these:

Arquivos

And inside the briefcase Application Files I own these others:

Arquivos2

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

Unable to download the application. Not all files required by the application are available.

When I return to the connectionStrings for the original, 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 hence my doubt arises: How to change the connectionStrings of the application, after publishing the application?

I thought of creating a file txt and read the connectionStrings but I don’t know if it’s viable, or if there’s a better way to do it.

2 answers

1


Ideal is 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 publishing, this should be done after installing the program... From what I’ve seen you’re using Clickonce to publish.. Then you should search for the following folder after the installation... c: user $Namedantity$ Appdata Local Apps 2.0 $Nameand$ $Othershow and search the application folder. Finding the folder will see the file . config with its connection..

I hope I’ve helped;

Abs. Augusto Cordeiro

  • I found the file, and it worked. But will these "strange names" always be the same? It is that we have many clients, and I need to document the form of installation. Keep putting "Strange Name" would catch "bad".

  • The option to create a TXT file to read would be unfeasible?

0

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

You can make a mask using String.Format and encapsulate the mounting of the new string. (It’s up to you how you mount it)

Note: Make sure that the context is pointing to string with the connection name in . config in this case the 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, below 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 from Windows Forms. Just map the connectionString Connection tag.

Browser other questions tagged

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