public void TC001_TestRewireAspEventsSection()
        {
            //Arrange
            FileStream fs = File.Open(Path.Combine(tempAppFolder, "web.config"), FileMode.Open, FileAccess.Read);
            XmlDocument testDoc = new XmlDocument();
            testDoc.Load(fs);
            XPathNavigator nav = testDoc.CreateNavigator();
            nodeExisted = (nav.SelectSingleNode("configuration/system.web/healthMonitoring") != null);
            fs.Close();
            ISiteConfigManager configManager = new SiteConfig(tempAppFolder, true);
            INodeConfigRewireBase hmNodeConfig = new HealthMonRewire();

            //Act
            hmNodeConfig.Register(configManager);
            configManager.Rewire(false);
            configManager.CommitChanges();

            //Assert
            fs = File.Open(Path.Combine(tempAppFolder, "web.config"), FileMode.Open, FileAccess.Read);
            testDoc = new XmlDocument();
            testDoc.Load(fs);
            nav = testDoc.CreateNavigator();
            int sCount = 0;
            XPathNodeIterator iter = nav.Select("configuration/system.web/healthMonitoring");
            while (iter.MoveNext())
            {
                sCount++;
            }
            if (nodeExisted && sCount != 1)
            {
                Assert.Fail("Duplicate healthMonitoring section after rewiring");
                fs.Close();
            }
            else if (nodeExisted == false && sCount != 1)
            {
                Assert.Fail("Health Monitoring node was not wired in web config");
                fs.Close();
            }
            sCount = 0;
            iter = nav.Select("configuration/system.web/healthMonitoring/@*");
            while (iter.MoveNext())
            {
                sCount++;
            }

            if (sCount == 0)
                Assert.Fail("Rewired node must have only the 'configSource' attribute set.");
            fs.Close();
        }
        /// <summary>
        /// Autowires the service connections and ASP.NET health monitoring in the application's web.config
        /// </summary>
        /// <param name="appInfo">The application info structure.</param>
        /// <param name="variables">All application variables.</param>
        /// <param name="services">The services.</param>
        /// <param name="logFilePath">The ASP.NET "Heartbeat" and "Lifetime Events" log file path.</param>
        /// <param name="errorLogFilePath">The ASP.NET "All Errors" events log file path.</param>
        private void AutowireApp(ApplicationInfo appInfo, ApplicationVariable[] variables, ApplicationService[] services, string logFilePath, string errorLogFilePath)
        {
            this.startupLogger.Info(Strings.StartingApplicationAutoWiring);

            List<ApplicationVariable> varList = variables.ToList<ApplicationVariable>();
            ApplicationVariable applicationVariable = new ApplicationVariable();
            applicationVariable.Name = "TUNNEL_NET_TCP_PORT";
            applicationVariable.Value = NetworkInterface.GrabEphemeralPort().ToString(CultureInfo.InvariantCulture);
            varList.Add(applicationVariable);
            variables = varList.ToArray();

            // get all config files
            string[] allConfigFiles = Directory.GetFiles(appInfo.Path, "*.config", SearchOption.AllDirectories);

            foreach (string configFile in allConfigFiles)
            {
                if (File.Exists(configFile))
                {
                    string configFileContents = File.ReadAllText(configFile);

                    if (services != null)
                    {
                        Dictionary<string, string> connections = new Dictionary<string, string>();
                        Dictionary<string, string> connValues = new Dictionary<string, string>();

                        foreach (ApplicationService service in services)
                        {
                            string key = service.ServiceLabel;
                            string template = string.Empty;

                            if (this.autoWireTemplates.TryGetValue(key, out template))
                            {
                                template = template.Replace(Strings.Host, service.Host);
                                template = template.Replace(Strings.Port, service.Port.ToString(CultureInfo.InvariantCulture));
                                template = template.Replace(Strings.Name, service.InstanceName);
                                template = template.Replace(Strings.User, service.User);
                                template = template.Replace(Strings.Password, service.Password);

                                connections[string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", key, service.Name)] = template;
                            }

                            char[] charsToTrim = { '{', '}' };
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.User.Trim(charsToTrim)), service.User);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Host.Trim(charsToTrim)), service.Host);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Port.Trim(charsToTrim)), service.Port.ToString(CultureInfo.InvariantCulture));
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Password.Trim(charsToTrim)), service.Password);
                            connValues.Add(string.Format(CultureInfo.InvariantCulture, "{{{0}#{1}}}", service.Name, Strings.Name.Trim(charsToTrim)), service.InstanceName);
                        }

                        foreach (string con in connections.Keys)
                        {
                            this.startupLogger.Info(Strings.ConfiguringService + con);
                            configFileContents = configFileContents.Replace(con, connections[con]);
                        }

                        foreach (string key in connValues.Keys)
                        {
                            this.startupLogger.Info(string.Format(CultureInfo.InvariantCulture, Strings.ConfiguringServiceValue, key));
                            configFileContents = configFileContents.Replace(key, connValues[key]);
                        }
                    }

                    File.WriteAllText(configFile, configFileContents);
                }
            }

            string webConfigFile = Path.Combine(appInfo.Path, "web.config");
            if (File.Exists(webConfigFile))
            {
                this.SetApplicationVariables(webConfigFile, variables, logFilePath, errorLogFilePath);

                this.startupLogger.Info(Strings.SavedConfigurationFile);

                this.startupLogger.Info(Strings.SettingUpLogging);

                string appDir = Path.GetDirectoryName(webConfigFile);
                string binDir = Path.Combine(appDir, "bin");
                string assemblyFile = typeof(LogFileWebEventProvider).Assembly.Location;
                string destinationAssemblyFile = Path.Combine(binDir, Path.GetFileName(assemblyFile));

                Directory.CreateDirectory(binDir);

                File.Copy(assemblyFile, destinationAssemblyFile, true);

                this.startupLogger.Info(Strings.CopiedLoggingBinariesToBin);

                SiteConfig siteConfiguration = new SiteConfig(appDir, true);
                HealthMonRewire healthMon = new HealthMonRewire();
                healthMon.Register(siteConfiguration);

                siteConfiguration.Rewire(false);
                siteConfiguration.CommitChanges();

                this.startupLogger.Info(Strings.UpdatedLoggingConfiguration);

                DirectoryInfo errorLogDir = new DirectoryInfo(Path.GetDirectoryName(errorLogFilePath));
                DirectoryInfo logDir = new DirectoryInfo(Path.GetDirectoryName(logFilePath));

                DirectorySecurity errorLogDirSecurity = errorLogDir.GetAccessControl();
                DirectorySecurity logDirSecurity = logDir.GetAccessControl();

                errorLogDirSecurity.SetAccessRule(
                    new FileSystemAccessRule(
                        appInfo.WindowsUserName,
                        FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.CreateFiles,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow));

                logDirSecurity.SetAccessRule(
                    new FileSystemAccessRule(
                        appInfo.WindowsUserName,
                        FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.CreateFiles,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow));

                errorLogDir.SetAccessControl(errorLogDirSecurity);
                logDir.SetAccessControl(logDirSecurity);
            }
        }