public static ConfigurationSection GetInstance() { if (instance == null) { lock (typeof(ConfigurationSection)) { try { #pragma warning disable 618 instance = (ConfigurationSection)ConfigurationSettings.GetConfig("Platform/VirtualFileSystem/Multimedia/Configuration"); #pragma warning restore 618 } catch (Exception e) { throw e.InnerException; } if (instance == null) { instance = new ConfigurationSection(); } } } return instance; }
protected static ConfigurationSourceBaseImpl GetConfigurationSource() { var section = new ConfigurationSection( SectionName ); var source = new ConfigurationSourceBaseImpl {section}; section.Set( Key, Value ); return source; }
public void CanReadAddedValue() { var section = new ConfigurationSection( SectionName ); section.Set( Key, Value ); var value = section.Get<string>( "key" ); Assert.Equal( Value, value ); }
public void CanRemoveAddedValue() { var section = new ConfigurationSection( SectionName ); section.Set( Key, Value ); bool success = section.Remove( Key ); Assert.True( success ); }
protected void Page_Load( object sender, EventArgs e ) { AdminPopedom.IsHoldModel(string.Empty); config = WebConfigurationManager.OpenWebConfiguration( Request.ApplicationPath ); connnetStrings = config.GetSection( "connectionStrings" ); IsEncry = connnetStrings.SectionInformation.IsProtected; }
public IEnumerable<ConfigurationEntry> Parse(string data) { ConfigurationSection currentSection = null; foreach (var line in data.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) { var sectionMatch = _configurationSectionRegex.Match(line); if (sectionMatch.Success) { if (currentSection != null) yield return currentSection; currentSection = new ConfigurationSection { Type = sectionMatch.Groups["type"].Value, Name = sectionMatch.Groups["name"].Success ? sectionMatch.Groups["name"].Value : string.Empty }; continue; } var lineMatch = _configurationLineRegex.Match(line); if (lineMatch.Success) { var configLine = new ConfigurationLine { Name = lineMatch.Groups["name"].Value, Value = lineMatch.Groups["value"].Value }; if (currentSection != null) currentSection.Lines.Add(configLine); else yield return configLine; } } if (currentSection != null) yield return currentSection; }
public void Start(ConfigurationSection configuration) { _tokenDistributor = new System.Timers.Timer(); _tokenDistributor.Elapsed += new System.Timers.ElapsedEventHandler(TokenDistributor_Elapsed); _tokenDistributor.Interval = _interval; _tokenDistributor.AutoReset = true; _tokenDistributor.Enabled = true; }
public void CanGetAndSetEnumFlagValues() { const OptionsEnum all = ( OptionsEnum.A | OptionsEnum.B | OptionsEnum.C ); var section = new ConfigurationSection( SectionName ); section.Set( Key, all ); var fromSection = section.Get<OptionsEnum>( Key ); Assert.AreEqual( all, fromSection ); }
public void CanGetAndSetEnumValues() { const OSEnum value = OSEnum.Win2k; var section = new ConfigurationSection( SectionName ); section.Set( Key, value ); var fromSection = section.Get<OSEnum>( Key ); Assert.AreEqual( value, fromSection ); }
public void CanReadAddedValueWithTryGet() { var section = new ConfigurationSection( SectionName ); section.Set( Key, Value ); string value; bool found = section.TryGet( "key", out value ); Assert.True( found ); Assert.Equal( Value, value ); }
public static IConfigurationSection GetSingleSection() { IConfigurationSection section = new ConfigurationSection( "Default" ); section.Set( "a", "a" ); section.Set( "b", "b" ); section.Set( "c", "c" ); section.Set( "d", "d" ); section.Set( "e", "e" ); return section; }
public void MergingWithCollectionOverwritesExistingKeys() { ConfigurationSourceBaseImpl source = GetConfigurationSource(); var section = new ConfigurationSection( SectionName ); section.Set( Key, Key ); var source2 = new ConfigurationSourceBaseImpl {section}; Assert.Equal( Value, source.Sections[SectionName].Get<string>( Key ) ); source.Merge( new[] {source2} ); Assert.Equal( Key, source.Sections[SectionName].Get<string>( Key ) ); }
public void AddingNewSectionOverridesKeys() { ConfigurationSourceBaseImpl source = GetConfigurationSource(); var section = new ConfigurationSection( SectionName ); section.Set( Key, Key ); Assert.Equal( Value, source.Sections[SectionName].Get<string>( Key ) ); source.Add( section ); Assert.Equal( Key, source.Sections[SectionName].Get<string>( Key ) ); }
public void MergingWithCollectionAddsConfigurationSection() { ConfigurationSourceBaseImpl source = GetConfigurationSource(); const string sectionName = SectionName + Key; var section = new ConfigurationSection( sectionName ); section.Set( Key, Key ); var source2 = new ConfigurationSourceBaseImpl {section}; source.Merge( new[] {source2} ); Assert.Contains( section, source ); }
public static IEnumerable<IConfigurationSection> GetTwoSections() { IConfigurationSection section = new ConfigurationSection( "Default" ); section.Set( "a", "a" ); section.Set( "b", "b" ); IConfigurationSection section2 = new ConfigurationSection( "Default2" ); section2.Set( "c", "c" ); section2.Set( "d", "d" ); section2.Set( "e", "e" ); return new[] { section, section2 }; }
public void EnumeratorGivesKeysAndValues() { var section = new ConfigurationSection( SectionName ); section.Set( Key, Value ); int count = 0; foreach ( KeyValuePair<string, string> pair in section ) { Assert.Equal( Key, pair.Key ); Assert.Equal( Value, pair.Value ); count++; } Assert.Equal( 1, count ); }
public void Should_be_possible_get_a_valid_configuration_from_a_section_object() { MockRepository mocks = new MockRepository(); var fakeView = MockRepository.GenerateStub<IConfigurationView>(); var fakeController = mocks.DynamicMock<ConfigurationController>(new object[] { fakeView }); var fakeConfigurationSection = new ConfigurationSection(); fakeConfigurationSection.server.Address = "http://localhost"; fakeConfigurationSection.server.Port = "1024"; fakeConfigurationSection.server.Username = "******"; fakeConfigurationSection.server.Password = "******"; fakeConfigurationSection.target.Address = "10.0.0.1"; fakeConfigurationSection.target.Username = "******"; fakeConfigurationSection.target.Password = "******"; fakeConfigurationSection.target.AdministrativePassword = "******"; fakeConfigurationSection.file.SaveFolder = "C:\\Temp\\"; fakeConfigurationSection.file.DefinitionFilename = "C:\\Temp\\definitions.xml"; using (mocks.Record()) { Expect.Call(fakeController.FileExists(null)).IgnoreArguments().Return(true); Expect.Call(fakeController.ReadConfigurationSection(null)).IgnoreArguments().Return(fakeConfigurationSection); } mocks.ReplayAll(); fakeController.view_OnReadConfiguration(this, EventArgs.Empty); mocks.VerifyAll(); Assert.IsNotNull(fakeView.Server); Assert.AreEqual("http://localhost", fakeView.Server.Address); Assert.AreEqual("1024", fakeView.Server.Port); Assert.AreEqual("admin", fakeView.Server.Username); Assert.AreEqual("PassworD", fakeView.Server.Password); Assert.IsNotNull(fakeView.Target); Assert.AreEqual("10.0.0.1", fakeView.Target.Address); Assert.AreEqual("administrator", fakeView.Target.Username); Assert.AreEqual("P@asswOrd", fakeView.Target.Password); Assert.AreEqual("qwerty", fakeView.Target.AdministrativePassword); Assert.IsNotNull(fakeView.DestinationFolder); Assert.AreEqual("C:\\Temp\\", fakeView.DestinationFolder); Assert.IsNotNull(fakeView.DefinitionFilename); Assert.AreEqual("C:\\Temp\\definitions.xml", fakeView.DefinitionFilename); }
public static ConfigurationSection GetInstance() { try { if (instance == null) { instance = (ConfigurationSection)ConfigurationManager.GetSection("searchEngineConfiguration"); } return instance; } catch (Exception ex) { throw ex; } }
public override bool TryGetSubSection(string key, out ConfigurationSection sect) { if (ParentConfig == null) { throw new InvalidOperationException(); } string res; if (TryGetValue(key, out res)) { sect = ParentConfig[res]; return true; } sect = null; return false; }
public DiskBackupManager(ConfigurationSection configSection, string partitionId, long keymin, long keymax, string codePackageTempDirectory) { this.keyMin = keymin; this.keyMax = keymax; string BackupArchivalPath = configSection.Parameters["BackupArchivalPath"].Value; this.backupFrequencyInSeconds = long.Parse(configSection.Parameters["BackupFrequencyInSeconds"].Value); this.MaxBackupsToKeep = int.Parse(configSection.Parameters["MaxBackupsToKeep"].Value); this.PartitionArchiveFolder = Path.Combine(BackupArchivalPath, "Backups", partitionId); this.PartitionTempDirectory = Path.Combine(codePackageTempDirectory, partitionId); ServiceEventSource.Current.Message( "DiskBackupManager constructed IntervalinSec:{0}, archivePath:{1}, tempPath:{2}, backupsToKeep:{3}", this.backupFrequencyInSeconds, this.PartitionArchiveFolder, this.PartitionTempDirectory, this.MaxBackupsToKeep); }
public AzureBlobBackupManager(ConfigurationSection configSection, string partitionId, long keymin, long keymax, string codePackageTempDirectory) { this.keyMin = keymin; this.keyMax = keymax; string backupAccountName = configSection.Parameters["BackupAccountName"].Value; string backupAccountKey = configSection.Parameters["PrimaryKeyForBackupTestAccount"].Value; string blobEndpointAddress = configSection.Parameters["BlobServiceEndpointAddress"].Value; this.backupFrequencyInSeconds = long.Parse(configSection.Parameters["BackupFrequencyInSeconds"].Value); this.MaxBackupsToKeep = int.Parse(configSection.Parameters["MaxBackupsToKeep"].Value); this.partitionId = partitionId; this.PartitionTempDirectory = Path.Combine(codePackageTempDirectory, partitionId); StorageCredentials storageCredentials = new StorageCredentials(backupAccountName, backupAccountKey); this.cloudBlobClient = new CloudBlobClient(new Uri(blobEndpointAddress), storageCredentials); this.backupBlobContainer = this.cloudBlobClient.GetContainerReference(this.partitionId); this.backupBlobContainer.CreateIfNotExists(); }
/// <summary> /// Gets the configuration section /// </summary> /// <returns></returns> public static ConfigurationSection GetSection() { if (instance == null) { if (ConfigurationManager.AppSettings["facebookSharpSectionOverride"] == null) { instance = (ConfigurationSection)ConfigurationManager.GetSection("facebookSharp"); } else { instance = (ConfigurationSection)ConfigurationManager.GetSection(ConfigurationManager.AppSettings["facebookSharpSectionOverride"]); } if (instance == null) { throw new InvalidOperationException("This operation requires a FacebookSharp configuration section; please make sure your site is fully configured before using this functionality."); } } return instance; }
public void Parse(ConfigurationSection sect) { float lng = sect.GetSingle("Longitude"); float lat = sect.GetSingle("Latitude"); lng = MathEx.Degree2Radian(lng); lat = MathEx.Degree2Radian(lat); float alt = TerrainData.Instance.QueryHeight(lng, lat); position = PlanetEarth.GetPosition(lng, lat); radius = sect.GetSingle("Radius"); radius = PlanetEarth.GetTileHeight(MathEx.Degree2Radian(radius)); string sfxName = sect["SFX"]; sound = SoundManager.Instance.MakeSoundObjcet(sfxName, null, radius); sound.Position = position; //probability = sect.GetSingle("Probability", 1); }
public MapCity(SimulationWorld world, ConfigurationSection sect) { City city = new City(world); city.Parse(sect); LinkableCity = city.LinkableCityName; FarmCount = city.FarmLandCount; ProblemEnvironment = city.ProblemEnvironment; ProblemEducation = city.ProblemEducation; ProblemDisease = city.ProblemDisease; ProblemChild = city.ProblemChild; ProblemGender = city.ProblemGender; ProblemHunger = city.ProblemHunger; ProblemMaternal = city.ProblemMaternal; Name = city.Name; Size = city.Size; Longitude = city.Longitude; Latitude = city.Latitude; StartUp = city.StartUp; }
/// <summary> /// Returns a collection of facts that belong to the specified configuration section. /// </summary> /// <param name="configSection">The <see cref="System.Configuration.ConfigurationSection"/> object containing the configuration section.</param> /// <returns>A collection of section-specific facts.</returns> public static object[] GetFacts(ConfigurationSection configSection) { Guard.ArgumentNotNull(configSection, "configSection"); List <object> facts = new List <object>(); facts.Add(configSection); if (configSection is ConnectionStringsSection) { ConnectionStringsSection connectionStringConfig = configSection as ConnectionStringsSection; facts.Add(connectionStringConfig.ConnectionStrings); facts.Add(new ConnectionStringView(connectionStringConfig)); } else if (configSection is ServiceBusConfigurationSettings) { facts.Add((configSection as ServiceBusConfigurationSettings).Endpoints); } else if (configSection is XPathQueryLibrary) { XPathQueryLibrary xPathLib = configSection as XPathQueryLibrary; facts.Add(xPathLib.Namespaces); facts.Add(xPathLib.Queries); } else if (configSection is LoggingSettings) { facts.Add(new LoggingConfigurationView(configSection as LoggingSettings)); } else if (configSection is CacheManagerSettings) { facts.Add(new CachingConfigurationView(configSection as CacheManagerSettings)); } return(facts.ToArray()); }
public override bool OverrideWithGroupPoliciesAndGenerateWmiObjects(ConfigurationSection configurationObject, bool readGroupPolicies, IRegistryKey machineKey, IRegistryKey userKey, bool generateWmiObjects, ICollection <ConfigurationSetting> wmiSettings) { called = true; this.configurationObject = configurationObject; this.readGroupPolicies = readGroupPolicies; this.machineKey = machineKey; this.userKey = userKey; this.generateWmiObjects = generateWmiObjects; IRegistryKey policyKey = GetPolicyKey(machineKey, userKey); if (policyKey != null) { if (!policyKey.GetBoolValue(PolicyValueName).Value) { return(false); } TestsConfigurationSection section = configurationObject as TestsConfigurationSection; if (section != null) { try { section.Value = policyKey.GetStringValue(ValuePropertyName); } catch (RegistryAccessException) { } } } if (generateWmiObjects) { TestConfigurationSettings setting = new TestConfigurationSettings(configurationObject.ToString()); setting.SourceElement = configurationObject; wmiSettings.Add(setting); } return(true); }
public bool RemoveJob(string name) { try { if (string.IsNullOrWhiteSpace(name)) { Time2RunSrv.WriteLog("管理端:【Manager】移除任务[" + name + "]失败:" + "未发现有效的任务名称!"); return(false); } lock (typeof(Time2RunSrv)) { Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection sec = conf.GetSection("JackTime2RunJobs"); string str = sec.SectionInformation.GetRawXml(); XmlDocument doc = new XmlDocument(); doc.LoadXml(str); List <XmlElement> jobs = doc.ChildNodes.OfType <XmlElement>().FirstOrDefault <XmlElement>().ChildNodes.OfType <XmlElement>().Where <XmlElement>((i) => i.Name == "job").ToList <XmlElement>(); for (int i = 0; i < jobs.Count; i++) { if (jobs[i].Attributes["name"].Value == name) { jobs[i].ParentNode.RemoveChild(jobs[i]); break; } } sec.SectionInformation.SetRawXml(doc.InnerXml); conf.Save(ConfigurationSaveMode.Modified); Host._srv.ReloadConf(); return(true); } } catch (Exception ex) { Time2RunSrv.WriteLog("管理端:【Manager】移除任务[" + name + "]失败:" + ex.ToString()); return(false); } }
public void Should_be_possible_get_a_valid_file_configuration_from_a_section_object() { MockRepository mocks = new MockRepository(); var fakeView = MockRepository.GenerateStub <IConfigurationView>(); var fakeController = mocks.DynamicMock <ConfigurationController>(new object[] { fakeView }); var fakeConfigurationSection = new ConfigurationSection(); fakeConfigurationSection.file.SaveFolder = "C:\\Temp\\"; fakeConfigurationSection.file.DefinitionFilename = "C:\\Temp\\definitions.xml"; using (mocks.Record()) { Expect.Call(fakeController.FileExists(null)).IgnoreArguments().Return(true); Expect.Call(fakeController.ReadConfigurationSection(null)).IgnoreArguments().Return(fakeConfigurationSection); } mocks.ReplayAll(); fakeController.view_OnReadConfiguration(this, EventArgs.Empty); mocks.VerifyAll(); Assert.AreEqual(String.Empty, fakeView.Server.Address); Assert.AreEqual(String.Empty, fakeView.Server.Port); Assert.AreEqual(String.Empty, fakeView.Server.Username); Assert.AreEqual(String.Empty, fakeView.Server.Password); Assert.AreEqual(String.Empty, fakeView.Target.Address); Assert.AreEqual(String.Empty, fakeView.Target.Username); Assert.AreEqual(String.Empty, fakeView.Target.Password); Assert.AreEqual(String.Empty, fakeView.Target.AdministrativePassword); Assert.AreEqual("C:\\Temp\\", fakeView.DestinationFolder); Assert.AreEqual("C:\\Temp\\definitions.xml", fakeView.DefinitionFilename); }
/// <summary> /// Sets the section name in the first valid alternative configuration file to the value contained /// in the section. /// </summary> /// <param name="section"></param> internal static void SetConfigurationSectionFromAltConfig(ConfigurationSection section) { Exception lastException = null; foreach (string file in Constants.ConfigFileNames) { try { string configFileName = GetFilePath(file); // Checking for the existence of the configured alternate config file if (File.Exists(configFileName)) { // Load the alternate configuration file using the configuration file map definition. System.Configuration.Configuration fiftyOneConfig = OpenConfigFileMap(configFileName); // If alternate configuration file loaded successfully go ahead and retrieve requested // confguration section. if (fiftyOneConfig != null && fiftyOneConfig.HasFile == true && SetConfigurationSection(section, fiftyOneConfig)) { return; } } } catch (SecurityException ex) { // Ignore as could be because file permissions are denied. Move // to the next file. lastException = ex; } } throw new MobileException(String.Format( "Could not set section with name '{0}' in any configuration files.", section.SectionInformation.SectionName), lastException); }
private void UpdateConfiguration(String configSource) { lock (configurationUpdateLock) { ConfigurationInstanceConfigurationAccessor updatedConfigurationAccessor = new ConfigurationInstanceConfigurationAccessor(ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)); manageabilityHelper.UpdateConfigurationManageability(updatedConfigurationAccessor); List <String> sectionsToNotify = new List <String>(); bool notifyAll = ConfigurationChangeWatcherCoordinator.MainConfigurationFileSource.Equals(configSource); foreach (String sectionName in currentConfigurationAccessor.GetRequestedSectionNames()) { ConfigurationSection currentSection = currentConfigurationAccessor.GetSection(sectionName); ConfigurationSection updatedSection = updatedConfigurationAccessor.GetSection(sectionName); if (currentSection != null || updatedSection != null) { UpdateWatchers(currentSection, updatedSection); // notify if: // - instructed to notify all // - any of the versions is null, or its config source matches the changed source if (notifyAll || (updatedSection == null || configSource.Equals(updatedSection.SectionInformation.ConfigSource)) || (currentSection == null || configSource.Equals(currentSection.SectionInformation.ConfigSource))) { sectionsToNotify.Add(sectionName); } } } currentConfigurationAccessor = updatedConfigurationAccessor; notificationCoordinator.NotifyUpdatedSections(sectionsToNotify); } }
public ConfigManager(Configuration config) { // Find all trace sources (These are probes) ConfigurationSection diagnosticsSection = config.GetSection("system.diagnostics"); ConfigurationElementCollection tracesources = diagnosticsSection.ElementInformation.Properties["sources"].Value as ConfigurationElementCollection; List <ConfigItem> probeList = new List <ConfigItem>(); foreach (ConfigurationElement tracesource in tracesources) { string name = tracesource.ElementInformation.Properties["name"].Value.ToString(); if (name.IndexOf('.') != -1) { ConfigItem configItem = new ConfigItem(); configItem.Name = name.Substring(0, name.IndexOf('.')); configItem.Type = name.Substring(name.IndexOf('.') + 1); probeList.Add(configItem); } } ProbeList = probeList; // Find all shared listeners List <ConfigItem> listenerList = new List <ConfigItem>(); ConfigurationElementCollection traceListeners = diagnosticsSection.ElementInformation.Properties["sharedListeners"].Value as ConfigurationElementCollection; foreach (ConfigurationElement listener in traceListeners) { ConfigItem configItem = new ConfigItem(); configItem.Name = listener.ElementInformation.Properties["name"].Value.ToString(); configItem.Type = listener.ElementInformation.Properties["type"].Value.ToString(); listenerList.Add(configItem); } ListenerList = listenerList; }
public object Create(object parent, object configContext, XmlNode section) { object retVal = GetConfigInstance(section); try { System.Configuration.Configuration config = null; //if the app is hosted you should be able to load a web.config. if (System.Web.Hosting.HostingEnvironment.IsHosted) { config = WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath); } else { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } //TODO: figure out how to get Configuration in a service //SectionInformation info = config.GetSection(section.Name).SectionInformation; ConfigurationSection configSection = config.GetSection(section.Name); if (configSection.SectionInformation.RestartOnExternalChanges == false) { SetupWatcher(config, configSection, retVal); } } //if an exception occurs here we simply have no watcher and the app pool must be reset in order to recognize config changes catch (Exception exc) { string Message = "Exception setting up FileSystemWatcher for Section = " + (section != null ? section.Name : "Unknown Section"); if (log.IsErrorEnabled) { log.Error(Message, exc); } } return(retVal); }
public static void EncryptWebConfigSection(String section_name, String web_config_dir, bool encrypt) { Configuration c = WebConfigurationManager.OpenWebConfiguration(web_config_dir); ConfigurationSection cs = c.GetSection(section_name); if (cs != null) { if (encrypt && !cs.SectionInformation.IsProtected) { cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); c.Save(); } else if (!encrypt && cs.SectionInformation.IsProtected) { cs.SectionInformation.UnprotectSection(); c.Save(); } } else { throw new Exception("Web.Config section '" + HttpContext.Current.Server.HtmlEncode(section_name) + "' does not exist or is not accessible. " + "Ensure that the specified configsection address is fully qualified and that you are encrypting a lowest child section."); } }
public MapCity(SimulationWorld world, ConfigurationSection sect) { City city = new City(world); city.Parse(sect); LinkableCity = city.LinkableCityName; FarmCount = city.FarmLandCount; ProblemEnvironment = city.ProblemEnvironment; ProblemEducation = city.ProblemEducation; ProblemDisease = city.ProblemDisease; ProblemChild = city.ProblemChild; ProblemGender = city.ProblemGender; ProblemHunger = city.ProblemHunger; ProblemMaternal = city.ProblemMaternal; Name = city.Name; Size = city.Size; Longitude = city.Longitude; Latitude = city.Latitude; StartUp = city.StartUp; }
internal static object SectionToJsonModel(ConfigurationSection section, Site site, string path, string configScope) { if (section == null) { return(null); } // configScope = configScope != null ? configScope : (site == null ? "" : $"{site.Name}{path}"); SectionId id = new SectionId(site?.Id, path, section.SectionPath.Replace($"{XPATH}/", string.Empty), configScope); var obj = new { name = section.SectionPath, id = id.Uuid, scope = site == null ? string.Empty : site.Name + path, config_scope = configScope, override_mode = Enum.GetName(typeof(OverrideMode), section.OverrideMode).ToLower(), override_mode_effective = Enum.GetName(typeof(OverrideMode), section.OverrideModeEffective).ToLower(), website = SiteHelper.ToJsonModelRef(site) }; return(Core.Environment.Hal.Apply(Defines.Resource.Guid, obj)); }
private void LoadConfiguration() { // Get the Health Check Interval configuration value. ConfigurationPackage pkg = Context.CodePackageActivationContext.GetConfigurationPackageObject("Config"); if (null != pkg) { if (true == pkg.Settings?.Sections?.Contains("Health")) { ConfigurationSection settings = pkg.Settings.Sections["Health"]; if (true == settings?.Parameters.Contains("HealthCheckIntervalSeconds")) { long lValue = 0; ConfigurationProperty prop = settings.Parameters["HealthCheckIntervalSeconds"]; if (long.TryParse(prop?.Value, out lValue)) { _interval = TimeSpan.FromSeconds(Math.Max(30, lValue)); _healthTimer?.Dispose(); _healthTimer = new Timer(ReportHealthAndLoad, null, _interval, _interval); } } } } }
private void updateIisRedirect(Website website, Configuration configuration) { ConfigurationSection cs = configuration.GetSection("system.webServer/httpRedirect"); if (website.IisSite.Mode == WebsiteIisMode.Redirect) { cs.SetAttributeValue("enabled", true); cs.SetAttributeValue("destination", website.IisSite.RedirectUrl); // For now, make these static, but they may need to be dynamic in future. cs.SetAttributeValue("exactDestination", true); cs.SetAttributeValue("childOnly", false); cs.SetAttributeValue("httpResponseStatus", 301); } else { // Only disable if currently enabled. if ((bool)cs.GetAttributeValue("enabled")) { // Enable, which creates web.config file. cs.SetAttributeValue("enabled", false); } } }
private static void Main() { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetApplicationHostConfiguration(); // Retrieve the sites collection. ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites"); ConfigurationElementCollection sitesCollection = sitesSection.GetCollection(); // Locate a specific site. ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", @"mySite"); if (siteElement == null) { throw new InvalidOperationException("Element not found!"); } // Create an object for the ftpServer element. ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer"); // Create an instance of the FlushLog method. ConfigurationMethodInstance FlushLog = ftpServerElement.Methods["FlushLog"].CreateInstance(); // Execute the method to flush the logs for the FTP site. FlushLog.Execute(); } }
/// <summary> /// 更改section内容 /// </summary> /// <param name="section">自定义节名</param> /// <param name="AppKey">键名</param> /// <param name="AppValue">键值</param> public static string GetAppSettings(string SectionName, string SettingName) { string value = string.Empty; System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); ConfigurationSectionCollection sections = config.Sections; ConfigurationSection section = sections.Get(SectionName); if (section != null) { value = section.SectionInformation.SectionName; } //foreach (string key in sections.Keys) //{ // Console.WriteLine( // "Key value: {0}", key); //} return(value); }
#pragma warning disable 618 // service needs to run on V2.1 cluster, so use obsolete API // CodePackageActivationContext.GetConfigurationPackage internal static T GetConfigValue <T>(string sectionName, string parameterName, T defaultValue) { T value = defaultValue; ConfigurationPackageDescription configPackageDesc = codePkgActivationCtx.GetConfigurationPackage(ConfigPackageName); if (null != configPackageDesc) { ConfigurationSettings configSettings = configPackageDesc.Settings; if (null != configSettings && null != configSettings.Sections && configSettings.Sections.Contains(sectionName)) { ConfigurationSection section = configSettings.Sections[sectionName]; if (null != section.Parameters && section.Parameters.Contains(parameterName)) { ConfigurationProperty property = section.Parameters[parameterName]; try { value = (T)Convert.ChangeType(property.Value, typeof(T), CultureInfo.InvariantCulture); } catch (Exception e) { serviceTrace.Error( "ConfigReader.GetConfigValue: Exception occurred while reading configuration from section {0}, parameter {1}. Exception: {2}", sectionName, parameterName, e); } } } } return(value); }
private void SetupBackupManager() { string partitionId = this.Context.PartitionId.ToString("N"); long minKey = ((Int64RangePartitionInformation)this.Partition.PartitionInfo).LowKey; long maxKey = ((Int64RangePartitionInformation)this.Partition.PartitionInfo).HighKey; if (this.Context.CodePackageActivationContext != null) { ICodePackageActivationContext codePackageContext = this.Context.CodePackageActivationContext; ConfigurationPackage configPackage = codePackageContext.GetConfigurationPackageObject("Config"); ConfigurationSection configSection = configPackage.Settings.Sections["Stateful1.Settings"]; string backupSettingValue = configSection.Parameters["BackupMode"].Value; if (string.Equals(backupSettingValue, "none", StringComparison.InvariantCultureIgnoreCase)) { this.backupStorageType = BackupManagerType.None; } else if (string.Equals(backupSettingValue, "azure", StringComparison.InvariantCultureIgnoreCase)) { this.backupStorageType = BackupManagerType.Azure; ConfigurationSection azureBackupConfigSection = configPackage.Settings.Sections["Stateful1.BackupSettings.Azure"]; this.backupManager = new AzureBlobBackupManager(azureBackupConfigSection, partitionId, minKey, maxKey, codePackageContext.TempDirectory); } else { throw new ArgumentException("Unknown backup type"); } ServiceEventSource.Current.ServiceMessage(this, "Backup Manager Set Up"); } }
private static bool IsSectionValid(ConfigurationSection section, bool sectionShouldBeEncrypted) { if (section == null) { return(false); } var sectionIsEncrypted = section.SectionInformation.IsProtected; var sectionShouldBeDecrypted = !sectionShouldBeEncrypted; var sectionIsDecrypted = !sectionIsEncrypted; if ((sectionShouldBeEncrypted && sectionIsEncrypted) || (sectionShouldBeDecrypted && sectionIsDecrypted)) { return(false); } if (section.ElementInformation.IsLocked) { throw new InvalidOperationException($"{section.SectionInformation.Name} is locked!"); } return(true); }
public static GlobalConfig GetExtNetSection(ISite site) { if (site != null) { IWebApplication app = (IWebApplication)site.GetService(typeof(IWebApplication)); if (app != null) { Configuration config = app.OpenWebConfiguration(false); if (config != null) { ConfigurationSection section = config.GetSection("extnet"); if (section != null) { return(section as GlobalConfig); } } } } return(null); }
static void Main(string[] args) { try { System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection connStrings = config.ConnectionStrings; ConnectionStringSettings cssc = ((ConnectionStringsSection)connStrings).ConnectionStrings["LocalSqlServer"]; Console.WriteLine("connStrings[LocalSqlServer] = {0}", (cssc == null ? "null" : cssc.ConnectionString)); ConnectionStringSettings cssc2 = ((ConnectionStringsSection)connStrings).ConnectionStrings["AccessFileName"]; Console.WriteLine("connStrings[AccessFileName] = {0}", (cssc2 == null ? "null" : cssc2.ConnectionString)); AppSettingsSection sect = (AppSettingsSection)config.AppSettings; Console.WriteLine("sect.Settings[hithere] = {0}", (sect.Settings ["hithere"] == null ? "null" : sect.Settings ["hithere"].Value.ToString())); RsaProtectedConfigurationProvider rsa = (RsaProtectedConfigurationProvider)ProtectedConfiguration.Providers [ProtectedConfiguration.DefaultProvider]; Console.WriteLine("rsa = {0}", (rsa == null ? "null" : rsa.ToString())); } catch (Exception e) { Console.WriteLine("{0} raised", e.GetType()); Console.WriteLine(e.Message); } }
/// <summary> /// Funzione per criptare le sezioni del file di configurazione che contengono dati sensibili. /// </summary> /// <param name="sections">Lista di sezioni da criptare.</param> public static void CryptSection(params string[] sections) { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string provider = "RsaProtectedConfigurationProvider"; foreach (string sectionName in sections) { ConfigurationSection section = config.GetSection(sectionName); if (section != null) { if (!section.SectionInformation.IsProtected) { if (!section.ElementInformation.IsLocked) { section.SectionInformation.ProtectSection(provider); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); } } } } }
public static ConfigurationSection GetConfigSection(long?siteId, string path, string sectionPath, Type sectionType, string configPath = null) { if (string.IsNullOrEmpty(sectionPath)) { throw new ArgumentNullException("sectionPath"); } if (siteId != null && path == null) { throw new ArgumentNullException("path"); } ConfigurationSection section = null; try { ScopedConfiguration sConfig = GetScopedConfig(siteId, path, configPath); section = sConfig.Location == null? sConfig.Configuration.GetSection(sectionPath, sectionType) : sConfig.Configuration.GetSection(sectionPath, sectionType, sConfig.Location); } catch (FileLoadException e) { throw new LockedException(sectionPath, e); } catch (DirectoryNotFoundException e) { throw new ConfigScopeNotFoundException(e); } catch (ArgumentException e) { if (configPath != null) { throw new ApiArgumentException(CONFIG_SCOPE_KEY, e); } throw; } return(section); }
private static void Main() { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetAdministrationConfiguration(); ConfigurationSection authorizationSection = config.GetSection("system.webServer/management/authorization"); ConfigurationElementCollection authorizationRulesCollection = authorizationSection.GetCollection("authorizationRules"); ConfigurationElement scopeElement = FindElement(authorizationRulesCollection, "scope", "path", @"/Default Web Site"); if (scopeElement == null) { scopeElement = authorizationRulesCollection.CreateElement("scope"); scopeElement["path"] = @"/Default Web Site"; authorizationRulesCollection.Add(scopeElement); } ConfigurationElementCollection scopeCollection = scopeElement.GetCollection(); ConfigurationElement addElement = scopeCollection.CreateElement("add"); addElement["name"] = @"ContosoUser"; scopeCollection.Add(addElement); serverManager.CommitChanges(); } }
/// <summary> /// !Caller holds config_load_lock /// </summary> /// <param name="trinity_config_file"></param> private static void LoadConfigLegacy(string trinity_config_file) { XMLConfig xml_config = new XMLConfig(trinity_config_file); //construct local configuration section XElement localSection = new XElement(ConfigurationConstants.Tags.LOCAL); XElement loggingEntry = new XElement(ConfigurationConstants.Tags.LOGGING); XElement storageEntry = new XElement(ConfigurationConstants.Tags.STORAGE); XElement networkEntry = new XElement(ConfigurationConstants.Tags.NETWORK); loggingEntry.SetAttributeValue(ConfigurationConstants.Attrs.LOGGING_DIRECTORY, xml_config.GetEntryValue(ConfigurationConstants.Tags.LOGGING.LocalName, ConfigurationConstants.Attrs.LOGGING_DIRECTORY)); loggingEntry.SetAttributeValue(ConfigurationConstants.Attrs.LOGGING_LEVEL, xml_config.GetEntryValue(ConfigurationConstants.Tags.LOGGING.LocalName, ConfigurationConstants.Attrs.LOGGING_LEVEL)); storageEntry.SetAttributeValue(ConfigurationConstants.Attrs.STORAGE_ROOT, xml_config.GetEntryValue(ConfigurationConstants.Tags.STORAGE.LocalName, ConfigurationConstants.Attrs.STORAGE_ROOT)); networkEntry.SetAttributeValue(ConfigurationConstants.Attrs.HTTP_PORT, xml_config.GetEntryValue(ConfigurationConstants.Tags.NETWORK.LocalName, ConfigurationConstants.Attrs.HTTP_PORT)); networkEntry.SetAttributeValue(ConfigurationConstants.Attrs.CLIENT_MAX_CONN, xml_config.GetEntryValue(ConfigurationConstants.Tags.NETWORK.LocalName, ConfigurationConstants.Attrs.CLIENT_MAX_CONN)); if (loggingEntry.Attributes().Count() > 0) { localSection.Add(loggingEntry); } if (storageEntry.Attributes().Count() > 0) { localSection.Add(storageEntry); } if (networkEntry.Attributes().Count() > 0) { localSection.Add(networkEntry); } //construct local ConfigurationSection s_localConfigurationSection = new ConfigurationSection(localSection); //construct a clusterSections s_current_cluster_config = ClusterConfig._LegacyLoadClusterConfig(trinity_config_file); s_clusterConfigurations.Add(ConfigurationConstants.Values.DEFAULT_CLUSTER, s_current_cluster_config); }
/// <summary> /// Checks whether a call to <see cref="IConfigurationSource.Add(string, ConfigurationSection)"/> should be extended.<br/> /// If the call should be extended performs the extended behavior. /// </summary> /// <param name="sectionName">The name of the section that should be stored in configuration.</param> /// <param name="configurationSection">The section that should be stored in configuration.</param> /// <returns><see langword="true"/> if the call to <see cref="IConfigurationSource.Add(string, ConfigurationSection)"/> was handled by the extension.</returns> /// <seealso cref="IConfigurationSource.Add(string, ConfigurationSection)"/> public bool CheckAddSection(string sectionName, ConfigurationSection configurationSection) { //if we are adding, we should return. if (RecursionLock.InsideHandlerOperation) { return(false); } //this is a section we depend on internally if (sectionName == ConfigurationSourceSection.SectionName) { return(false); } lock (LockObject) { using (new RecursionLock()) { EnsureInitialized(); return(DoCheckAddSection(sectionName, configurationSection)); } } }
private bool DecryptionSection(string sectionName, out string msgErr) { msgErr = string.Empty; try { System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = config.GetSection(sectionName); if (section != null && section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); config.Save(); return(true); } else { return(false); } } catch (Exception ex) { msgErr = ex.Message; } return(false); }
private void SetWindowsAuthenticationProviders() { if (!this.SiteExists()) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The website: {0} was not found on: {1}", this.Name, this.MachineName)); return; } if (string.IsNullOrWhiteSpace(this.Providers)) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "No authentication providers were specified for website {0} on {1}", this.Name, this.MachineName)); return; } string[] providers = this.Providers.Trim().Split(new[] { ';' }); Configuration config = this.iisServerManager.GetApplicationHostConfiguration(); ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", this.Name); ConfigurationElementCollection providersCollection = windowsAuthenticationSection.GetCollection("providers"); for (int index = providersCollection.Count - 1; index >= 0; index--) { var existingProvider = providersCollection[index]; if (!providers.Contains(existingProvider["value"])) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Removing provider {0}", existingProvider["value"])); providersCollection.Remove(existingProvider); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Keeping provider {0}", existingProvider["value"])); } } windowsAuthenticationSection["useKernelMode"] = this.UseKernelMode; this.iisServerManager.CommitChanges(); }
private void ReadSettings() { // Read settings from the DeviceActorServiceConfig section in the Settings.xml file ICodePackageActivationContext activationContext = this.Context.CodePackageActivationContext; ConfigurationPackage config = activationContext.GetConfigurationPackageObject(ConfigurationPackage); ConfigurationSection section = config.Settings.Sections[ConfigurationSection]; // Read the MaxRetryCount setting from the Settings.xml file this.maxRetryCount = DefaultMaxRetryCount; ConfigurationProperty parameter = section.Parameters[MaxQueryRetryCountParameter]; if (!string.IsNullOrWhiteSpace(parameter?.Value)) { int.TryParse(parameter.Value, out this.maxRetryCount); } // Read the BackoffDelay setting from the Settings.xml file this.backoffDelay = DefaultBackoffDelay; parameter = section.Parameters[BackoffDelayParameter]; if (!string.IsNullOrWhiteSpace(parameter?.Value)) { int.TryParse(parameter.Value, out this.backoffDelay); } }
public override ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection) { // Expand mode works on the raw string input if (Mode == KeyValueMode.Expand) { return(configSection); } // In Greedy mode, we need to know all the key/value pairs from this config source. So we // can't 'cache' them as we go along. Slurp them all up now. But only once. ;) if ((Mode == KeyValueMode.Greedy) && (!_greedyInited)) { lock (_cachedValues) { if (!_greedyInited) { foreach (KeyValuePair <string, string> kvp in GetAllValuesInternal(KeyPrefix)) { _cachedValues.Add(kvp); } _greedyInited = true; } } } if (configSection is AppSettingsSection) { return(ProcessAppSettings((AppSettingsSection)configSection)); } else if (configSection is ConnectionStringsSection) { return(ProcessConnectionStrings((ConnectionStringsSection)configSection)); } return(configSection); }
private static void Main() { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection iisClientCertificateMappingAuthenticationSection = config.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", "Default Web Site"); iisClientCertificateMappingAuthenticationSection["enabled"] = true; iisClientCertificateMappingAuthenticationSection["oneToOneCertificateMappingsEnabled"] = true; ConfigurationElementCollection oneToOneMappingsCollection = iisClientCertificateMappingAuthenticationSection.GetCollection("oneToOneMappings"); ConfigurationElement addElement = oneToOneMappingsCollection.CreateElement("add"); addElement["enabled"] = true; addElement["userName"] = @"Username"; addElement["password"] = @"Password"; addElement["certificate"] = @"Base-64-Encoded-Certificate-Data"; oneToOneMappingsCollection.Add(addElement); ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", "Default Web Site"); accessSection["sslFlags"] = @"Ssl, SslNegotiateCert"; serverManager.CommitChanges(); } }
public void Start(ConfigurationSection configuration) { }
private IConfigurationSection GetSection( string sectionData ) { IConfigurationSection section = new ConfigurationSection( "Temp" ); string[] lines = sectionData.Split( new[] { Environment.NewLine }, StringSplitOptions.None ); foreach ( string line in lines ) { string workingLine = line; if ( line.Contains( Comment ) ) { workingLine = line.Substring( 0, line.IndexOf( Comment, StringComparison.OrdinalIgnoreCase ) ); } if ( workingLine.StartsWith( "[", StringComparison.OrdinalIgnoreCase ) && workingLine.EndsWith( "]", StringComparison.OrdinalIgnoreCase ) ) { string sectionName = workingLine.Substring( 1, workingLine.Length - 2 ).Trim(); if ( string.IsNullOrEmpty( sectionName ) ) { throw new InvalidOperationException( Text.NoEmptySectionNames ); } section.Name = sectionName; continue; } string[] pair = workingLine.Split( new[] { Delimiter }, StringSplitOptions.None ); if ( pair.Length != 2 ) { continue; } string key = pair[0].Trim(); string value = pair[1].Trim(); if ( string.IsNullOrEmpty( key ) ) { continue; } section.Set( key, value ); } return section; }
public void Start(ConfigurationSection configuration) { _configuration = configuration as SharedObjectServiceConfiguration; }
private IConfigurationSection GetSection( string subKey, string sectionName ) { IConfigurationSection section = null; using ( RegistryKey key = GetKey( subKey, ref sectionName, RegistryKeyPermissionCheck.Default ) ) { if ( key == null ) { return section; } section = new ConfigurationSection( sectionName ); foreach ( string valueName in key.GetValueNames() ) { string name = valueName; if ( string.IsNullOrEmpty( valueName ) ) { name = DefaultKeyName; } object value = key.GetValue( valueName ); //string stringValue = SettingConverter.GetStringFromT( value ); switch ( key.GetValueKind( valueName ) ) { case RegistryValueKind.Binary: section.Set( name, (byte[]) value ); break; case RegistryValueKind.DWord: section.Set( name, (int) value ); break; case RegistryValueKind.ExpandString: section.Set( name, (string) value ); break; case RegistryValueKind.MultiString: section.Set( name, (string[]) value ); break; case RegistryValueKind.QWord: section.Set( name, (long) value ); break; case RegistryValueKind.String: section.Set( name, (string) value ); break; case RegistryValueKind.Unknown: section.Set( name, value ); break; } } } return section; }
public void CopyTo(ConfigurationSection[] array, int index) {}
public void Add(string name, ConfigurationSection section) {}