3

With Advanced Installer, I'm trying to make a Custom Action, that at installationtime, encrypt the Connection String.

I seems like I can't use "~" here. (I moved my working code from the MVC project, to here).

Is there a simple alternative to that line or am I forced to make a complete rewrite and use e.g. a solution that uses somekind of Stream (like this Modifying Web.Config During Installation

Exception thrown by custom action: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The application relative virtual path '~' is not allowed here.

Custom Action:

[CustomAction]
public static ActionResult EncryptConnStr(Session session)
{
    try
    {
        var config = WebConfigurationManager.OpenWebConfiguration("~");
        var section = (ConnectionStringsSection)config.GetSection("connectionStrings");
        var cms = section.ConnectionStrings[GetConnectionStringName()];
        var connStr = BuildConnStr(session["CONN_STR_SERVER"], session["CONN_STR_DATABASE"], session["CONN_STR_USERNAME"], session["CONN_STR_PASSWORD"]);

        if (cms == null)
        {
            // Add new Connection String
            section.ConnectionStrings.Add(new ConnectionStringSettings(GetConnectionStringName(), connStr));
        }
        else
        {
            // Update existing Connection String
            cms.ConnectionString = connStr;
        }

        // Encrypt
        section.SectionInformation.ProtectSection(ConnStrEncryptionKey);

        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);

        return ActionResult.Success;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.StackTrace, ex.Message);
        throw;
    }
}
radbyx
  • 9,352
  • 21
  • 84
  • 127
  • Take a look in https://solutiondesign.com/blog/-/blogs/a-simple-trick-to-centralize-your-net-configurati-1/ – Ravikumar Aug 09 '17 at 13:51

1 Answers1

0

The solution to the path issue, is to use ConfigurationManager a long with some mapping, like this, instead of the web version WebConfigurationManager.

var map = new ExeConfigurationFileMap { ExeConfigFilename = path };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

The encryption works fine as the code is, but the issue with save is still not solved because the execution time is to early. The installation isn't finished and the web.config isn't yet copyed to the APPDIR.

radbyx
  • 9,352
  • 21
  • 84
  • 127