public ConfigReader() { config__ = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); backupConfigHandler__ = (BackupConfigHandler)config__.GetSection("BackupConfig"); editorCompilerConfigHandler__ = (EditorCompilerConfigHandler)config__.GetSection("EditorCompilerConfig"); preferenceConfigHandler__ = (PreferenceConfigHandler)config__.GetSection("PreferenceConfig"); }
internal static ToolsetConfigurationSection ReadToolsetConfigurationSection(Configuration configuration) { ToolsetConfigurationSection configurationSection = null; // This will be null if the application config file does not have the following section // definition for the msbuildToolsets section as the first child element. // <configSections> // <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> // </configSections>"; // Note that the application config file may or may not contain an msbuildToolsets element. // For example: // If section definition is present and section is not present, this value is not null // If section definition is not present and section is also not present, this value is null // If the section definition is not present and section is present, then this value is null if (null != configuration) { ConfigurationSection msbuildSection = configuration.GetSection("msbuildToolsets"); configurationSection = msbuildSection as ToolsetConfigurationSection; if (configurationSection == null && msbuildSection != null) // we found msbuildToolsets but the wrong type of handler { if (String.IsNullOrEmpty(msbuildSection.SectionInformation.Type) || msbuildSection.SectionInformation.Type.IndexOf("Microsoft.Build", StringComparison.OrdinalIgnoreCase) >= 0) { // Set the configuration type handler to the current ToolsetConfigurationSection type msbuildSection.SectionInformation.Type = typeof(ToolsetConfigurationSection).AssemblyQualifiedName; try { // fabricate a temporary config file with the correct section handler type in it string tempFileName = FileUtilities.GetTemporaryFile(); // Save the modified config configuration.SaveAs(tempFileName + ".config"); // Open the configuration again, the new type for the section handler will do its stuff // Note that the OpenExeConfiguraion call uses the config filename *without* the .config // extension configuration = ConfigurationManager.OpenExeConfiguration(tempFileName); // Get the toolset information from the section using our real handler configurationSection = configuration.GetSection("msbuildToolsets") as ToolsetConfigurationSection; File.Delete(tempFileName + ".config"); File.Delete(tempFileName); } catch (Exception ex) { if (ExceptionHandling.NotExpectedException(ex)) { throw; } } } } } return configurationSection; }
public ApplicationSettings() { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); General = (GeneralSettings)config.GetSection("general"); SerialPorts = (SerialPortSettings)config.GetSection("serialPorts"); Plugins = (PluginSettings)config.GetSection("plugin"); ConnectionStrings = config.ConnectionStrings.ConnectionStrings; }
private ClientSettingsSection GetConfigSection(Configuration config, string sectionName, bool declare) { string fullSectionName = UserSettingsGroupPrefix + sectionName; ClientSettingsSection section = null; if (config != null) { section = config.GetSection(fullSectionName) as ClientSettingsSection; if (section == null && declare) { // Looks like the section isn't declared - let's declare it and try again. DeclareSection(config, sectionName); section = config.GetSection(fullSectionName) as ClientSettingsSection; } } return section; }
private static void Init() { _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); // Map the roaming configuration file. This enables the application to access the configuration file using the // System.Configuration.Configuration class //var configFileMap = new ExeConfigurationFileMap {ExeConfigFilename = roamingConfig.FilePath}; // Get the mapped configuration file. //_config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); //Get the configuration section or create it _dialerConfig = (PlacetelDialerConfig) _config.GetSection(SectionName); if (_dialerConfig == null) { _dialerConfig = new PlacetelDialerConfig(); _dialerConfig.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; _dialerConfig.SectionInformation.AllowOverride = true; _config.Sections.Add(SectionName, _dialerConfig); //Save the initial state _config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(SectionName); } }
protected void btnSubmit_Click(object sender, EventArgs e) { Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); //操作appSettings AppSettingsSection appseting = (AppSettingsSection)Configuration.GetSection("appSettings"); //修改设置 try { appseting.Settings["txtiosapplink"].Value = this.txtiosapplink.Text; } catch (Exception) { appseting.Settings.Add("txtiosapplink", this.txtiosapplink.Text); } try { appseting.Settings["txtapklink"].Value = this.txtapklink.Text; } catch (Exception) { appseting.Settings.Add("txtapklink", this.txtapklink.Text); } Configuration.Save(); }
private OptionsForm(bool local) { InitializeComponent(); // Copy the Bootstrap.exe file to New.exe, // so that the configuration file will load properly string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); string sandboxDir = Path.Combine(currentDir, "Sandbox"); if (!File.Exists(Path.Combine(sandboxDir, "New.exe"))) { File.Copy( Path.Combine(sandboxDir, "Bootstrap.exe"), Path.Combine(sandboxDir, "New.exe") ); } string filename = local ? "New.exe" : "Bootstrap.exe"; string filepath = Path.Combine(sandboxDir, filename); _Configuration = ConfigurationManager.OpenExeConfiguration(filepath); // Get the DDay.Update configuration section _Cfg = _Configuration.GetSection("DDay.Update") as DDayUpdateConfigurationSection; // Set the default setting on which application folder to use. cbAppFolder.SelectedIndex = 0; SetValuesFromConfig(); if (!local) _Configuration.SaveAs(Path.Combine(sandboxDir, "New.exe.config")); }
// https://msdn.microsoft.com/en-us/library/tkwek5a4%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 // Example Configuration Code for an HTTP Module: public static void AddModule(Configuration config, string moduleName, string moduleClass) { HttpModulesSection section = (HttpModulesSection)config.GetSection("system.web/httpModules"); // Create a new module action object. HttpModuleAction moduleAction = new HttpModuleAction( moduleName, moduleClass); // "RequestTimeIntervalModule", "Samples.Aspnet.HttpModuleExamples.RequestTimeIntervalModule"); // Look for an existing configuration for this module. int indexOfModule = section.Modules.IndexOf(moduleAction); if (-1 != indexOfModule) { // Console.WriteLine("RequestTimeIntervalModule module is already configured at index {0}", indexOfModule); } else { section.Modules.Add(moduleAction); if (!section.SectionInformation.IsLocked) { config.Save(); // Console.WriteLine("RequestTimeIntervalModule module configured."); } } }
/// <summary> /// Loads the config file /// </summary> public TreeTabConfig() { try { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); System.Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location)); fileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, CONFIG_FILENAME); config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); if (config.HasFile) { ConfigurationSection cs = config.GetSection(CONTEXT_MENU_ICONS_SECTION); if (cs != null) { XmlDocument xmlConf = new XmlDocument(); xmlConf.LoadXml(cs.SectionInformation.GetRawXml()); xmlContextMenuIcons = (XmlElement)xmlConf.FirstChild; this.isCorrectlyLoaded = true; } } } catch { this.isCorrectlyLoaded = false; } }
/// <summary> /// This method will retrieve the configuration settings. /// </summary> private void GetConfiguration() { try { m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); if (m_config.Sections["TracePreferences"] == null) { m_settings = new TracePreferences(); m_config.Sections.Add("TracePreferences", m_settings); m_config.Save(ConfigurationSaveMode.Full); } else m_settings = (TracePreferences)m_config.GetSection("TracePreferences"); } catch (InvalidCastException e) { System.Diagnostics.Trace.WriteLine("Preference Error - " + e.Message, "MainForm.GetConfiguration"); MessageBoxOptions options = 0; MessageBox.Show(Properties.Resources.PREF_NOTLOADED, Properties.Resources.PREF_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, options); m_settings = new TracePreferences(); } catch (ArgumentException e) { System.Diagnostics.Trace.WriteLine("Argument Error - " + e.Message, "MainForm.GetConfiguration"); throw; } catch (ConfigurationErrorsException e) { System.Diagnostics.Trace.WriteLine("Configuration Error - " + e.Message, "MainForm.GetConfiguration"); throw; } }
/// <summary> /// Initializes a new instance of AppConfig based on supplied configuration /// </summary> /// <param name="configuration"> Configuration to load settings from </param> public AppConfig(Configuration configuration) : this( configuration.ConnectionStrings.ConnectionStrings, configuration.AppSettings.Settings, (EntityFrameworkSection)configuration.GetSection(EFSectionName)) { DebugCheck.NotNull(configuration); }
private AuthenticationSection GetFormsAuthConfig(out Configuration webConfig) { string root = this.Request.ApplicationPath; webConfig = WebConfigurationManager.OpenWebConfiguration(root); AuthenticationSection authenticationSection = (AuthenticationSection)webConfig.GetSection("system.web/authentication"); return authenticationSection; }
/// <summary> /// Initializes a new instance of AppConfig based on supplied configuration /// </summary> /// <param name="configuration">Configuration to load settings from</param> public AppConfig(Configuration configuration) : this( configuration.ConnectionStrings.ConnectionStrings, configuration.AppSettings.Settings, (EntityFrameworkSection)configuration.GetSection(EFSectionName)) { //Contract.Requires(configuration != null); }
public static StandardEndpointsSection GetSection(Configuration config) { if (config == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("config"); } return (StandardEndpointsSection)config.GetSection(ConfigurationStrings.StandardEndpointsSectionPath); }
private void OpenConfigurationFile() { _Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); string configurationName = "GlobalConfiguration"; _GlobalConfiguration = new GlobalConfiguration(); _GlobalConfiguration.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; CreateConfigurationSection(configurationName, _GlobalConfiguration); _GlobalConfiguration = (GlobalConfiguration)_Configuration.GetSection(configurationName); configurationName = "TrackEditorConfiguration"; _TrackEditorConfiguration = new Core.Globals.TrackEditorConfiguration(); _TrackEditorConfiguration.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; CreateConfigurationSection(configurationName, _TrackEditorConfiguration); _TrackEditorConfiguration = (TrackEditorConfiguration)_Configuration.GetSection(configurationName); }
public Form1() { backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); backgroundWorker2 = new System.ComponentModel.BackgroundWorker(); backgroundWorker3 = new System.ComponentModel.BackgroundWorker(); backgroundWorker2.WorkerReportsProgress = true; backgroundWorker2.WorkerSupportsCancellation = true; InitializeComponent(); backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler( backgroundWorker1_RunWorkerCompleted); backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler( backgroundWorker1_ProgressChanged); backgroundWorker2.DoWork += new DoWorkEventHandler(backgroundWorker2_DoWork); backgroundWorker2.RunWorkerCompleted += new RunWorkerCompletedEventHandler( backgroundWorker2_RunWorkerCompleted); backgroundWorker2.ProgressChanged += new ProgressChangedEventHandler( backgroundWorker2_ProgressChanged); customSection = new CustomSection(); try { // Get the current configuration file. config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); // Create the custom section entry // in <configSections> group and the // related target section in <configuration>. if (config.Sections["CustomSection"] == null) { config.Sections.Add("CustomSection", customSection); // Save the configuration file. customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } customSection = config.GetSection("CustomSection") as CustomSection; userText.Text = customSection.User; passwdText.Text = customSection.Passwd; databaseText.Text = customSection.Database; } catch (ConfigurationErrorsException err) { MessageBox.Show("CreateConfigurationFile: {0}", err.ToString()); } }
private void Context_Error(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; // determine if it was an HttpException if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException)))) { // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config"); // Get the section. CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); // Get the collection CustomErrorCollection customErrorsCollection = customErrorsSection.Errors; int statusCode = ((HttpException)context.Error).GetHttpCode(); //Clears existing response headers and sets the desired ones. context.Response.ClearHeaders(); context.Response.StatusCode = statusCode; if (statusCode == 404) { string Path = context.Request.Path; if (Path.Contains("playlist.xml")) { context.Response.Clear(); context.Response.StatusCode = 101; context.Response.Redirect("/mp3/playlist.xml"); } else if (!Path.EndsWith(".js") && !Path.EndsWith(".gif") && !Path.EndsWith(".jpg") && !Path.EndsWith(".png")) { context.Response.Clear(); context.Response.Write("404 file not found"); context.Response.Redirect("/404.aspx"); } } else { } //context.Response.Flush(); } else { // log the error here in the tracer //Clears existing response headers and sets the desired ones. context.Response.ClearHeaders(); context.Response.StatusCode = 500; //context.Server.Transfer("/500.aspx"); if (!context.Request.IsLocal) { context.Response.Redirect("/500.aspx"); } // } }
public OptionsViewModel() { _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); _configSection = (BlackJackSection)_configuration.GetSection("blackJack"); _deckFile = _configSection.DeckFile; _backFile = _configSection.BackFile; _initialPlayerMoney = _configSection.InitialPlayerMoney; _initialDealerMoney = _configSection.InitialDealerMoney; }
private static void UnprotectSectionImpl(string sectionName, Configuration config) { ConfigurationSection section = config.GetSection(sectionName); if (section != null && section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); config.Save(); } }
private static void ProtectSectionImpl(string sectionName, string provider, Configuration config) { ConfigurationSection section = config.GetSection(sectionName); if (section != null && !section.SectionInformation.IsProtected) { section.SectionInformation.ProtectSection(provider); config.Save(); } }
static SystemConfig() { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.Sections["Machine"] == null) { config.Sections.Add("Machine", new MachineSection()); machineSection.SectionInformation.ForceSave = true; config.Save(); } machineSection = config.GetSection("Machine") as MachineSection; }
private AppSettingsSection GetModuleSection(Configuration configuration) { var section = (AppSettingsSection) configuration.GetSection(Guid); if (section == null) { var newSection = new AppSettingsSection(); newSection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToRoamingUser; configuration.Sections.Add(Guid, newSection); section = newSection; } return section; }
//##### INICIALIZA LOS DATOS DEL APPCONFIG ##### public ClassModConfig() { try { MiAppConfig = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); //Se abre el app.config CadenaConexion = (ConnectionStringsSection)MiAppConfig.GetSection("connectionStrings"); //Obtengo la cadena de conexion MiConfig = (AppSettingsSection)MiAppConfig.GetSection("appSettings"); //Obtengo la seccion appSettings MiCnx = ConfigurationManager.ConnectionStrings["EnterpriseSolution.Properties.Settings.bdnominaConnectionString"]; //capturo cadena de conexion Estado = ConfigurationManager.AppSettings["Validador"]; Licencia = ConfigurationManager.AppSettings["Licencia"]; InfEmp = ConfigurationManager.AppSettings["InfEmp"]; Skins = ConfigurationManager.AppSettings["Skins"]; Update = ConfigurationManager.AppSettings["Update"]; } catch (Exception ex) { MsjErr.MsjBox(1, "ERR001-01", "No se pueden leer todos los valores del app.config - " + ex.ToString()); Environment.Exit(0); } }
public static void Reload() { Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); ConnectionStringsSection = Config.GetSection("userConnectionStrings") as System.Configuration.ConnectionStringsSection; if (ConnectionStringsSection == null) { ConnectionStringsSection = new System.Configuration.ConnectionStringsSection(); ConnectionStringsSection.SectionInformation.set_AllowExeDefinition(ConfigurationAllowExeDefinition.MachineToLocalUser); Config.Sections.Add("userConnectionStrings", ConnectionStringsSection); Config.Save(); } }
public SettingsForm() { InitializeComponent(); configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); UploadSettingsConfigSection section = (UploadSettingsConfigSection)configuration.GetSection("UploadSettings"); if (section != null) { foreach (UploadElement uploadElement in section.UploadSettings) { Panels.Controls.Add(new PanelConfig(uploadElement, configuration)); } } }
public SampleService() { Config = ConfigurationManager.OpenMappedExeConfiguration(FileMap, ConfigurationUserLevel.None); if (! Config.HasFile) { throw new ArgumentException("系统未找到" + FileMap.ExeConfigFilename + "文件"); } AccountSection = (AccountSection)Config.GetSection("accountConfig"); if (AccountSection == null) { throw new ArgumentException(FileMap.ExeConfigFilename + "文件中未配置accountConfig节点"); } }
protected void Button1_Click(object sender, EventArgs e) { // Get the application configuration file. System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); // <Snippet2> System.Web.Configuration.CacheSection cacheSection = (System.Web.Configuration.CacheSection)config.GetSection( "system.web/caching/cache"); // </Snippet2> // <Snippet6> // Increase the PrivateBytesLimit property to 0. cacheSection.PrivateBytesLimit = cacheSection.PrivateBytesLimit + 10; // </Snippet6> // <Snippet7> // Increase memory limit. cacheSection.PercentagePhysicalMemoryUsedLimit = cacheSection.PercentagePhysicalMemoryUsedLimit + 1; // </Snippet7> // <Snippet8> // Increase poll time. cacheSection.PrivateBytesPollTime = cacheSection.PrivateBytesPollTime + TimeSpan.FromMinutes(1); // </Snippet8> // <Snippet3> // Enable or disable memory collection. cacheSection.DisableMemoryCollection = !cacheSection.DisableMemoryCollection; // </Snippet3> // <Snippet4> // Enable or disable cache expiration. cacheSection.DisableExpiration = !cacheSection.DisableExpiration; // </Snippet4> // Save the configuration file. config.Save(System.Configuration.ConfigurationSaveMode.Modified); }
public StartHostingDlg() { StartHostingParameters = new StartHostingParams (); config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None); appSettings = (AppSettingsSection) config.GetSection ("appSettings"); List<string> keys = new List<string> (appSettings.Settings.AllKeys); if (keys.Contains ("lastHostPort")) StartHostingParameters.Port = int.Parse (appSettings.Settings["lastHostPort"].Value); if (keys.Contains ("lastNickname")) StartHostingParameters.Nickname = appSettings.Settings["lastNickname"].Value; DataContext = StartHostingParameters; InitializeComponent (); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); try { AppSettingsSection appseting = (AppSettingsSection)Configuration.GetSection("appSettings"); //修改设置 this.txtiosapplink.Text = appseting.Settings["txtiosapplink"].Value; this.txtapklink.Text = appseting.Settings["txtapklink"].Value; } catch (Exception) { } } }
public override void Configure(IServiceCollection services, Configuration moduleConfiguration) { // Configure module authorization if needed IAuthorizationRulesService authorizationRuleService = services.Get<IAuthorizationRulesService>(); if (authorizationRuleService != null) { AuthorizationConfigurationSection authorizationSection = moduleConfiguration.GetSection(AuthorizationSection) as AuthorizationConfigurationSection; if (authorizationSection != null) { foreach (AuthorizationRuleElement ruleElement in authorizationSection.ModuleRules) { authorizationRuleService.RegisterAuthorizationRule(ruleElement.AbsolutePath, ruleElement.RuleName); } } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); try { AppSettingsSection appseting = (AppSettingsSection)Configuration.GetSection("appSettings"); //修改设置 this.pteamTitle.InnerHtml = appseting.Settings["txtTeamTitle"].Value; } catch (Exception) { } this.BindData(); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); try { AppSettingsSection appseting = (AppSettingsSection)Configuration.GetSection("appSettings"); //修改设置 this.owkeywords.Content = appseting.Settings["Keywords"].Value; this.owdescription.Content= appseting.Settings["Description"].Value; this.OWTitle.InnerHtml = appseting.Settings["OW_Title"].Value; this.LOGOimg.Src = appseting.Settings["LOGOimg"].Value; } catch (Exception) { } } }
public static void GetConverterElement() { // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the external JSON section. ScriptingJsonSerializationSection jsonSection = (ScriptingJsonSerializationSection)configuration.GetSection( "system.web.extensions/scripting/webServices/jsonSerialization"); //Get the converters collection. ConvertersCollection converters = jsonSection.Converters; if ((converters != null) && converters.Count > 0) { // Get the first registered converter. Converter converterElement = converters[0]; } }
protected void Button2_Click(object sender, EventArgs e) { // Get the application configuration file. System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); System.Web.Configuration.CacheSection cacheSection = (System.Web.Configuration.CacheSection)config.GetSection( "system.web/caching/cache"); // Read the cache section. System.Text.StringBuilder buffer = new System.Text.StringBuilder(); string currentFile = cacheSection.CurrentConfiguration.FilePath; bool dExpiration = cacheSection.DisableExpiration; bool dMemCollection = cacheSection.DisableMemoryCollection; TimeSpan pollTime = cacheSection.PrivateBytesPollTime; int phMemUse = cacheSection.PercentagePhysicalMemoryUsedLimit; long pvBytesLimit = cacheSection.PrivateBytesLimit; string cacheEntry = String.Format("File: {0} <br/>", currentFile); buffer.Append(cacheEntry); cacheEntry = String.Format("Expiration Disabled: {0} <br/>", dExpiration); buffer.Append(cacheEntry); cacheEntry = String.Format("Memory Collection Disabled: {0} <br/>", dMemCollection); buffer.Append(cacheEntry); cacheEntry = String.Format("Poll Time: {0} <br/>", pollTime.ToString()); buffer.Append(cacheEntry); cacheEntry = String.Format("Memory Limit: {0} <br/>", phMemUse.ToString()); buffer.Append(cacheEntry); cacheEntry = String.Format("Bytes Limit: {0} <br/>", pvBytesLimit.ToString()); buffer.Append(cacheEntry); Label1.Text = buffer.ToString(); }
// </Snippet3> // <Snippet7> // Create the AppSettings section. // The function uses the GetSection(string)method // to access the configuration section. // It also adds a new element to the section collection. public static void CreateAppSettings() { // Get the application configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); string sectionName = "appSettings"; // Add an entry to appSettings. int appStgCnt = ConfigurationManager.AppSettings.Count; string newKey = "NewKey" + appStgCnt.ToString(); string newValue = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(); config.AppSettings.Settings.Add(newKey, newValue); // Save the configuration file. config.Save(ConfigurationSaveMode.Modified); // Force a reload of the changed section. This // makes the new values available for reading. ConfigurationManager.RefreshSection(sectionName); // Get the AppSettings section. AppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection(sectionName); Console.WriteLine(); Console.WriteLine("Using GetSection(string)."); Console.WriteLine("AppSettings section:"); Console.WriteLine( appSettingSection.SectionInformation.GetRawXml()); }
// </Snippet23> // <Snippet24> // This function shows how to read the key/value // pairs (settings collection)contained in the // appSettings section. static void ReadAppSettings() { try { // Get the configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get the appSettings section. System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)config.GetSection("appSettings"); // Get the auxiliary file name. Console.WriteLine("Auxiliary file: {0}", config.AppSettings.File); // Get the settings collection (key/value pairs). if (appSettings.Settings.Count != 0) { foreach (string key in appSettings.Settings.AllKeys) { string value = appSettings.Settings[key].Value; Console.WriteLine("Key: {0} Value: {1}", key, value); } } else { Console.WriteLine("The appSettings section is empty. Write first."); } } catch (Exception e) { Console.WriteLine("Exception raised: {0}", e.Message); } }
void protectSection(bool isProtect) { System.Configuration.Configuration config = getBaseConfig(); ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp"); if (section != null) { if (isProtect) { if (!section.SectionInformation.IsProtected) { section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); } } else { if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); } } config.Save(); } }
public static object?GetCustomSection(this System.Configuration.Configuration @this, string name) { var info = @this.GetSection(name)?.SectionInformation; if (info == null) { return(null); } var type = Type.GetType(info.Type); if (type == null) { return(null); } var xml = info.GetRawXml(); if (xml.IsNullOrWhiteSpace()) { return(null); } var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); var sectionHandler = Activator.CreateInstance(type) as IConfigurationSectionHandler; if (sectionHandler == null) { return(null); } return(sectionHandler.Create(null, null, xmlDocument.DocumentElement)); }
public static void Main() { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the section. HttpModulesSection httpModulesSection = (HttpModulesSection)configuration.GetSection( "system.web/httpModules"); // </Snippet1> // <Snippet2> // Create a new section object. HttpModuleAction newModuleAction = new HttpModuleAction("MyModule", "MyModuleType"); // </Snippet2> // <Snippet3> // Initialize the module name and type properties. newModuleAction.Name = "ModuleName"; newModuleAction.Type = "ModuleType"; // </Snippet3> // <Snippet4> // Get the modules collection. HttpModuleActionCollection httpModules = httpModulesSection.Modules; string moduleFound = "moduleName not found."; // Find the module with the specified name. foreach (HttpModuleAction currentModule in httpModules) { if (currentModule.Name == "moduleName") { moduleFound = "moduleName found."; } } // </Snippet4> // <Snippet5> // Get the modules collection. HttpModuleActionCollection httpModules2 = httpModulesSection.Modules; string typeFound = "typeName not found."; // Find the module with the specified type. foreach (HttpModuleAction currentModule in httpModules2) { if (currentModule.Type == "typeName") { typeFound = "typeName found."; } } // </Snippet5> }
public bool storeAPIConfiguration(com.show.api.APISection customSection) { string configFile = System.IO.Path.Combine( Environment.CurrentDirectory, configFileName); // Map the new configuration file. ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(); configFileMap.ExeConfigFilename = configFile; // Get the configuration file. The file name has // this format appname.exe.config. // Get the mapped configuration file System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None); try { // Create a custom configuration section // having the same name that is used in the // roaming configuration file. // This is because the configuration section // can be overridden by lower-level // configuration files. // See the GetRoamingConfiguration() function in // this example. string sectionName = "apiSection"; if (config.Sections[sectionName] == null) { // Create a custom section if it does // not exist yet. // Store console settings. // Add configuration information to the // configuration file. config.Sections.Add(sectionName, customSection); config.Save(ConfigurationSaveMode.Modified); // Force a reload of the changed section. // This makes the new values available for reading. ConfigurationManager.RefreshSection(sectionName); return(true); } else { // Set console properties using values // stored in the configuration file. com.show.api.APISection tmpSection = (com.show.api.APISection)config.GetSection(sectionName); if (tmpSection.ApiElement.AppID.Equals(customSection.ApiElement.AppID) && tmpSection.ApiElement.Secret.Equals(customSection.ApiElement.Secret)) { return(true); } else { tmpSection.ApiElement.AppID = customSection.ApiElement.AppID; tmpSection.ApiElement.Secret = customSection.ApiElement.Secret; customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); return(true); } } } catch (ConfigurationErrorsException e) { Console.WriteLine("[Error exception: {0}]", e.ToString()); } // Display feedback. Console.WriteLine("[Error] storeAPIConfiguration"); Console.WriteLine("Using OpenExeConfiguration(string)."); // Display the current configuration file path. Console.WriteLine("Configuration file is: {0}", config.FilePath); return(false); }
public override T GetSection <T>(string sectionName) { return(config.GetSection(sectionName) as T); }
public static T GetSection(System.Configuration.Configuration configuration) { var section = (XmlConfigurationSection <T>)configuration.GetSection(typeof(T).Name); return(section?._configurationItem); }
protected UnityConfigurationSection GetUnitySection(string baseName) { SysConfiguration config = OpenConfigFile(baseName); return((UnityConfigurationSection)config.GetSection("unity")); }
public static void Main() { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration( "/aspnet"); // Get the section. AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection( "system.web/authentication"); // Get the users collection. FormsAuthenticationUserCollection formsAuthenticationUsers = authenticationSection.Forms.Credentials.Users; // </Snippet1> // <Snippet2> // </Snippet2> // <Snippet3> // Define the user name. string name = "userName"; // Define the encrypted password. string password = "******"; // Create a new FormsAuthenticationUser object. FormsAuthenticationUser newformsAuthenticationUser = new FormsAuthenticationUser(name, password); // </Snippet3> // <Snippet4> // Using the Password property. // Get current password. string currentPassword = formsAuthenticationUsers[0].Password; // Set a SHA1 encrypted password. // This example uses the SHA1 algorithm. // Due to collision problems with SHA1, Microsoft recommends SHA256 or better. formsAuthenticationUsers[0].Password = "******"; // </Snippet4> // <Snippet5> // Using the Name property. // Get current name. string currentName = formsAuthenticationUsers[0].Name; // Set a new name. formsAuthenticationUsers[0].Name = "userName"; // </Snippet5> }
private static void ToggleConnectionStringProtection(string pathName, bool protect) { // Define the Dpapi provider name. string strProvider = "DataProtectionConfigurationProvider"; // string strProvider = "RSAProtectedConfigurationProvider"; System.Configuration.Configuration oConfiguration = null; System.Configuration.ConnectionStringsSection oSection = null; try { // Open the configuration file and retrieve // the connectionStrings section. // For Web! // oConfiguration = System.Web.Configuration. // WebConfigurationManager.OpenWebConfiguration("~"); // For Windows! // Takes the executable file name without the config extension. oConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName); if (oConfiguration != null) { bool blnChanged = false; oSection = oConfiguration.GetSection("connectionStrings") as System.Configuration.ConnectionStringsSection; if (oSection != null) { if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked))) { if (protect) { if (!(oSection.SectionInformation.IsProtected)) { blnChanged = true; // Encrypt the section. oSection.SectionInformation.ProtectSection(strProvider); } } else { if (oSection.SectionInformation.IsProtected) { blnChanged = true; // Remove encryption. oSection.SectionInformation.UnprotectSection(); } } } if (blnChanged) { // Indicates whether the associated configuration section // will be saved even if it has not been modified. oSection.SectionInformation.ForceSave = true; // Save the current configuration. oConfiguration.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } } } } catch (System.Exception ex) { throw (ex); } finally { } }
private bool changeConnexionString(ConnectionDB _ConnectionDB, out string msgErr) { msgErr = string.Empty; bool b = false; try { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = _ConnectionDB.DataSource; builder.InitialCatalog = _ConnectionDB.InitialCatalog; builder.PersistSecurityInfo = true; string _connexionString = string.Empty; System.Configuration.Configuration configWeb = WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringsSection connectionStringSection = (ConnectionStringsSection)configWeb.GetSection(Constantes.sectionConnexionConfig); if (!string.IsNullOrEmpty(_ConnectionDB.UserID)) { builder.UserID = _ConnectionDB.UserID; builder.Password = _ConnectionDB.Password; } else { builder.IntegratedSecurity = _ConnectionDB.IntegratedSecurity; } _connexionString = builder.ConnectionString; connectionStringSection.ConnectionStrings[Constantes.SAPHIRCOMConnexionStringName].ConnectionString = _connexionString; configWeb.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(Constantes.sectionConnexionConfig); return(b = true); } catch (Exception ex) { msgErr = ex.Message; } //pour le contenu de la connection string in ffile. //string connStr = ConfigurationManager.ConnectionStrings["nameMyconnectionString"].ConnectionString; return(b); }
public static void Main() { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the section. string configPath = "system.web/cache/sqlCacheDependency"; System.Web.Configuration.SqlCacheDependencySection sqlDs = (System.Web.Configuration.SqlCacheDependencySection)webConfig.GetSection( configPath); // Get the databases element at 0 index. System.Web.Configuration.SqlCacheDependencyDatabase sqlCdd = sqlDs.Databases[0]; // </Snippet1> // <Snippet2> // Get the current PollTime property value. Int32 pollTimeValue = sqlCdd.PollTime; // Set the PollTime property to 1000 milliseconds. sqlCdd.PollTime = 1000; // </Snippet2> // <Snippet3> // Get the current Name property value. string nameValue = sqlCdd.Name; // Set the Name for this configuration element. sqlCdd.Name = "ConfigElementName"; // </Snippet3> // <Snippet4> // Get the current ConnectionStringName property value. string connectionNameValue = sqlCdd.ConnectionStringName; // Set the ConnectionName property. This is the database name. sqlCdd.ConnectionStringName = "DataBaseName"; // </Snippet4> // <Snippet5> SqlCacheDependencyDatabase dbElement0 = new SqlCacheDependencyDatabase( "dataBase", "dataBaseElement", 500); // </Snippet5> // <Snippet6> SqlCacheDependencyDatabase dbElement1 = new SqlCacheDependencyDatabase( "dataBase1", "dataBaseElement1"); // </Snippet6> }
public static T GetSection(System.Configuration.Configuration configuration, string sectionName) { var section = (XmlConfigurationSection <T>)configuration.GetSection(sectionName); return(section?._configurationItem); }
private static void ToggleConnectionStringProtection (string pathName, bool protect) { // Define the Dpapi provider name. string strProvider = "DataProtectionConfigurationProvider"; // string strProvider = "RSAProtectedConfigurationProvider"; System.Configuration.Configuration oConfiguration = null; System.Configuration.ConnectionStringsSection oSection = null; try { // Open the configuration file and retrieve // the connectionStrings section. // For Web! oConfiguration = System.Web.Configuration. WebConfigurationManager.OpenWebConfiguration("~"); // For Windows! // Takes the executable file name without the config extension. //oConfiguration = System.Configuration.ConfigurationManager. // OpenExeConfiguration(pathName); if (oConfiguration != null) { bool blnChanged = false; oSection = oConfiguration.GetSection("connectionStrings") as System.Configuration.ConnectionStringsSection; if (oSection != null) { if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked))) { if (protect) { if (!(oSection.SectionInformation.IsProtected)) { blnChanged = true; // Encrypt the section. oSection.SectionInformation.ProtectSection (strProvider); oConfiguration.AppSettings.Settings["Cypher"].Value = "true"; } } else { if (oSection.SectionInformation.IsProtected) { blnChanged = true; // Remove encryption. oSection.SectionInformation.UnprotectSection(); System.Configuration.ConnectionStringSettings connString = new ConnectionStringSettings(); if (0 < oConfiguration.ConnectionStrings.ConnectionStrings.Count) { connString = oConfiguration.ConnectionStrings.ConnectionStrings["CNTSEntities"]; } string con = connString.ConnectionString; int inicio = con.IndexOf("\""); int fin = con.IndexOf("\"", inicio + 1); string conectionString = con.Substring(inicio + 1, fin - inicio - 1); } } } if (blnChanged) { // Indicates whether the associated configuration section // will be saved even if it has not been modified. oSection.SectionInformation.ForceSave = true; // Save the current configuration. oConfiguration.Save(); } } } } catch (System.Exception ex) { throw (ex); } finally { } }
static void Main(string[] args) { //<snippet1> // Obtains the machine configuration settings on the local machine. System.Configuration.Configuration machineConfig = System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration(); machineConfig.SaveAs("c:\\machineConfig.xml"); //</snippet1> //<snippet2> // Obtains the configuration settings for a Web application. System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp"); webConfig.SaveAs("c:\\webConfig.xml"); //</snippet2> //<snippet3> // Obtains the configuration settings for the <anonymousIdentification> section. System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp"); System.Web.Configuration.SystemWebSectionGroup systemWeb = config.GetSectionGroup("system.web") as System.Web.Configuration.SystemWebSectionGroup; System.Web.Configuration.AnonymousIdentificationSection sectionConfig = systemWeb.AnonymousIdentification; if (sectionConfig != null) { StringBuilder sb = new StringBuilder(); sb.Append("<anonymousIdentification> attributes:\r\n"); System.Configuration.PropertyInformationCollection props = sectionConfig.ElementInformation.Properties; foreach (System.Configuration.PropertyInformation prop in props) { sb.AppendFormat("{0} = {1}\r\n", prop.Name.ToString(), prop.Value.ToString()); } Console.WriteLine(sb.ToString()); } //</snippet3> //<snippet4> IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token; // Obtains the machine configuration settings on a remote machine. System.Configuration.Configuration remoteMachineConfig = System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration (null, "ServerName", userToken); remoteMachineConfig.SaveAs("c:\\remoteMachineConfig.xml"); // Obtains the root Web configuration settings on a remote machine. System.Configuration.Configuration remoteRootConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration (null, null, null, "ServerName", userToken); remoteRootConfig.SaveAs("c:\\remoteRootConfig.xml"); // Obtains the configuration settings for the // W3SVC/1/Root/Temp application on a remote machine. System.Configuration.Configuration remoteWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("/Temp", "1", null, "ServerName", userToken); remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml"); //</snippet4> //<snippet5> // Updates the configuration settings for a Web application. System.Configuration.Configuration updateWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp"); System.Web.Configuration.CompilationSection compilation = updateWebConfig.GetSection("system.web/compilation") as System.Web.Configuration.CompilationSection; Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug); compilation.Debug = true; if (!compilation.SectionInformation.IsLocked) { updateWebConfig.Save(); Console.WriteLine("New <compilation> debug = {0}", compilation.Debug); } else { Console.WriteLine("Could not save configuration."); } //</snippet5> //<snippet6> System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot"); System.Configuration.ConnectionStringSettings connString; if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"]; if (connString != null) { Console.WriteLine("Northwind connection string = \"{0}\"", connString.ConnectionString); } else { Console.WriteLine("No Northwind connection string"); } } //</snippet6> //<snippet7> System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); if (rootWebConfig1.AppSettings.Settings.Count > 0) { System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings["customsetting1"]; if (customSetting != null) { Console.WriteLine("customsetting1 application string = \"{0}\"", customSetting.Value); } else { Console.WriteLine("No customsetting1 application string"); } } //</snippet7> }
public void WebConfigUtil_UpdateConfiguration() { string tempConfigFile = Path.GetTempFileName(); try { File.WriteAllText(tempConfigFile, EmptyConfig); System.Configuration.Configuration cfg = ConfigurationManager.OpenExeConfiguration(tempConfigFile); WebConfigUtil webConfigUtil = new WebConfigUtil(cfg); // Verify that none of the sections we wat to set are present Assert.IsFalse(webConfigUtil.IsAspNetCompatibilityEnabled(), "Blank config should not have AspNetCompatibility"); Assert.IsFalse(webConfigUtil.IsMultipleSiteBindingsEnabled(), "Blank config should not have MultiSiteBinding"); Assert.IsFalse(webConfigUtil.IsEndpointDeclared(BusinessLogicClassConstants.ODataEndpointName), "Blank config should not have OData endpoint"); Assert.IsTrue(webConfigUtil.DoWeNeedToValidateIntegratedModeToWebServer(), "Blank config should not have validate integrated mode"); Assert.IsTrue(webConfigUtil.DoWeNeedToAddHttpModule(), "Blank config should not have http module"); Assert.IsTrue(webConfigUtil.DoWeNeedToAddModuleToWebServer(), "Blank config should not have http module to web server"); string domainServiceFactoryName = WebConfigUtil.GetDomainServiceModuleTypeName(); Assert.IsFalse(string.IsNullOrEmpty(domainServiceFactoryName), "Could not find domain service factory name"); // ------------------------------------ // Set everything we set from the wizard // ------------------------------------ webConfigUtil.SetAspNetCompatibilityEnabled(true); webConfigUtil.SetMultipleSiteBindingsEnabled(true); webConfigUtil.AddValidateIntegratedModeToWebServer(); webConfigUtil.AddHttpModule(domainServiceFactoryName); webConfigUtil.AddModuleToWebServer(domainServiceFactoryName); // ------------------------------------ // Verify API's see the changes // ------------------------------------ Assert.IsTrue(webConfigUtil.IsAspNetCompatibilityEnabled(), "Failed to set AspNetCompatibility"); Assert.IsTrue(webConfigUtil.IsMultipleSiteBindingsEnabled(), "Failed to set MultiSiteBinding"); Assert.IsFalse(webConfigUtil.DoWeNeedToValidateIntegratedModeToWebServer(), "Failed to set validate integrated mode"); Assert.IsFalse(webConfigUtil.DoWeNeedToAddHttpModule(), "Failed to set http module"); Assert.IsFalse(webConfigUtil.DoWeNeedToAddModuleToWebServer(), "Failed to set http module to web server"); // ------------------------------------ // Independently verify those changes // ------------------------------------ // AspNetCompat ServiceHostingEnvironmentSection section = cfg.GetSection("system.serviceModel/serviceHostingEnvironment") as ServiceHostingEnvironmentSection; Assert.IsTrue(section != null && section.AspNetCompatibilityEnabled, "AspNetCompat did not set correct section"); // MultisiteBindings Assert.IsTrue(section != null && section.MultipleSiteBindingsEnabled, "MultisiteBinding did not set correct section"); // Http modules System.Web.Configuration.HttpModulesSection httpModulesSection = cfg.GetSection("system.web/httpModules") as System.Web.Configuration.HttpModulesSection; HttpModuleAction module = (httpModulesSection == null) ? null : httpModulesSection.Modules.OfType <HttpModuleAction>() .FirstOrDefault(a => String.Equals(a.Name, BusinessLogicClassConstants.DomainServiceModuleName, StringComparison.OrdinalIgnoreCase)); Assert.IsNotNull(module, "Did not find httpModule"); // ------------------------------------ // Set and verify OData endpoint // ------------------------------------ webConfigUtil.AddEndpointDeclaration(BusinessLogicClassConstants.ODataEndpointName, WebConfigUtil.GetODataEndpointFactoryTypeName()); Assert.IsTrue(webConfigUtil.IsEndpointDeclared(BusinessLogicClassConstants.ODataEndpointName), "Failed to set OData endpoint"); DomainServicesSection domainServicesSection = cfg.GetSection("system.serviceModel/domainServices") as DomainServicesSection; Assert.IsNotNull(domainServicesSection, "system.serviceModel/domainServices section not found"); Assert.AreEqual(ConfigurationAllowDefinition.MachineToApplication, domainServicesSection.SectionInformation.AllowDefinition, "AllowDefinition s/b MachineToApplication"); Assert.IsFalse(domainServicesSection.SectionInformation.RequirePermission, "RequirePermission s/b false"); ProviderSettings setting = (domainServicesSection == null) ? null : domainServicesSection.Endpoints.OfType <ProviderSettings>().FirstOrDefault(p => string.Equals(p.Name, BusinessLogicClassConstants.ODataEndpointName, StringComparison.OrdinalIgnoreCase)); Assert.IsNotNull(setting, "Did not find OData endpoint in config"); // ValidateIntegratedMode this.CheckValidateIntegratedMode(cfg); // WebServer module this.CheckWebServerModule(cfg, WebConfigUtil.GetDomainServiceModuleTypeName()); } catch (Exception ex) { Assert.Fail("Did not expect exception " + ex); } finally { File.Delete(tempConfigFile); } }
private InstrumentationConfigurationSection GetSection(string configFile) { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = configFile; System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); InstrumentationConfigurationSection section = (InstrumentationConfigurationSection)config.GetSection(InstrumentationConfigurationSection.SectionName); return(section); }
public static ExpressionEditor GetExpressionEditor(Type expressionBuilderType, IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } if (expressionBuilderType == null) { throw new ArgumentNullException("expressionBuilderType"); } ExpressionEditor editor = null; IWebApplication service = (IWebApplication)serviceProvider.GetService(typeof(IWebApplication)); if (service != null) { IDictionary expressionEditorsByTypeCache = GetExpressionEditorsByTypeCache(service); if (expressionEditorsByTypeCache != null) { editor = (ExpressionEditor)expressionEditorsByTypeCache[expressionBuilderType]; } if (editor != null) { return(editor); } System.Configuration.Configuration configuration = service.OpenWebConfiguration(true); if (configuration == null) { return(editor); } CompilationSection section = (CompilationSection)configuration.GetSection("system.web/compilation"); ExpressionBuilderCollection expressionBuilders = section.ExpressionBuilders; bool flag = false; string fullName = expressionBuilderType.FullName; foreach (System.Web.Configuration.ExpressionBuilder builder in expressionBuilders) { if (string.Equals(builder.Type, fullName, StringComparison.OrdinalIgnoreCase)) { editor = GetExpressionEditorInternal(expressionBuilderType, builder.ExpressionPrefix, service, serviceProvider); flag = true; } } if (flag) { return(editor); } object[] customAttributes = expressionBuilderType.GetCustomAttributes(typeof(ExpressionPrefixAttribute), true); ExpressionPrefixAttribute attribute = null; if (customAttributes.Length > 0) { attribute = (ExpressionPrefixAttribute)customAttributes[0]; } if (attribute != null) { System.Web.Configuration.ExpressionBuilder buildProvider = new System.Web.Configuration.ExpressionBuilder(attribute.ExpressionPrefix, expressionBuilderType.FullName); configuration = service.OpenWebConfiguration(false); section = (CompilationSection)configuration.GetSection("system.web/compilation"); section.ExpressionBuilders.Add(buildProvider); configuration.Save(); editor = GetExpressionEditorInternal(expressionBuilderType, buildProvider.ExpressionPrefix, service, serviceProvider); } } return(editor); }
// </Snippet5> // <Snippet6> // Get the application configuration file. // This function uses the // OpenExeConfiguration(string)method // to get the application configuration file. // It also creates a custom ConsoleSection and // sets its ConsoleElement BackgroundColor and // ForegroundColor properties to black and white // respectively. Then it uses these properties to // set the console colors. public static void GetAppConfiguration() { // Get the application path needed to obtain // the application configuration file. #if DEBUG string applicationName = Environment.GetCommandLineArgs()[0]; #else string applicationName = Environment.GetCommandLineArgs()[0] + ".exe"; #endif string exePath = System.IO.Path.Combine( Environment.CurrentDirectory, applicationName); // Get the configuration file. The file name has // this format appname.exe.config. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); try { // Create a custom configuration section // having the same name that is used in the // roaming configuration file. // This is because the configuration section // can be overridden by lower-level // configuration files. // See the GetRoamingConfiguration() function in // this example. string sectionName = "consoleSection"; ConsoleSection customSection = new ConsoleSection(); if (config.Sections[sectionName] == null) { // Create a custom section if it does // not exist yet. // Store console settings. customSection.ConsoleElement.BackgroundColor = ConsoleColor.Black; customSection.ConsoleElement.ForegroundColor = ConsoleColor.White; // Add configuration information to the // configuration file. config.Sections.Add(sectionName, customSection); config.Save(ConfigurationSaveMode.Modified); // Force a reload of the changed section. // This makes the new values available for reading. ConfigurationManager.RefreshSection(sectionName); } // Set console properties using values // stored in the configuration file. customSection = (ConsoleSection)config.GetSection(sectionName); Console.BackgroundColor = customSection.ConsoleElement.BackgroundColor; Console.ForegroundColor = customSection.ConsoleElement.ForegroundColor; // Apply the changes. Console.Clear(); } catch (ConfigurationErrorsException e) { Console.WriteLine("[Error exception: {0}]", e.ToString()); } // Display feedback. Console.WriteLine(); Console.WriteLine("Using OpenExeConfiguration(string)."); // Display the current configuration file path. Console.WriteLine("Configuration file is: {0}", config.FilePath); }
/// <summary> /// Retrieves the specified <see cref="ConfigurationSection"/> from the configuration file. /// </summary> /// <param name="sectionName">The section name.</param> /// <returns>The section, or <see langword="null"/> if it doesn't exist.</returns> protected override ConfigurationSection DoGetSection(string sectionName) { System.Configuration.Configuration configuration = GetConfiguration(); return(configuration.GetSection(sectionName) as ConfigurationSection); }
// </Snippet4> // <Snippet9> // Access a configuration file using mapping. // This function uses the OpenMappedExeConfiguration // method to access a new configuration file. // It also gets the custom ConsoleSection and // sets its ConsoleElement BackgroundColor and // ForegroundColor properties to green and red // respectively. Then it uses these properties to // set the console colors. public static void MapExeConfiguration() { // Get the application configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); Console.WriteLine(config.FilePath); if (config == null) { Console.WriteLine( "The configuration file does not exist."); Console.WriteLine( "Use OpenExeConfiguration to create the file."); } // Create a new configuration file by saving // the application configuration to a new file. string appName = Environment.GetCommandLineArgs()[0]; string configFile = string.Concat(appName, ".2.config"); config.SaveAs(configFile, ConfigurationSaveMode.Full); // Map the new configuration file. ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(); configFileMap.ExeConfigFilename = configFile; // Get the mapped configuration file config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None); // Make changes to the new configuration file. // This is to show that this file is the // one that is used. string sectionName = "consoleSection"; ConsoleSection customSection = (ConsoleSection)config.GetSection(sectionName); if (customSection == null) { customSection = new ConsoleSection(); config.Sections.Add(sectionName, customSection); } else { // Change the section configuration values. customSection = (ConsoleSection)config.GetSection(sectionName); } customSection.ConsoleElement.BackgroundColor = ConsoleColor.Green; customSection.ConsoleElement.ForegroundColor = ConsoleColor.Red; // Save the configuration file. config.Save(ConfigurationSaveMode.Modified); // Force a reload of the changed section. This // makes the new values available for reading. ConfigurationManager.RefreshSection(sectionName); // Set console properties using the // configuration values contained in the // new configuration file. Console.BackgroundColor = customSection.ConsoleElement.BackgroundColor; Console.ForegroundColor = customSection.ConsoleElement.ForegroundColor; Console.Clear(); Console.WriteLine(); Console.WriteLine("Using OpenMappedExeConfiguration."); Console.WriteLine("Configuration file is: {0}", config.FilePath); }
protected void WzdInstall_NextButtonClick(object sender, WizardNavigationEventArgs e) { switch (e.CurrentStepIndex) { case 0: this.InstallFileCheck(); return; case 1: { string connectionString = WebConfigurationManager.ConnectionStrings["Connection String"].ConnectionString; this.TxtDataSource.Text = connectionString.Split(new char[] { ';' })[0].Split(new char[] { '=' })[1]; this.TxtDataBase.Text = connectionString.Split(new char[] { ';' })[1].Split(new char[] { '=' })[1]; this.TxtUserID.Text = connectionString.Split(new char[] { ';' })[2].Split(new char[] { '=' })[1]; return; } case 2: { string str2 = "server=" + this.TxtDataSource.Text + ";database=" + this.TxtDataBase.Text + ";uid=" + this.TxtUserID.Text + ";pwd=" + this.TxtPassword.Text; try { SqlConnection connection = new SqlConnection(str2); connection.Open(); connection.Close(); this.HdnPassword.Value = this.TxtPassword.Text; } catch (SqlException) { this.LblCheckConnectString.Visible = true; e.Cancel = true; } break; } case 3: { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Config\Site.config"); this.TxtSiteTitle.Text = ReadSiteConfigElement(fileName, "SiteTitle"); this.TxtSiteUrl.Text = ReadSiteConfigElement(fileName, "SiteUrl"); this.TxtManageDir.Text = ReadSiteConfigElement(fileName, "ManageDir"); this.TxtSiteManageCode.Text = ReadSiteConfigElement(fileName, "SiteManageCode"); return; } case 4: { string connectString = "server=" + this.TxtDataSource.Text + ";database=" + this.TxtDataBase.Text + ";uid=" + this.TxtUserID.Text + ";pwd=" + this.HdnPassword.Value; string valueList = this.TxtSiteTitle.Text + ";" + this.TxtSiteUrl.Text + ";" + this.TxtManageDir.Text + ";" + this.TxtSiteManageCode.Text + ";" + base.Request.ApplicationPath; try { this.SetConfig(valueList); System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); AppSettingsSection section = (AppSettingsSection)configuration.GetSection("appSettings"); ConnectionStringsSection section2 = (ConnectionStringsSection)configuration.GetSection("connectionStrings"); section2.ConnectionStrings["Connection String"].ConnectionString = connectString; section.Settings["Version"].Value = ProductVersion; configuration.Save(); try { ChangeAdminPassword(connectString, this.TxtAdminPassword.Text.Trim()); } catch (Exception exception) { this.LblErrorMessage.Text = exception.Message; e.Cancel = true; } } catch { this.LblErrorMessage.Text = "配置信息没有写入,可能是因为Config配置文件下的AppSettings.config、ConnectionStrings.config及Site.config三个文件是只读文件!\r\n<br/>或者是它们的ASPNET(XP)或Network Service(Server)用户没有修改权限!"; e.Cancel = true; } break; } default: return; } }
/// <summary> /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with /// required current subscription. /// </summary> /// <param name="azureSubscription">Azure Subscription</param> public PSRecoveryServicesClient(IAzureProfile azureProfile) { System.Configuration.Configuration siteRecoveryConfig = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)siteRecoveryConfig.GetSection("appSettings"); string resourceNamespace = string.Empty; string resourceType = string.Empty; // Get Resource provider namespace and type from config only if Vault context is not set // (hopefully it is required only for Vault related cmdlets) if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) || string.IsNullOrEmpty(asrVaultCreds.ARMResourceType)) { if (appSettings.Settings.Count == 0) { resourceNamespace = "Microsoft.SiteRecovery"; // ProviderNameSpace for Production is taken as default resourceType = ARMResourceTypeConstants.SiteRecoveryVault; } else { resourceNamespace = null == appSettings.Settings["ProviderNamespace"] ? "Microsoft.SiteRecovery" : appSettings.Settings["ProviderNamespace"].Value; resourceType = null == appSettings.Settings["ResourceType"] ? ARMResourceTypeConstants.SiteRecoveryVault : appSettings.Settings["ResourceType"].Value; } Utilities.UpdateCurrentVaultContext(new ASRVaultCreds() { ResourceNamespace = resourceNamespace, ARMResourceType = resourceType }); } if (null == endPointUri) { if (appSettings.Settings.Count == 0) { endPointUri = azureProfile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager); } else { if (null == appSettings.Settings["RDFEProxy"]) { endPointUri = azureProfile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager); } else { // Setting Endpoint to RDFE Proxy if (null == ServicePointManager.ServerCertificateValidationCallback) { ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateErrorHandler; } endPointUri = new Uri(appSettings.Settings["RDFEProxy"].Value); } } } cloudCredentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(azureProfile.Context); this.recoveryServicesClient = AzureSession.ClientFactory.CreateCustomClient <SiteRecoveryVaultManagementClient>( asrVaultCreds.ResourceNamespace, asrVaultCreds.ARMResourceType, cloudCredentials, azureProfile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)); }
public TSection GetSection <TSection>(string sectionName) where TSection : ConfigurationSection { return((TSection)configuration.GetSection(sectionName)); }
public static void Main(string[] args) { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the section. string configPath = "system.web/caching/outputCacheSettings"; System.Web.Configuration.OutputCacheSettingsSection outputCacheSettings = (System.Web.Configuration.OutputCacheSettingsSection)webConfig.GetSection( configPath); // Get the profile collection. System.Web.Configuration.OutputCacheProfileCollection outputCacheProfiles = outputCacheSettings.OutputCacheProfiles; // </Snippet1> // <Snippet2> // Execute the Add method. System.Web.Configuration.OutputCacheProfile outputCacheProfile0 = new System.Web.Configuration.OutputCacheProfile("MyCacheProfile"); outputCacheProfile0.Location = System.Web.UI.OutputCacheLocation.Any; outputCacheProfile0.NoStore = false; outputCacheProfiles.Add(outputCacheProfile0); // Update if not locked. if (!outputCacheSettings.IsReadOnly()) { webConfig.Save(); } // </Snippet2> // <Snippet3> // Execute the Clear method. outputCacheProfiles.Clear(); // </Snippet3> // <Snippet4> // Get the profile with the specified index. System.Web.Configuration.OutputCacheProfile outputCacheProfile2 = outputCacheProfiles[0]; // </Snippet4> // <Snippet5> // Get the profile with the specified name. System.Web.Configuration.OutputCacheProfile outputCacheProfile3 = outputCacheProfiles["MyCacheProfile"]; // </Snippet5> // <Snippet6> // Get the key with the specified index. string theKey = outputCacheProfiles.GetKey(0).ToString(); // </Snippet6> // <Snippet7> // Remove the output profile with the specified index. outputCacheProfiles.RemoveAt(0); // </Snippet7> // <Snippet8> // Remove the output profile with the specified name. outputCacheProfiles.Remove("MyCacheProfile"); // </Snippet8> // <Snippet9> // Get the keys. object [] keys = outputCacheProfiles.AllKeys; // </Snippet9> // <Snippet10> // Execute the Set method. System.Web.Configuration.OutputCacheProfile outputCacheProfile = new System.Web.Configuration.OutputCacheProfile("MyCacheProfile"); outputCacheProfile.Location = System.Web.UI.OutputCacheLocation.Any; outputCacheProfile.NoStore = false; outputCacheProfiles.Set(outputCacheProfile); // Update if not locked. if (!outputCacheSettings.IsReadOnly()) { webConfig.Save(); } // </Snippet10> // <Snippet11> // Get the profile with the specified name. System.Web.Configuration.OutputCacheProfile outputCacheProfile4 = outputCacheProfiles.Get("MyCacheProfile"); // </Snippet11> // <Snippet12> // Get thge profile with the specified index. System.Web.Configuration.OutputCacheProfile outputCacheProfile5 = outputCacheProfiles.Get(0); // </Snippet12> }