예제 #1
0
        public static string GetConfigurationValue(ConfigurationAttribute attribute)
        {
            // there are a few problems with doing it differently, more precisely
            // with trying to find at runtime which environment we are running in:

            // #1: when running in the console application, WindowsAzure.ServiceRuntime.dll fails to load
            // so we can't even check RoleEnvironment.IsAvailable

            // #2: when invoked by a test within Visual Studio, RoleEnvironment.IsAvailable returns true
            // and then, of course, fails to read configuration

            // so there

            try
            {
                if (IsAzure)
                {
                    return(RoleEnvironment.GetConfigurationSettingValue(attribute.Name));
                }
                return(ConfigurationManager.AppSettings[attribute.Name]);
            }
            catch (Exception e)
            {
                if (attribute.DefaultValue == null)
                {
                    Log.Error("Unable to read configuration variable [{0}]".ExpandWith(attribute.Name));
                    Log.Error(e);
                    throw;
                }
                Log.Warning("Unable to read configuration variable [{0}], using default value [{0}]".ExpandWith(attribute.Name, attribute.DefaultValue));
                return(attribute.DefaultValue);
            }
        }
예제 #2
0
        }         // SetWebSiteUploadLimitation

        private int GetWebSiteUploadLimitation(Microsoft.Web.Administration.Configuration oConfig, string sControllerAction)
        {
            int nResult = 0;

            try {
                ConfigurationSection requestFilteringSection = string.IsNullOrWhiteSpace(sControllerAction)
                                        ? oConfig.GetSection(SectionPath)
                                        : oConfig.GetSection(SectionPath, sControllerAction);

                ConfigurationElement requestLimitsElement = requestFilteringSection.GetChildElement(ElementName);

                ConfigurationAttribute oAttr = requestLimitsElement.GetAttribute(AttributeName);

                if (oAttr != null)
                {
                    int macl;

                    if (int.TryParse(oAttr.Value.ToString(), out macl))
                    {
                        nResult = macl;
                    }
                    else
                    {
                        m_oLog.Warn("Failed to parse upload limit for action '{0}'.", sControllerAction);
                    }
                }                 // if

                m_oLog.Debug("Current upload limit for action '{1}' is {0} bytes.", nResult, sControllerAction);
            }
            catch (Exception e) {
                m_oLog.Warn(e, "Failed to load upload limit for action '{0}'.", sControllerAction);
            }             // try

            return(nResult);
        } // GetWebSiteUploadLimitation
        public static string GetWebRootPath([NotNull] Site site)
        {
            Assert.ArgumentNotNull(site, nameof(site));

            Application apps = site.Applications["/"];

            if (apps != null)
            {
                VirtualDirectory vdirs = apps.VirtualDirectories["/"];
                if (vdirs != null)
                {
                    ConfigurationAttribute phpath = vdirs.Attributes["physicalPath"];
                    if (phpath != null)
                    {
                        var value = (string)phpath.Value;
                        if (!string.IsNullOrEmpty(value))
                        {
                            return(value);
                        }
                    }
                }
            }

            throw new Exception($"IIS website {site.Id} seems to be corrupted or misconfigured");
        }
예제 #4
0
        /// <summary>
        ///     Configures the automatic start provider.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="type">The type.</param>
        public void CreateAutoStartProvider(string name, Type type)
        {
            if (string.IsNullOrEmpty(name))
            {
                WriteLine("No auto start provider name specified. Skipping.", Severity.Warning);
                return;
            }

            if (type == null)
            {
                WriteLine("No auto start provider type specified. Skipping.", Severity.Warning);
                return;
            }

            if (_serverManager == null)
            {
                WriteLine($"Failed to configure auto-start provider '{name}'. No connection to IIS.", Severity.Error);
                return;
            }

            bool modified = false;

            var hostConfiguration = _serverManager.GetApplicationHostConfiguration( );
            var serviceAutoStartProvidersSection    = hostConfiguration.GetSection("system.applicationHost/serviceAutoStartProviders");
            var serviceAutoStartProvidersCollection = serviceAutoStartProvidersSection.GetCollection( );

            ConfigurationElement serviceAutoStartProvider = null;

            foreach (var item in serviceAutoStartProvidersCollection)
            {
                ConfigurationAttribute attribute = item.Attributes ["name"];

                if (attribute != null && string.Equals(attribute.Value.ToString( ), name, StringComparison.InvariantCultureIgnoreCase))
                {
                    serviceAutoStartProvider = item;
                    break;
                }
            }

            if (serviceAutoStartProvider == null)
            {
                WriteLine($"Creating service auto-start provider '{name}' with type '{type.AssemblyQualifiedName}'.");

                serviceAutoStartProvider          = serviceAutoStartProvidersCollection.CreateElement("add");
                serviceAutoStartProvider ["name"] = name;
                serviceAutoStartProvider ["type"] = type.AssemblyQualifiedName;
                serviceAutoStartProvidersCollection.Add(serviceAutoStartProvider);
                modified = true;
            }
            else
            {
                WriteLine($"Found existing service auto-start provider with name '{name}'.");
            }

            if (modified)
            {
                _serverManager.CommitChanges( );
            }
        }
예제 #5
0
 internal static void CommitToWebConfigMWA(ExchangeVirtualDirectory exchangeVirtualDirectory, Task task, string path, string site, string server, bool isTokenCheckingSpecified, bool isSpnListSpecified)
 {
     if (ExtendedProtection.WebConfigReflectionHelper.isExtendedProtectionSupported && (isTokenCheckingSpecified || isSpnListSpecified))
     {
         using (ServerManager serverManager = ServerManager.OpenRemote(server))
         {
             Configuration webConfiguration      = serverManager.GetWebConfiguration(site, path);
             string        configurationFilePath = ExtendedProtection.WebConfigReflectionHelper.GetConfigurationFilePath(serverManager, site, path);
             if (!string.IsNullOrEmpty(configurationFilePath) && File.Exists(configurationFilePath))
             {
                 ConfigurationSection section = webConfiguration.GetSection(ExtendedProtection.BindingsSectionName);
                 if (section != null)
                 {
                     ConfigurationElement configurationElement = section.ChildElements["customBinding"];
                     if (configurationElement != null)
                     {
                         ConfigurationElementCollection collection = configurationElement.GetCollection();
                         if (collection != null)
                         {
                             bool flag = false;
                             foreach (ConfigurationElement configurationElement2 in collection)
                             {
                                 ConfigurationElement   configurationElement3 = configurationElement2.ChildElements["httpsTransport"];
                                 ConfigurationAttribute attribute             = configurationElement3.GetAttribute("authenticationScheme");
                                 if (attribute.IsInheritedFromDefaultValue)
                                 {
                                     configurationElement3 = configurationElement2.ChildElements["httpTransport"];
                                     attribute             = configurationElement3.GetAttribute("authenticationScheme");
                                 }
                                 if (!attribute.IsInheritedFromDefaultValue && (int)attribute.Value == 2)
                                 {
                                     ConfigurationElement configurationElement4 = configurationElement3.ChildElements["extendedProtectionPolicy"];
                                     if (configurationElement4 != null)
                                     {
                                         if (isTokenCheckingSpecified)
                                         {
                                             ExtendedProtection.WebConfigReflectionHelper.SetPolicyEnforcementMWA(configurationElement4, exchangeVirtualDirectory.ExtendedProtectionTokenChecking);
                                         }
                                         if (isSpnListSpecified)
                                         {
                                             ExtendedProtection.WebConfigReflectionHelper.SetServiceNamesMWA(configurationElement4, exchangeVirtualDirectory.ExtendedProtectionSPNList);
                                         }
                                         flag = true;
                                     }
                                 }
                             }
                             if (flag)
                             {
                                 serverManager.CommitChanges();
                             }
                         }
                     }
                 }
             }
         }
     }
 }
예제 #6
0
        static void Main(string[] args)
        {
            ServerManager          serverManager = new ServerManager();
            Configuration          config        = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection   section       = config.GetSection("system.webServer/defaultDocument", "Default Web Site");
            ConfigurationAttribute enabled       = section.GetAttribute("enabled");

            enabled.Value = false;
            serverManager.CommitChanges();
        }
예제 #7
0
 private string GetSafeAttributeValue(ConfigurationAttribute attribute)
 {
     try
     {
         return(attribute.Value != null?attribute.Value.ToString() : "");
     }
     catch (Exception)
     {
         return("");
     }
 }
예제 #8
0
        private void UpdateRequestAndThreadsLimits()
        {
            TaskLogger.LogEnter();
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration          applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection   section   = applicationHostConfiguration.GetSection("system.webServer/serverRuntime");
                ConfigurationAttribute attribute = section.GetAttribute("appConcurrentRequestLimit");
                if (attribute != null && attribute.Schema != null && (long)attribute.Value == (long)((ulong)((uint)attribute.Schema.DefaultValue)))
                {
                    attribute.Value = 50000;
                    TaskLogger.Trace("Update applicationHost.config setting appConcurrentRequestLimit to {0}.", new object[]
                    {
                        attribute.Value
                    });
                }
                TaskLogger.Trace("Unlock system.webServer/serverRuntime for all web sites", new object[0]);
                section.OverrideMode = 2;
                serverManager.CommitChanges();
            }
            Configuration       configuration       = WebConfigurationManager.OpenMachineConfiguration();
            ProcessModelSection processModelSection = (ProcessModelSection)configuration.GetSection("system.web/processModel");
            bool flag = false;

            if (processModelSection.RequestQueueLimit == 5000)
            {
                processModelSection.RequestQueueLimit = 25000;
                flag = true;
                TaskLogger.Trace("Update machine.config setting requestQueueLimit to {0}.", new object[]
                {
                    processModelSection.RequestQueueLimit
                });
            }
            if (processModelSection.AutoConfig)
            {
                processModelSection.AutoConfig = false;
                flag = true;
                TaskLogger.Trace("Update machine.config autoconfig to false.", new object[0]);
            }
            if (processModelSection.MinWorkerThreads < 9)
            {
                processModelSection.MinWorkerThreads = 9;
                flag = true;
                TaskLogger.Trace("Update machine.config minWorkerThreads to {0}", new object[]
                {
                    processModelSection.MinWorkerThreads
                });
            }
            if (flag)
            {
                configuration.Save();
            }
            TaskLogger.LogExit();
        }
예제 #9
0
        /// <summary>
        /// Performs one-time configuration of IIS/ARR.
        /// </summary>
        private static void ConfigureOnce(string serverEndpointName, IPEndPoint bindInfo)
        {
            using (ServerManager sm = new ServerManager())
            {
                Configuration        config = sm.GetApplicationHostConfiguration();
                ConfigurationSection rules  = config.GetSection("system.webServer/rewrite/rules");

                // Check if we already have a rewrite rule for this farm.
                bool ruleFound = rules.GetCollection().Any(e =>
                {
                    ConfigurationAttribute name = e.Attributes["name"];
                    return(name != null && name.Value.ToString().Equals(
                               serverEndpointName,
                               StringComparison.OrdinalIgnoreCase));
                });

                if (!ruleFound)
                {
                    ConfigurationElement rule = rules.GetCollection().CreateElement("rule");
                    rule.SetAttributeValue("name", serverEndpointName);
                    rule.SetAttributeValue("stopProcessing", true);
                    rule.GetChildElement("match").SetAttributeValue("url", ".*");
                    rule.GetChildElement("action").SetAttributeValue("type", "Rewrite");
                    rule.GetChildElement("action").SetAttributeValue(
                        "url",
                        string.Format(CultureInfo.InvariantCulture, @"http://{0}/{{R:0}}", serverEndpointName));

                    rules.GetCollection().Add(rule);

                    // Ensure that the default app pool is set to classic mode.
                    Debug.Assert(sm.ApplicationPools["DefaultAppPool"] != null, "DefaultAppPool is not present");
                    sm.ApplicationPools["DefaultAppPool"].ManagedPipelineMode =
                        ManagedPipelineMode.Classic;

                    // Make sure that we have a binging in the default web site, which listens on ARR port.
                    Debug.Assert(sm.Sites["Default Web Site"] != null, "Default Web Site is not present");
                    foreach (Binding binding in sm.Sites["Default Web Site"].Bindings)
                    {
                        if (binding.Protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
                        {
                            binding["bindingInformation"] = string.Format(
                                CultureInfo.InvariantCulture,
                                "{0}:{1}:",
                                bindInfo.Address.ToString(),
                                bindInfo.Port);
                            break;
                        }
                    }
                }

                sm.CommitChanges();
            }
        }
        public attribute Convert(ConfigurationAttribute ca)
        {
            var a = new attribute
            {
                name    = ca.Name,
                present = ca.Present == Present.No
                                  ? null
                                  : new present {
                    xml = ca.Present == Present.YesXml, xmlSpecified = true
                },
                search_attributes = ca.SearchOptions != null
                                            ? new[]
                {
                    new search_attribute
                    {
                        name         = ca.Name,
                        format       = _configurationOptions.Format(ca.SearchOptions.Format),
                        locale       = ca.SearchOptions.Locale,
                        match_suffix = ca.SearchOptions.MatchSuffix,
                        suggest      = ca.SearchOptions.Suggest
                    }
                }
                                            : new search_attribute[0],
                filter_attributes = ca.FilterOptions != null
                                            ? new[]
                {
                    new filter_attribute
                    {
                        name         = ca.Name,
                        format       = _configurationOptions.Format(ca.FilterOptions.Format),
                        tokenization = _configurationOptions.Tokenization(ca.FilterOptions.Tokenization),
                        type         = ca.Type
                    }
                }
                                            : new filter_attribute[0],
                sort_attributes = ca.SortOptions != null
                                          ? new[]
                {
                    new sort_attribute
                    {
                        name          = ca.Name,
                        normalization = _configurationOptions.Normalization(ca.SortOptions.Normalization),
                        type          = ca.Type
                    }
                }
                                          : new sort_attribute[0]
            };

            return(a);
        }
예제 #11
0
 private void SetAttributeDefaults(PropertyInfo info, ConfigurationAttribute atty)
 {
     if (info != null && atty != null)
     {
         //set the KeyName as the property name if it is empty
         if (string.IsNullOrEmpty(atty.KeyName))
         {
             atty.KeyName = info.Name;
         }
     }
     else
     {
         _logger.Log("SetAttributeDefault called with null parameters!", LogMessageSeverity.Error);
     }
 }
 public void AttributesExpectedTest()
 {
     foreach (var expectedAttribute in _expectedConfigurationAttributes)
     {
         ConfigurationAttribute expectedAttribute1 = expectedAttribute;
         try
         {
             _attributes.Single(a => a.Name == expectedAttribute1.Name);
         }
         catch (Exception)
         {
             Console.WriteLine("Test failed with expected attribute [name: {0}].", expectedAttribute1.Name);
             throw;
         }
     }
 }
예제 #13
0
        private static ConfigurationElement GetFarmElement(ServerManager sm, string serverEndpointName, Boolean enableAffinity)
        {
            ConfigurationElement farmElement = null;
            Configuration        config      = sm.GetApplicationHostConfiguration();
            ConfigurationSection webFarms    = config.GetSection("webFarms");

            Debug.Assert(webFarms != null, "webFarms element is not present");

            ConfigurationElementCollection webFarmsCollection = webFarms.GetCollection();

            // See if we already have a farm.
            foreach (ConfigurationElement farm in webFarmsCollection)
            {
                ConfigurationAttribute name = farm.Attributes["name"];
                if (name != null && name.Value.ToString().Equals(
                        serverEndpointName,
                        StringComparison.OrdinalIgnoreCase))
                {
                    farmElement = farm;
                    break;
                }
            }

            if (farmElement == null)
            {
                farmElement = webFarmsCollection.CreateElement("webFarm");
                farmElement.SetAttributeValue("name", serverEndpointName);
                farmElement.SetAttributeValue("enabled", "true");
                if (enableAffinity)
                {
                    farmElement.GetChildElement("applicationRequestRouting").
                    GetChildElement("affinity").SetAttributeValue("useCookie", true);
                    farmElement.GetChildElement("applicationRequestRouting").
                    GetChildElement("affinity").SetAttributeValue("cookieName", "ARRWAP4EJ");
                    farmElement.GetChildElement("applicationRequestRouting").
                    GetChildElement("loadBalancing").SetAttributeValue("algorithm", "WeightedRoundRobin");
                }
                farmElement.GetChildElement("applicationRequestRouting").
                GetChildElement("protocol").SetAttributeValue("timeout", TimeSpan.Parse(ARR_TIME_OUT));

                webFarmsCollection.Add(farmElement);
            }

            return(farmElement);
        }
예제 #14
0
        public static string EditSiteConfig(string applicationName, string xPath, string attribute, string value)
        {
            try
            {
                using (ServerManager serverManager = new ServerManager(IIS_CONFIG_LOCAL_PATH))
                {
                    Configuration          webConfiguration       = serverManager.GetWebConfiguration(applicationName);
                    ConfigurationSection   configurationSection   = webConfiguration.GetSection(xPath);
                    ConfigurationAttribute configurationAttribute = configurationSection.GetAttribute(attribute);

                    configurationAttribute.Value = value;
                    serverManager.CommitChanges();
                }

                return("F**k yeah! It works baby");
            }
            catch (System.Exception exc)
            {
                return(exc.Message);
            }
        }
예제 #15
0
        /// <summary>
        /// 扫描Configuration特性的类,并创建实例。
        /// </summary>
        /// <param name="dlls">指定的要被扫描的dll。</param>
        private void ScanConfigurationAttribute(string[] dlls)
        {
            foreach (string dll in dlls)
            {
                Assembly assembly = Assembly.LoadFile(dll);
                Type[]   types    = assembly.GetTypes();
                foreach (Type clazz in types)
                {
                    if (clazz.IsClass)
                    {
                        //1.扫描类的Configuration特性
                        //获取属性
                        Attribute attributeConfigurationAttribute = clazz.GetCustomAttribute(typeof(ConfigurationAttribute));
                        if (attributeConfigurationAttribute == null)//如果该类没有Configuration特性
                        {
                            continue;
                        }
                        ConfigurationAttribute configurationAttribute = (ConfigurationAttribute)attributeConfigurationAttribute;
                        string configurationName = clazz.Name.Substring(0, 1).ToLower() + (clazz.Name.Length > 1 ? clazz.Name.Substring(1) : string.Empty);
                        if (!string.IsNullOrWhiteSpace(configurationAttribute.Name))//如果设置了ConfigurationAttribute的Name值
                        {
                            configurationName = configurationAttribute.Name;
                        }
                        if (BeanContainer.ContainsKey(configurationName))
                        {
                            throw new BeanCreationException(string.Format("不能创建‘{0}’,已经存在该实例。", configurationName));
                        }

                        //添加实例到容器中
                        object clazzInstance = Activator.CreateInstance(clazz);//创建类的实例
                        BeanContainer.Add(configurationName, new BeanInfo()
                        {
                            Bean = clazzInstance, AtrributeType = AtrributeType.Configuration
                        });
                    } //end : if (clazz.IsClass)
                }     //end : foreach (Type clazz in types)
            }         //end : foreach (string dll in dlls)
        }
        public static void UpdateSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var section = GetSection(site, path, configPath);

            try {
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled = v);
                DynamicHelper.If((object)model.user, v => section.UserName          = v);
                DynamicHelper.If((object)model.password, v => section.Password      = v);

                string user = DynamicHelper.Value(model.user);

                // Empty username is for application pool identity
                bool deletePassword = (user != null) && (user.Equals(string.Empty) || user.Equals("iusr", StringComparison.OrdinalIgnoreCase));
                if (deletePassword)
                {
                    ConfigurationAttribute passwordAttr = section.GetAttribute("password");
                    passwordAttr.Delete();
                }

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
예제 #17
0
 /// <summary>
 /// Construtor.
 /// </summary>
 /// <param name="ca"></param>
 /// <param name="methodInfo"></param>
 public MethodTarget(ConfigurationAttribute ca, MethodInfo methodInfo) : base(ca)
 {
     dispatcher = new MethodDispatcher(new MethodInvoker(methodInfo, ca.RequiredParameters));
 }
예제 #18
0
        /// <summary>
        ///     Removes the automatic start provider.
        /// </summary>
        /// <param name="name">The name.</param>
        public void RemoveAutoStartProvider(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                WriteLine("No auto start provider name specified. Skipping removal of auto start provider.", Severity.Warning);
                return;
            }

            if (_serverManager == null)
            {
                WriteLine($"Failed to remove auto-start provider '{name}'. No connection to IIS.", Severity.Error);
                return;
            }

            Site defaultSite = DefaultSite;

            if (defaultSite == null)
            {
                WriteLine($"Failed to remove auto start provider '{name}'. No IIS default site found. Please ensure IIS is configured and running on the local machine.", Severity.Error);
                return;
            }

            int count = 0;

            foreach (Application app in defaultSite.Applications)
            {
                object autoStartProviderObject = app.GetAttributeValue("serviceAutoStartProvider");

                if (autoStartProviderObject != null)
                {
                    if (string.Equals(autoStartProviderObject.ToString( ), name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        WriteLine($"Found auto start provider '{name}' in use by application '{app.Path}'.");
                        count++;
                    }
                }
            }

            bool modified = false;

            if (count > 0)
            {
                WriteLine($"Auto start provider '{name}' currently in use and will not be removed.", Severity.Warning);
            }
            else
            {
                var hostConfiguration = _serverManager.GetApplicationHostConfiguration( );
                var serviceAutoStartProvidersSection    = hostConfiguration.GetSection("system.applicationHost/serviceAutoStartProviders");
                var serviceAutoStartProvidersCollection = serviceAutoStartProvidersSection.GetCollection( );

                ConfigurationElement serviceAutoStartProvider = null;

                foreach (var item in serviceAutoStartProvidersCollection)
                {
                    ConfigurationAttribute attribute = item.Attributes ["name"];

                    if (attribute != null && string.Equals(attribute.Value.ToString( ), name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        serviceAutoStartProvider = item;
                        break;
                    }
                }

                if (serviceAutoStartProvider == null)
                {
                    WriteLine($"Service auto-start provider '{name}' not found. Skipping.");
                }
                else
                {
                    WriteLine($"Removing service auto start provider '{name}'...");

                    serviceAutoStartProvidersCollection.Remove(serviceAutoStartProvider);

                    modified = true;
                }
            }

            if (modified)
            {
                _serverManager.CommitChanges( );

                WriteLine($"Service auto start provider '{name}' successfully removed.");
            }
        }
예제 #19
0
        public static List <SiteInfo> GetSiteInfo()
        {
            List <SiteInfo> siteList = new List <SiteInfo>();

            if (TestMode)
            {
                siteList.Add(new SiteInfo(1, "Test Site", "TestAppPool", "%windir%\\inetpub\\logs\\", "running", "OK"));
            }
            else
            {
                try
                {
                    ServerManager  server = new ServerManager();
                    SiteCollection sites  = server.Sites;
                    foreach (Site site in sites)
                    {
                        //Get AdvancedLogging Directory
                        string SiteName = Convert.ToString(site.Name);
                        string LogPath;
                        string Status = "OK";
                        try {
                            //Load AppSettings to see if AdvancedLogging is configured
                            string AdvancedLoggingSiteDirectory = Settings.GetAppSetting("AdvancedLoggingSiteDirectory");
                            ConfigurationElement   logAttr      = site.GetChildElement("advancedLogging");
                            ConfigurationAttribute logPathAttr  = logAttr.GetAttribute("directory");
                            //Check the app.config to see AdvancedLogging site name directory format
                            if (AdvancedLoggingSiteDirectory == "%siteName")
                            {
                                if (Settings.GetAppSetting("AdvancedLoggingSiteDirectoryAllCaps") == "true")
                                {
                                    LogPath = "*" + Convert.ToString(logPathAttr.Value) + SiteName.ToUpper() + "\\";
                                }
                                else
                                {
                                    LogPath = "*" + Convert.ToString(logPathAttr.Value) + SiteName + "\\";
                                }
                            }
                            else if (AdvancedLoggingSiteDirectory != "error")
                            {
                                LogPath = "*" + Convert.ToString(logPathAttr.Value) + AdvancedLoggingSiteDirectory + "\\";
                            }
                            else
                            {
                                LogPath = "*" + Convert.ToString(logPathAttr.Value);
                            }
                            //Strip off any beginning identifiers and check if directory exists
                            if (!System.IO.Directory.Exists(@LogPath.Trim(new Char[] { ' ', '*', '.', '!' })))
                            {
                                LogPath = "!" + LogPath;
                                Status  = "error";
                            }
                        } catch (Exception ex)
                        {
                            //ApplicationDefaults defaults = site.ApplicationDefaults;
                            LogPath = Convert.ToString(site.LogFile);
                            Status  = "error";
                        }
                        site.Applications[0].ToString();

                        siteList.Add(new SiteInfo(Convert.ToInt32(site.Id), SiteName, site.Applications[0].ApplicationPoolName.ToString(), LogPath, site.State.ToString(), Status));
                    }
                }
                catch (Exception e)
                {
                    siteList.Add(new SiteInfo(0, "Error", "Error Loading Site", "Error", "Error", "Error"));
                    ErrorHandler.logError("Error Connecting to IIS Manager", "There was an error thrown while connecting to the IIS Manager, see inner exception for details", "error", true, e);
                }
            }
            return(siteList);
        }
 public override string GetConfigurationValue(ConfigurationAttribute attribute)
 {
     return(RoleEnvironment.GetConfigurationSettingValue(attribute.Name));
 }
예제 #21
0
        /// <summary>
        /// 扫描Bean特性的方法,并创建实例。
        /// </summary>
        /// <param name="dlls">指定的要被扫描的dll。</param>
        private void ScanBeanAttribute(string[] dlls)
        {
            foreach (string dll in dlls)
            {
                Assembly assembly = Assembly.LoadFile(dll);
                Type[]   types    = assembly.GetTypes();
                foreach (Type clazz in types)
                {
                    if (clazz.IsClass)
                    {
                        //1.扫描类的Configuration特性
                        //获取属性
                        Attribute attributeConfigurationAttribute = clazz.GetCustomAttribute(typeof(ConfigurationAttribute));
                        if (attributeConfigurationAttribute == null)//如果该类没有Configuration特性
                        {
                            continue;
                        }
                        ConfigurationAttribute configurationAttribute = (ConfigurationAttribute)attributeConfigurationAttribute;
                        string beanName = clazz.Name.Substring(0, 1).ToLower() + (clazz.Name.Length > 1 ? clazz.Name.Substring(1) : string.Empty);
                        if (!string.IsNullOrWhiteSpace(configurationAttribute.Name))
                        {
                            beanName = configurationAttribute.Name;
                        }

                        bool           isDefault         = true;//是否使用默认配置文件
                        PropertiesUtil _properties       = null;
                        string         configurationPath = "application.properties";
                        if (!string.IsNullOrWhiteSpace(configurationAttribute.Path))//如果设置了ConfigurationAttribute的Path值
                        {
                            configurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configurationAttribute.Path);
                            _properties       = new PropertiesUtil(configurationPath);
                            isDefault         = false;
                        }

                        //2.扫描字段的Value特性
                        FieldInfo[] fieldInfos = clazz.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
                        foreach (FieldInfo fieldInfo in fieldInfos)
                        {
                            Attribute attributeValueAttribute = fieldInfo.GetCustomAttribute(typeof(ValueAttribute));
                            if (attributeValueAttribute == null)//如果此字段没有Value特性
                            {
                                continue;
                            }

                            ValueAttribute valueAttribute = (ValueAttribute)attributeValueAttribute;
                            string         valueName      = fieldInfo.Name; //字段名称
                            if (!string.IsNullOrWhiteSpace(valueName))      //如果设置了ValueAttribute的Key值
                            {
                                valueName = valueAttribute.Key;
                            }

                            if (BeanContainer.ContainsKey(beanName))
                            {
                                if (isDefault == false)//如果使用的不是默认配置文件
                                {
                                    fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(_properties[valueName], fieldInfo.FieldType));
                                }
                                else
                                {
                                    fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(Properties[valueName], fieldInfo.FieldType));
                                }
                            }
                        }


                        //3.扫描方法的Bean特性
                        MethodInfo[] methods = clazz.GetMethods();
                        foreach (MethodInfo method in methods)
                        {
                            Attribute attributeBeanAttribute = method.GetCustomAttribute(typeof(BeanAttribute));
                            if (attributeBeanAttribute == null)//如果此方法没有Bean特性
                            {
                                continue;
                            }
                            BeanAttribute beanAttribute = (BeanAttribute)attributeBeanAttribute;
                            string        methodName    = method.Name;          //方法名称
                            if (!string.IsNullOrWhiteSpace(beanAttribute.Name)) //如果设置了BeanAttribute的Name值
                            {
                                methodName = beanAttribute.Name;
                            }
                            if ("Void".Equals(method.ReturnType.Name))//如果此方法无返回值
                            {
                                throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。方法需要返回值。", methodName));
                            }
                            if (BeanContainer.ContainsKey(beanAttribute.Name))//判断单例容器里是否已存在
                            {
                                throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。已经存在名为‘{1}’的实例。", methodName, methodName));
                            }


                            //4.扫描方法参数的Parameter特性
                            ParameterInfo[] parameterInfos = method.GetParameters();
                            int             parameterCount = parameterInfos.Length;
                            if (parameterCount > 0)//如果有参数
                            {
                                object[] parameterValues = new object[parameterCount];
                                int      index           = 0;
                                foreach (ParameterInfo parameterInfo in parameterInfos)//设置参数的值
                                {
                                    Attribute attributeParameterAttribute = parameterInfo.GetCustomAttribute(typeof(ParameterAttribute));
                                    string    parameterName = parameterInfo.Name; //默认参数的名称
                                    if (attributeParameterAttribute != null)      //如果有特性标注
                                    {
                                        ParameterAttribute parameterAttribute = (ParameterAttribute)attributeParameterAttribute;
                                        parameterName = parameterAttribute.Name;
                                    }
                                    if (!BeanContainer.ContainsKey(parameterName)) //如果从容器中找不到参数的实例
                                    {
                                        if (parameterInfo.HasDefaultValue)         //根据参数是否设置了默认值来决定是否抛出异常
                                        {
                                            parameterValues[index] = parameterInfo.DefaultValue;
                                            continue;
                                        }
                                        throw new BeanNotFoundException(string.Format("找不到指定的实例‘{0}’。", parameterName));
                                    }
                                    parameterValues[index] = BeanContainer[parameterName].Bean;
                                    index++;
                                }

                                if (BeanContainer.ContainsKey(beanName))
                                {
                                    //执行方法,得到方法的返回值,并存入单例容器
                                    object objReturn = method.Invoke(BeanContainer[beanName].Bean, parameterValues);
                                    BeanContainer.Add(methodName, new BeanInfo()
                                    {
                                        Bean = objReturn, AtrributeType = AtrributeType.Bean
                                    });
                                }
                            }
                            else//如果无参数
                            {
                                if (BeanContainer.ContainsKey(beanName))
                                {
                                    //执行方法,得到方法的返回值,并存入单例容器
                                    object objReturn = method.Invoke(BeanContainer[beanName].Bean, null);
                                    BeanContainer.Add(methodName, new BeanInfo()
                                    {
                                        Bean = objReturn, AtrributeType = AtrributeType.Bean
                                    });
                                }
                            }
                        } //end : foreach (MethodInfo method in methods)
                    }     //end : if (clazz.IsClass)
                }         //end : foreach (Type clazz in types)
            }             //end : foreach (string dll in dlls)
        }
예제 #22
0
 /// <summary>
 /// Construtor
 /// </summary>
 /// <param name="ca">Metadado relacionado com a propriedade.</param>
 /// <param name="pi">Propriedade</param>
 public PropertyTarget(ConfigurationAttribute ca, PropertyInfo pi) : base(ca)
 {
     this.RepresentPropertyInfo = pi;
 }
예제 #23
0
        // Performs one-time configuration of IIS/ARR.
        private static void ConfigureHTTPRedirectForARR(String httpRedirectEndPointName, IPEndPoint redirectBindInfo, IPEndPoint arrPublicEP)
        {
            using (ServerManager sm = new ServerManager())
            {
                Configuration        config = sm.GetApplicationHostConfiguration();
                ConfigurationSection rules  = config.GetSection("system.webServer/rewrite/rules");

                // Check if we already have a rewrite rule for this farm.
                bool ruleFound = rules.GetCollection().Any(e =>
                {
                    ConfigurationAttribute name = e.Attributes["name"];
                    return(name != null && name.Value.ToString().Equals(
                               httpRedirectEndPointName,
                               StringComparison.OrdinalIgnoreCase));
                });

                if (!ruleFound)
                {
                    int arrPublicPort = arrPublicEP.Port;

                    ConfigurationElement rule = rules.GetCollection().CreateElement("rule");
                    rule.SetAttributeValue("name", httpRedirectEndPointName);
                    rule.SetAttributeValue("stopProcessing", true);
                    rule.GetChildElement("match").SetAttributeValue("url", ".*");
                    rule.GetChildElement("action").SetAttributeValue("type", "Redirect");
                    if (arrPublicPort == 443)
                    {
                        rule.GetChildElement("action").SetAttributeValue("url", "https://{SERVER_NAME}{HTTP_URL}");
                    }
                    else
                    {
                        rule.GetChildElement("action").SetAttributeValue("url", "https://{SERVER_NAME}:" + arrPublicPort + "{HTTP_URL}");
                    }

                    /* rule.GetChildElement("action").SetAttributeValue(
                     *  "url",
                     *  string.Format(CultureInfo.InvariantCulture, @"https://{0}/{{R:0}}", "{HTTP_HOST}")); */

                    // Add conditions
                    var conditions = rule.GetChildElement("conditions");

                    var condition = conditions.GetCollection().CreateElement("add");
                    condition.SetAttributeValue("input", "{HTTPS}");
                    condition.SetAttributeValue("pattern", "OFF");
                    conditions.GetCollection().Add(condition);

                    rules.GetCollection().Add(rule);

                    // Ensure that the default app pool is set to classic mode.
                    Debug.Assert(sm.ApplicationPools["DefaultAppPool"] != null, "DefaultAppPool is not present");
                    sm.ApplicationPools["DefaultAppPool"].ManagedPipelineMode =
                        ManagedPipelineMode.Classic;

                    // Make sure that we have a binding in the default web site, which listens on ARR port for http redirect
                    Debug.Assert(sm.Sites["Default Web Site"] != null, "Default Web Site is not present");

                    BindingCollection bindingCollection = sm.Sites["Default Web Site"].Bindings;

                    Binding binding = sm.Sites["Default Web Site"].Bindings.CreateElement("binding");

                    binding["protocol"] = "http";

                    var bindingInformation = string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}:{1}:",
                        redirectBindInfo.Address.ToString(),
                        redirectBindInfo.Port);
                    binding["bindingInformation"] = bindingInformation;


                    bindingCollection.Add(binding);
                }

                sm.CommitChanges();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationObjectDefinition{TOptions}"/> class.
 /// </summary>
 /// <param name="attribute">The <see cref="ConfigurationAttribute"/>.</param>
 public ConfigurationObjectDefinition(ConfigurationAttribute attribute)
     : this(attribute.Section)
 {
     IsPerTenant = false;
 }
예제 #25
0
        /// <summary>
        /// Constrói a novo instancia do ConfigurationMap para o tipo submetido.
        /// Isso irá carrega as informações dos metados contidos no tipo para carregar
        /// o mapeamento do arquivo de configuração <see cref="ConfigurationAttribute"/>.
        /// </summary>
        /// <exception cref="GDA.GDAException"></exception>
        public ConfigurationMap(Type type)
        {
            List <MemberAttributeInfo> memberInfos = LoadMembersConfigurationAttributes(Helper.ReflectionFlags.InstanceCriteria, type);

            foreach (MemberAttributeInfo mai in memberInfos)
            {
                ConfigurationAttribute ca = mai.Attributes[0] as ConfigurationAttribute;
                switch (mai.MemberInfo.MemberType)
                {
                case MemberTypes.Method:
                    MethodTarget target = null;
                    if (instanceOverloads.ContainsKey(ca.XmlNodePath))
                    {
                        target = instanceOverloads[ca.XmlNodePath] as MethodTarget;
                    }
                    if (target != null)
                    {
                        target.AddCallbackMethod(mai.MemberInfo as MethodInfo, ca.RequiredParameters);
                    }
                    else
                    {
                        target = new MethodTarget(ca, mai.MemberInfo as MethodInfo);
                        instanceTargets.Add(target);
                        instanceOverloads[ca.XmlNodePath] = target;
                    }
                    break;

                case MemberTypes.Field:
                    instanceTargets.Add(new FieldTarget(ca, mai.MemberInfo as FieldInfo));
                    break;

                case MemberTypes.Property:
                    instanceTargets.Add(new PropertyTarget(ca, mai.MemberInfo as PropertyInfo));
                    break;

                default:
                    throw new GDAException("Unknown configuration target type for member {0} on class {1}.", mai.MemberInfo.Name, type);
                }
            }
            memberInfos = LoadMembersConfigurationAttributes(Helper.ReflectionFlags.StaticCriteria, type);
            foreach (MemberAttributeInfo mai in memberInfos)
            {
                ConfigurationAttribute ca = mai.Attributes[0] as ConfigurationAttribute;
                switch (mai.MemberInfo.MemberType)
                {
                case MemberTypes.Method:
                    MethodTarget target = null;
                    if (staticOverloads.ContainsKey(ca.XmlNodePath))
                    {
                        target = staticOverloads[ca.XmlNodePath] as MethodTarget;
                    }
                    if (target != null)
                    {
                        target.AddCallbackMethod(mai.MemberInfo as MethodInfo, ca.RequiredParameters);
                    }
                    else
                    {
                        target = new MethodTarget(ca, mai.MemberInfo as MethodInfo);
                        staticTargets.Add(target);
                        staticOverloads[ca.XmlNodePath] = target;
                    }
                    break;

                case MemberTypes.Field:
                    staticTargets.Add(new FieldTarget(ca, mai.MemberInfo as FieldInfo));
                    break;

                case MemberTypes.Property:
                    staticTargets.Add(new PropertyTarget(ca, mai.MemberInfo as PropertyInfo));
                    break;

                default:
                    throw new GDAException("Unknown configuration target type for member {0} on class {1}.", mai.MemberInfo.Name, type);
                }
            }
        }
예제 #26
0
    public ConfigurationAttribute Clone()
    {
        var clone = new ConfigurationAttribute(Name, Value, Description);

        return(clone);
    }
예제 #27
0
 /// <summary>
 /// Construtor.
 /// </summary>
 /// <param name="ca">Atributo de configuração para preecher o objeto.</param>
 public ElementTarget(ConfigurationAttribute ca)
 {
     this.XmlNodePath            = ca.XmlNodePath;
     this.KeyPresenceRequirement = ca.KeyPresenceRequirement;
 }
예제 #28
0
 /// <summary>
 /// Construtor padrão.
 /// </summary>
 /// <param name="ca"></param>
 /// <param name="fi"></param>
 public FieldTarget(ConfigurationAttribute ca, FieldInfo fi) : base(ca)
 {
     this.RepresentFieldInfo = fi;
 }
예제 #29
0
        /// <summary>
        /// Performs one-time configuration of IIS/ARR.
        /// </summary>
        private static void ConfigureOnce(string serverEndpointName, IPEndPoint bindInfo, string certHash, string certStoreName)
        {
            using (ServerManager sm = new ServerManager())
            {
                Configuration        config = sm.GetApplicationHostConfiguration();
                ConfigurationSection rules  = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationSection allowedServerVariables = config.GetSection("system.webServer/rewrite/allowedServerVariables");

                // Check if we already have a rewrite rule for this farm.
                bool ruleFound = rules.GetCollection().Any(e =>
                {
                    ConfigurationAttribute name = e.Attributes["name"];
                    return(name != null && name.Value.ToString().Equals(
                               serverEndpointName,
                               StringComparison.OrdinalIgnoreCase));
                });

                if (!ruleFound)
                {
                    ConfigurationElement rule = rules.GetCollection().CreateElement("rule");
                    rule.SetAttributeValue("name", serverEndpointName);
                    rule.SetAttributeValue("stopProcessing", true);
                    rule.GetChildElement("match").SetAttributeValue("url", ".*");
                    rule.GetChildElement("action").SetAttributeValue("type", "Rewrite");
                    rule.GetChildElement("action").SetAttributeValue(
                        "url",
                        string.Format(CultureInfo.InvariantCulture, @"http://{0}/{{R:0}}", serverEndpointName));

                    // Add conditions
                    var conditions = rule.GetChildElement("conditions");

                    var condition = conditions.GetCollection().CreateElement("add");
                    condition.SetAttributeValue("input", "{SERVER_PORT}");
                    condition.SetAttributeValue("pattern", bindInfo.Port);
                    conditions.GetCollection().Add(condition);

                    rules.GetCollection().Add(rule);

                    // Add server variables
                    if (certHash != null)
                    {
                        // Add server variables
                        var serverVariables = rule.GetChildElement("serverVariables");

                        var serverVariable = serverVariables.GetCollection().CreateElement("set");
                        serverVariable.SetAttributeValue("name", "HTTP_X_FORWARDED_PROTO");
                        serverVariable.SetAttributeValue("value", "https");
                        serverVariable.SetAttributeValue("replace", "false");
                        serverVariables.GetCollection().Add(serverVariable);

                        // Make an entry in allowed server variables
                        var allowedServerVariable = allowedServerVariables.GetCollection().CreateElement("add");
                        allowedServerVariable.SetAttributeValue("name", "HTTP_X_FORWARDED_PROTO");
                        allowedServerVariables.GetCollection().Add(allowedServerVariable);
                    }



                    // Ensure that the default app pool is set to classic mode.
                    Debug.Assert(sm.ApplicationPools["DefaultAppPool"] != null, "DefaultAppPool is not present");
                    sm.ApplicationPools["DefaultAppPool"].ManagedPipelineMode =
                        ManagedPipelineMode.Classic;

                    // Make sure that we have a binging in the default web site, which listens on ARR port.
                    Debug.Assert(sm.Sites["Default Web Site"] != null, "Default Web Site is not present");
                    foreach (Binding binding in sm.Sites["Default Web Site"].Bindings)
                    {
                        if (binding.Protocol.Equals("http", StringComparison.OrdinalIgnoreCase))
                        {
                            var bindingInformation = string.Format(
                                CultureInfo.InvariantCulture,
                                "{0}:{1}:",
                                bindInfo.Address.ToString(),
                                bindInfo.Port);

                            if (certHash != null)
                            {
                                byte[] certHashInbytes = getCertHashInbytes(certHash, certStoreName);
                                var    httpsBinding    = sm.Sites["Default Web Site"].Bindings.Add(bindingInformation, certHashInbytes, certStoreName);
                                httpsBinding.Protocol = "https";
                                sm.Sites["Default Web Site"].Bindings.Remove(binding);
                            }
                            else
                            {
                                binding["bindingInformation"] = bindingInformation;
                            }
                            break;
                        }
                    }
                }

                sm.CommitChanges();
            }
        }