Installer
using System                        ;
using System.Collections.Generic    ;
using System.ComponentModel            ;
using System.Configuration.Install    ;
using System.Reflection                ;
using System.IO                        ;
using System.Collections            ;
using System.Diagnostics            ;
using System.DirectoryServices        ;
 
namespace Lex.Website
{
    [RunInstaller(true)]
    public partial class SiteInstaller : Installer
    {
        #region constructers
 
        public SiteInstaller()
        {
            InitializeComponent();
        }
 
        #endregion
 
        #region constants
 
        private const string DefaultDBConnectionString    = @"Data Source=(local);Initial Catalog=MyDB;Integrated Security=SSPI;"" providerName=""System.Data.SqlClient""";
        private const string DBConnectionProvider        = @"providerName=""System.Data.SqlClient"""    ;
        private const string DBConnectionKey            = @"DBConnection"                            ;
        private const string TargetFolderKey            = @"Folder"                                    ;
        private const string TargetSiteKey                = "Site"                                    ;
        private const string TargetVirtualDirKey        = "VDir"                                    ;
        private const string MetaBasePathToAppPools        = "IIS://localhost/W3SVC/AppPools"            ;
        private const string TargetAspNetVersion        = "v2.0.50727"                                ;
        private const string ApplicationPoolName        = "MediaServer " + TargetAspNetVersion        ;
 
        #endregion
 
        #region Methods
 
        public override void Install(IDictionary stateSaver)
        {
            //TextWriterTraceListener log = new TextWriterTraceListener(System.IO.File.CreateText(@"c:\installerLog.txt"));
            //Debug.Listeners.Add(log)        ;
 
            // the following parameters must be passed in via the CustomActionData property of the CustomAction for the Install Method
            // /tv=[TARGETVDIR] /ts=[TARGETSITE]
 
            string targetVDir    = Context.Parameters[TargetVirtualDirKey    ];
            string targetSite    = Context.Parameters[TargetSiteKey            ];
            targetSite            = (targetSite.StartsWith("/LM/"))? targetSite.Substring(4) : targetSite;
 
            CreateWebApplicationAndAppPool(targetSite, targetVDir, ApplicationPoolName);
            SetWebApplicationAspNetVersion(targetSite, targetVDir, TargetAspNetVersion);
            SetDBConnectionString(Context.Parameters[TargetFolderKey], Context.Parameters[DBConnectionKey]);
 
            Debug.Flush();
            base.Install(stateSaver);
        }
 
        /// <summary>
        /// CreateWebApplicationAndAppPool("W3SVC/2", "site", "MyAppPool");
        /// </summary>
        /// <param name="targetSite">metabase path to the website to use</param>
        /// <param name="targetVDir">virtual directory version</param>
        /// <param name="appPoolName">appPoolName is of the form "<name>", for example, "MyAppPool"</param>
        protected void CreateWebApplicationAndAppPool    (string targetSite, string targetVirtualDirectory, string applicationPoolName)
        {
            string metabasePath = String.Format("IIS://localhost/{0}/Root/{1}", targetSite, targetVirtualDirectory);
            Debug.WriteLine(String.Format("Assigning application {0} to the application pool named {1}:", metabasePath, applicationPoolName));
            try
            {
                using (DirectoryEntry virtualDirectory = new DirectoryEntry(metabasePath))
                {
                    string className = virtualDirectory.SchemaClassName.ToString();
                    if ((className.EndsWith("VirtualDir")) || (className.EndsWith("WebDirectory")))
                    {
                        // put the vdir in the desired app pool, creating the app pool if necessary
                        object[] parameters = { 2, applicationPoolName, true };
                        virtualDirectory.Invoke("AppCreate3", parameters);
                        // assign the application friendly name
                        virtualDirectory.Properties["AppFriendlyName"][0] = targetVirtualDirectory;
                        virtualDirectory.CommitChanges();
                    }
                    else
                    {
                        Debug.WriteLine("Only virtual directories can be assigned to application pools: classname=" + className);
                        throw new NotSupportedException("Only virtual directories can be assigned to application pools: classname=" + className);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Failed in AssignVDirToAppPool with the following exception: {0}", ex.Message));
                throw;
            }
        }
 
        /// <summary>
        /// SetWebApplicationASPNetVersion("W3SVC/2", "UniversitySite", "v2.0.50727");
        /// </summary>
        /// <param name="targetSite">metabase path to the website to use</param>
        /// <param name="targetVDir">virtual directory version</param>
        /// <param name="ASPNetVersion">asp net version number as specified in the path to the directory in the file system</param>
        protected void SetWebApplicationAspNetVersion    (string targetSite, string targetVDir, string ASPNetVersion)
        {
            Debug.WriteLine(String.Format("Assigning ASPNetVersion {0} to the vDir named {1} on WebSite {2}:", ASPNetVersion, targetVDir, targetSite));
            try
            {
                ProcessStartInfo processStartInfo    = new ProcessStartInfo();
                processStartInfo.FileName            = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), @"Microsoft.NET\Framework\" + ASPNetVersion + @"\aspnet_regiis.exe");
                processStartInfo.Arguments            = string.Format("-s {0}/Root/{1}", targetSite, targetVDir);
                processStartInfo.CreateNoWindow        = true    ;
                processStartInfo.UseShellExecute    = false    ;
                Process.Start(processStartInfo);
 
                Debug.WriteLine(" Done executing: " + processStartInfo.FileName + " " + processStartInfo.Arguments);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Failed in AssignASPNetVersionToVDir with the following exception: {0}", ex.Message));
                throw;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetFolder"></param>
        /// <param name="connectionString"></param>
        protected void SetDBConnectionString            (string targetFolder, string connectionString)
        {
            Assembly    assembly            = Assembly.GetExecutingAssembly();
            string        configurationText    = null;
 
            using (Stream        manifestStream    = assembly.GetManifestResourceStream(assembly.GetName().Name + ".connectionStrings.config"))
            {
                using (StreamReader    manifestReader        = new StreamReader(manifestStream))
                {
                    configurationText    = manifestReader.ReadToEnd()                    ;
                }
            }
 
            DirectoryInfo applicationFolder    = new DirectoryInfo(targetFolder);
            if (applicationFolder.Exists == false){applicationFolder.Create();}
 
            configurationText = configurationText.Replace(DefaultDBConnectionString, connectionString + DBConnectionProvider);
 
            using (FileStream outputStream = new FileStream(Path.Combine(applicationFolder.FullName, @"connectionStrings.config"), FileMode.Create))
            {
                using (StreamWriter outputWriter = new StreamWriter(outputStream))
                {
                    outputWriter.Write(configurationText);
                }
            }
        }
 
#endregion
 
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License