简体   繁体   中英

How to encrypt your Connection String in Advanced Installer (13.3) Custom Action

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 eg 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;
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM