public void Update_configuration_and_save() { //string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MvcInstaller.Tests.dll.config"); string path = @"C:\VSProjects\MvcInstaller\MvcInstaller.Tests\web.config"; //System.Configuration.Configuration configSection = ConfigurationManager.OpenExeConfiguration(path); System.Configuration.Configuration configSection = WebConfigurationManager.OpenWebConfiguration(path); if (configSection == null) { throw new InvalidOperationException("Configuration file not available."); } InstallerConfig config = Serializer <InstallerConfig> .Deserialize(AppDomain.CurrentDomain.BaseDirectory + @"\installer.config"); IConnectionStringComponent component = new ConnectionStringComponent(config); IConfigurationFactory factory = new ConfigurationFactory(component); factory.Execute(config, configSection); configSection.Save(); }
/// <summary> /// Set SINF path /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSinfPath_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtSinfPath.Text = dialog.SelectedPath; System.Configuration.Configuration config = WR.Utils.Config.GetConfig(); config.AppSettings.Settings.Remove("sinfPath"); config.AppSettings.Settings.Add("sinfPath", dialog.SelectedPath); config.Save(); WR.Utils.Config.Refresh(); DataCache.SinfPath = dialog.SelectedPath; } }
protected void btnEnable_Click(object sender, EventArgs args) { try { System.Configuration.Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); EngineSection engineConfiguration = (EngineSection)cfg.GetSection("n2/engine"); engineConfiguration.Globalization.Enabled = true; cfg.Save(); cvLanguageRoots.IsValid = Engine.Resolve <ILanguageGateway>().GetAvailableLanguages().GetEnumerator().MoveNext(); Initialize(); } catch (Exception ex) { Trace.Write(ex.ToString()); cvEnable.IsValid = false; } }
public void Remove(string fileName, string section) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException("fileName"); } if (string.IsNullOrEmpty(section)) { throw new ArgumentNullException("section"); } System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = fileName; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); if (config.Sections.Get(section) != null) { config.Sections.Remove(section); config.Save(); UpdateImplementation(fileName); } }
public static void SetParameter(string key, string value) { try { if (!string.IsNullOrEmpty(key)) { System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] == null) { config.AppSettings.Settings.Add(key, value); } else { config.AppSettings.Settings[key].Value = value; } config.Save(System.Configuration.ConfigurationSaveMode.Modified); System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } } catch { } }
public string this[string Key] { get { var setting = configObject.AppSettings.Settings[Key]; return(setting != null ? setting.Value : null); } set { var setting = configObject.AppSettings.Settings[Key]; if (setting != null) { setting.Value = value; } else { configObject.AppSettings.Settings.Add(Key, value); } configObject.Save(System.Configuration.ConfigurationSaveMode.Modified); } }
/// <summary> /// 设置ConnectionString连接字符串 /// </summary> public static void SetConnectionString(string Name, string ConnectionString, string ProviderName, bool Refresh = true) { System.Configuration.Configuration Config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); System.Configuration.ConnectionStringSettings ConnStrSettings = Config.ConnectionStrings.ConnectionStrings[Name]; if (ConnStrSettings != null) { ConnStrSettings.ConnectionString = ConnectionString; ConnStrSettings.ProviderName = ProviderName; } else { Config.ConnectionStrings.ConnectionStrings.Add(new System.Configuration.ConnectionStringSettings(Name, ConnectionString, ProviderName)); } Config.Save(System.Configuration.ConfigurationSaveMode.Modified); if (Refresh) { System.Configuration.ConfigurationManager.RefreshSection("connectionStrings"); } }
public static bool WriteAppSetting(string _sect, string _sett, string _value) { if (String.IsNullOrEmpty(_sect) || String.IsNullOrEmpty(_sett)) { return(false); } bool res = true; try { System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (config != null) { var sgroup = config.SectionGroups[APP_SETTINGS_GROUP_NAME]; if (sgroup != null) { var section = sgroup.Sections[_sect] as System.Configuration.ClientSettingsSection; if (section != null) { var sett = section.Settings.Get(_sett) as System.Configuration.SettingElement; if (sett != null) { sett.Value.ValueXml.InnerText = _value; section.Settings.Remove(sett); section.Settings.Add(sett); config.Save(System.Configuration.ConfigurationSaveMode.Modified); //Properties.Settings.Default.Reload(); } } } } } catch { res = false; } return(res); }
public static bool SetConfigValue(string key, string value) { try { System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] != null) { config.AppSettings.Settings[key].Value = value; } else { config.AppSettings.Settings.Add(key, value); } config.Save(System.Configuration.ConfigurationSaveMode.Modified); System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } catch { return(false); } return(true); }
internal void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings) { if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) { throw new ConfigurationErrorsException(System.SR.GetString("UserSettingsNotSupported")); } System.Configuration.Configuration userConfig = this.GetUserConfig(isRoaming); ClientSettingsSection section = this.GetConfigSection(userConfig, sectionName, true); if (section != null) { SettingElementCollection settings = section.Settings; foreach (DictionaryEntry entry in newSettings) { SettingElement element = settings.Get((string)entry.Key); if (element == null) { element = new SettingElement { Name = (string)entry.Key }; settings.Add(element); } StoredSetting setting = (StoredSetting)entry.Value; element.SerializeAs = setting.SerializeAs; element.Value.ValueXml = setting.Value; } try { userConfig.Save(); return; } catch (ConfigurationErrorsException exception) { throw new ConfigurationErrorsException(System.SR.GetString("SettingsSaveFailed", new object[] { exception.Message }), exception); } } throw new ConfigurationErrorsException(System.SR.GetString("SettingsSaveFailedNoSection")); }
/// <summary> /// app.config 节点添加 更新 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="encrypt">是否需要加密:true,加密;false,不需要加密</param> public static void WriteAppSetting(string key, string value, bool encrypt) { //key的值为空 则写key value if (String.IsNullOrEmpty(GetAppSetting(key))) { System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (encrypt) { configuration.AppSettings.Settings.Add(key, GetEncryptedValue(value)); } else { configuration.AppSettings.Settings.Add(key, value); } configuration.Save(System.Configuration.ConfigurationSaveMode.Modified); //refresh System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } //key 不为空 更新 value else { System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (encrypt) { configuration.AppSettings.Settings[key].Value = GetEncryptedValue(value); } else { configuration.AppSettings.Settings[key].Value = value; } configuration.Save(System.Configuration.ConfigurationSaveMode.Modified); //refresh System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } }
public static void UpdateAppConfig(string newKey, string newValue) { //��ȡ���������ļ� string assemblyConfigFile = Assembly.GetEntryAssembly().Location; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(assemblyConfigFile); bool exist = false; foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == newKey) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(newKey); } config.AppSettings.Settings.Add(newKey, newValue); config.Save(System.Configuration.ConfigurationSaveMode.Modified); System.Configuration.ConfigurationManager.RefreshSection("appSettings"); }
public void Update(ConnectionStringConfiguration connectionStringConfiguration) { if (connectionStringConfiguration == null) { throw new ArgumentNullException(nameof(connectionStringConfiguration)); } try { _config.ConnectionStrings.ConnectionStrings[connectionStringConfiguration.Name].ConnectionString = connectionStringConfiguration.ConnectionString; _config.ConnectionStrings.ConnectionStrings[connectionStringConfiguration.Name].ProviderName = connectionStringConfiguration.ProviderName; _config.Save(System.Configuration.ConfigurationSaveMode.Modified, true); System.Configuration.ConfigurationManager.RefreshSection("connectionStrings"); } catch (NullReferenceException ex) { throw new RepositoryLoadException(ex.Message, ex); } }
//*** change receivers public void Update(FtpConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } try { var ftpConfigurationSection = GetFtpSection(_configuration); ftpConfigurationSection.Host.Address = configuration.Uri; ftpConfigurationSection.Host.Port = configuration.Port; ftpConfigurationSection.Credentials.User = configuration.User; ftpConfigurationSection.Credentials.Password = configuration.Password; _configuration.Save(); } catch (NullReferenceException ex) { throw new RepositoryLoadException(ex.Message, ex); } }
static ComBoostAuthentication() { _Config = WebConfigurationManager.OpenWebConfiguration("~"); SystemWebSectionGroup system = (SystemWebSectionGroup)_Config.GetSectionGroup("system.web"); IsEnabled = system.Authentication.Mode == AuthenticationMode.Forms; if (!IsEnabled) return; if (!_Config.AppSettings.Settings.AllKeys.Contains("ComBoostAuthenticationKey")) { _Key = Guid.NewGuid().ToByteArray(); _Config.AppSettings.Settings.Add("ComBoostAuthenticationKey", Convert.ToBase64String(_Key)); _Config.Save(); } else { _Key = Convert.FromBase64String(_Config.AppSettings.Settings["ComBoostAuthenticationKey"].Value); } CookieDomain = system.Authentication.Forms.Domain; CookieName = system.Authentication.Forms.Name ?? "comboostauth"; CookiePath = system.Authentication.Forms.Path; LoginUrl = system.Authentication.Forms.LoginUrl; Timeout = system.Authentication.Forms.Timeout; }
/// <summary> /// 设定App值 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <returns>0:错误 1:修改 2:插入</returns> public static int SetAppValue(string key, string value) { // 参数空验证 if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value)) { return(0); } try { // 配置文件空验证 System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); if (config == null) { return(0); } int result = 0; if (config.AppSettings.Settings[key] != null) { config.AppSettings.Settings[key].Value = value; result = 1; } else { config.AppSettings.Settings.Add(key, value); result = 2; } config.Save(System.Configuration.ConfigurationSaveMode.Modified); return(result); } catch (Exception) { return(0); } }
//*** change recivers public void Update(SenderConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } try { var senderSection = GetSenderSection(_configuration); senderSection.Host.Address = configuration.Host; senderSection.Host.Port = configuration.Port; senderSection.Credentials.Login = configuration.SenderLogin; senderSection.Credentials.Password = configuration.SenderPassword; _configuration.Save(); } catch (NullReferenceException ex) { throw new RepositoryLoadException(ex.Message, ex); } }
/// <summary> /// Sets values to web configuration. /// Use this when saving multiple keys so a save is not called for each key. /// </summary> /// <param name="settings">The settings.</param> public static void SetValueToWebConfig(Dictionary <string, string> settings) { bool changed = false; System.Configuration.Configuration rockWebConfig = null; try { rockWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); } catch (Exception ex) { ExceptionLogService.LogException(ex, null); } foreach (var setting in settings) { if (System.Configuration.ConfigurationManager.AppSettings[setting.Key] != null) { rockWebConfig.AppSettings.Settings[setting.Key].Value = setting.Value; changed = true; } } try { if (changed) { rockWebConfig.Save(); } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); } }
private void btnOK_Click(object sender, System.EventArgs e) { #if !NET_1_1 if ( System.Configuration.ConfigurationManager.AppSettings["license"] != APPSETTINGS_LICENSE_IHAVEREADLINCENSE ) { System.Configuration.Configuration _config = System.Configuration.ConfigurationManager.OpenExeConfiguration( System.Configuration.ConfigurationUserLevel.None ); try { _config.AppSettings.Settings.Remove(APPSETTINGS_LICENSE); } catch { } _config.AppSettings.Settings.Add(APPSETTINGS_LICENSE, APPSETTINGS_LICENSE_IHAVEREADLINCENSE); _config.Save(); System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } #endif this.Close(); }
static void Main() { try { DataPhilosophiaeSection dps = cm.GetSection("DataPhilosophiaeSection") as DataPhilosophiaeSection; if (dps != null) { System.Console.WriteLine(dps.Stage.PathDir); foreach (DataStoreElement ds in dps.DataStores) { System.Console.WriteLine(ds.Name); System.Console.WriteLine(ds.LoadDefaultDatabaseOnly); System.Console.WriteLine(ds.LoadSystemObjects); System.Console.WriteLine(ds.WithFields); if (string.IsNullOrWhiteSpace(ds.PathDir)) { ds.PathDir = System.IO.Path.Combine(dps.Stage.PathDir, ds.Name); cm.Save(System.Configuration.ConfigurationSaveMode.Minimal, true); } System.Console.WriteLine(ds.PathDir); } } //DataStoreElement dse = new DataStoreElement( ); //cm.Save( System.Configuration.ConfigurationSaveMode.Minimal, false ); } catch (System.Configuration.ConfigurationErrorsException ex) { System.Console.WriteLine(ex.Message); } try { System.Configuration.ConnectionStringSettingsCollection settings = System.Configuration.ConfigurationManager.ConnectionStrings; if (settings != null) { foreach (System.Configuration.ConnectionStringSettings cs in settings) { System.Console.WriteLine(" Name:" + cs.Name); System.Console.WriteLine(" ProviderName:" + cs.ProviderName); System.Console.WriteLine("ConnectionString:" + cs.ConnectionString); } } } catch (System.Configuration.ConfigurationErrorsException ex) { System.Console.WriteLine(ex.Message); } { DataPhilosophiaeSection dps = cm.GetSection("DataPhilosophiaeSection") as DataPhilosophiaeSection; DataStoreElement ds = dps.DataStores[0]; System.Configuration.ConnectionStringSettingsCollection settings = System.Configuration.ConfigurationManager.ConnectionStrings; System.Configuration.ConnectionStringSettings cs = settings[ds.ConnectionStringName]; // ActiveQueryBuilder.Core.SyntaxProviderList syntaxProviderList = new ActiveQueryBuilder.Core.SyntaxProviderList( ); ActiveQueryBuilder.Core.SQLContext sc = new ActiveQueryBuilder.Core.SQLContext( ) { SyntaxProvider = new ActiveQueryBuilder.Core.AutoSyntaxProvider( ), MetadataProvider = new ActiveQueryBuilder.Core.OLEDBMetadataProvider { Connection = new System.Data.OleDb.OleDbConnection( ) { ConnectionString = cs.ConnectionString } } }; } { DataPhilosophiaeSection dps = cm.GetSection("DataPhilosophiaeSection") as DataPhilosophiaeSection; DataStoreElement ds = dps.DataStores[0]; System.Configuration.ConnectionStringSettingsCollection settings = System.Configuration.ConfigurationManager.ConnectionStrings; System.Configuration.ConnectionStringSettings cs = settings[ds.ConnectionStringName]; // ActiveQueryBuilder.Core.SyntaxProviderList syntaxProviderList = new ActiveQueryBuilder.Core.SyntaxProviderList( ); ActiveQueryBuilder.Core.SQLContext sc = new ActiveQueryBuilder.Core.SQLContext( ) { SyntaxProvider = new ActiveQueryBuilder.Core.SQLiteSyntaxProvider( ), MetadataProvider = new ActiveQueryBuilder.Core.SQLiteMetadataProvider( ) { Connection = new System.Data.SQLite.SQLiteConnection( ) { ConnectionString = cs.ConnectionString } } }; ActiveQueryBuilder.Core.MetadataLoadingOptions loadingOptions = sc.MetadataContainer.LoadingOptions; loadingOptions.LoadDefaultDatabaseOnly = ds.LoadDefaultDatabaseOnly == 1 ? true : false; loadingOptions.LoadSystemObjects = ds.LoadSystemObjects == 1 ? true : false; //loadingOptions.IncludeFilter.Types = MetadataType.Field; //loadingOptions.ExcludeFilter.Schemas.Add(“dbo”); sc.MetadataContainer.LoadAll(ds.WithFields == 1 ? true : false); } //TunnelSection ts = System.Configuration.ConfigurationManager.GetSection( "TunnelSection" ) as TunnelSection; TunnelSection ts = cm.GetSection("TunnelSection") as TunnelSection; int count1 = ts.Tunnels.Count; HostConfigElement hc = ts.Tunnels[0]; string sSHServerHostname = hc.SSHServerHostname; string username = hc.Username; TunnelCollection tunnels = hc.Tunnels; int count2 = tunnels.Count; TunnelConfigElement tce = tunnels[0]; string name = tce.Name; int localPort = tce.LocalPort; //ProductSettings productSettings = System.Configuration.ConfigurationManager.GetSection( "ProductSettings" ) as ProductSettings; //ConfigurationClassLoader x = System.Configuration.ConfigurationManager.GetSection( "Plugins" ) as ConfigurationClassLoader; // System.Configuration.ConfigurationSectionGroup a = cm.GetSectionGroup("DataStoreGroup"); System.Configuration.ConfigurationSectionCollection sections = a.Sections; int count = sections.Count; System.Configuration.ConfigurationSection get = sections.Get(0); // NewMethod( ); // System.Windows.Forms.Application.EnableVisualStyles( ); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); System.Windows.Forms.Application.Run(new Form1( )); }
/// <summary> /// Save the changes to the configuration file. /// </summary> /// <param name="configuration">The configuration that represents the file.</param> /// <param name="saveMode">The save mode.</param> public static void Save(System.Configuration.Configuration configuration, System.Configuration.ConfigurationSaveMode saveMode) { configuration.Save(saveMode); }
///<summary> ///加密配置文件中的AppSettings配置节 ///</summary> ///<param name="protect">true为加密,false为解密</param> public static void AppSettingProtection(bool protect) { //取得当前程序的执行路径 string pathName = Application.ExecutablePath; // Define the Dpapi provider name. string strProvider = "DataProtectionConfigurationProvider"; System.Configuration.Configuration oConfiguration = null; System.Configuration.AppSettingsSection oSection = null; try { // Open the configuration file and retrieve the connectionStrings section. oConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName); if (oConfiguration != null) { bool blnChanged = false; oSection = oConfiguration.GetSection("appSettings") as System.Configuration.AppSettingsSection; 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(); } } } } catch (System.Exception ex) { throw (ex); } finally { } }
///<summary> ///加密配置文件中的ConnectionString节 ///</summary> ///<param name="protect">true为加密,false为解密</param> public static void ConnectionStringProtection(bool protect) { //取得当前程序的执行路径 string pathName = Application.ExecutablePath; // 定义Dpapi提供程序的名称. string strProvider = "DataProtectionConfigurationProvider"; System.Configuration.Configuration oConfiguration = null; System.Configuration.ConnectionStringsSection oSection = null; try { // 打开配置文件,并取得connectionStrings配置节. 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; // 加密connectionStrings配置节. oSection.SectionInformation.ProtectSection(strProvider); } } else { if (oSection.SectionInformation.IsProtected) { blnChanged = true; // 解密connectionStrings配置节. oSection.SectionInformation.UnprotectSection(); } } } if (blnChanged) { // 如果connectionStrings配置节被更改,则强制保存它. oSection.SectionInformation.ForceSave = true; // 保存对connectionStrings配置节的更改. oConfiguration.Save(); } } } } catch (System.Exception ex) { throw (ex); } finally { } }
/// <summary> /// Sets the value for the specified key in the persistent storage (app.config, etc). /// <locDE><para />Schreibt den Wert für den angegebenen Schlüsselbegriff in den Konfigurationsspeicher (app.config, etc).</locDE> /// </summary> /// <param name="key">The key.<locDE><para />Der Schlüsselbegriff.</locDE></param> /// <param name="value">The value to store.<locDE><para />Der zu speichernde Wert.</locDE></param> public void SetValue(string key, string value) { if (string.IsNullOrWhiteSpace(key)) { return; } string writeInto = null; if (key.EndsWith("@appSettings")) { writeInto = "appSettings"; } else if (key.EndsWith("@applicationSettings")) { writeInto = "applicationSettings"; } else if (key.EndsWith("@userSettings")) { writeInto = "userSettings"; } else { GetValue(key, out writeInto); } #region TheAppName.Properties.Settings | userSettings if (writeInto.Equals("userSettings")) { try { //<userSettings> // <TheAppName.Properties.Settings> // <setting name="TheKey" serializeAs="String"> // <value>TheValue</value> // </setting> // </TheAppName.Properties.Settings> //</userSettings> #region Get Configuration instance System.Configuration.Configuration config = null; if (null != ConfigurationInstanceProvider) { config = ConfigurationInstanceProvider(); } else { config = System.Configuration.ConfigurationManager.OpenExeConfiguration(this.ConfigurationUserLevel); } #endregion System.Configuration.ClientSettingsSection clientSettingsSection = config.GetSection("userSettings/" + this.AppName + ".Properties.Settings") as System.Configuration.ClientSettingsSection; if (null != clientSettingsSection) { // Try to get existing entry System.Configuration.SettingElement settingElement = clientSettingsSection.Settings.Get(key); if (null != settingElement) { // Remove existing entry clientSettingsSection.Settings.Remove(settingElement); // Set new value settingElement.Value.ValueXml.InnerXml = value; clientSettingsSection.Settings.Add(settingElement); } else { // Create new entry settingElement = new System.Configuration.SettingElement(key, System.Configuration.SettingsSerializeAs.String); settingElement.Value = new System.Configuration.SettingValueElement(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); settingElement.Value.ValueXml = doc.CreateElement("value"); // Set new value settingElement.Value.ValueXml.InnerXml = value; clientSettingsSection.Settings.Add(settingElement); } // Save changes config.Save(this.ConfigurationSaveMode); System.Configuration.ConfigurationManager.RefreshSection("userSettings"); } } catch (Exception ex) { HandleException(ex); } return; } #endregion #region TheAppName.Properties.Settings | applicationSettings if (writeInto.Equals("applicationSettings")) { try { //<applicationSettings> // <TheAppName.Properties.Settings> // <setting name="TheKey" serializeAs="String"> // <value>TheValue</value> // </setting> // </TheAppName.Properties.Settings> //</applicationSettings> #region Get Configuration instance System.Configuration.Configuration config = null; if (null != ConfigurationInstanceProvider) { config = ConfigurationInstanceProvider(); } else { config = System.Configuration.ConfigurationManager.OpenExeConfiguration(this.ConfigurationUserLevel); } #endregion System.Configuration.ClientSettingsSection clientSettingsSection = config.GetSection("applicationSettings/" + this.AppName + ".Properties.Settings") as System.Configuration.ClientSettingsSection; if (null != clientSettingsSection) { // Try to get existing entry System.Configuration.SettingElement settingElement = clientSettingsSection.Settings.Get(key); if (null != settingElement) { // Remove existing entry clientSettingsSection.Settings.Remove(settingElement); // Set new value settingElement.Value.ValueXml.InnerXml = value; clientSettingsSection.Settings.Add(settingElement); } else { // Create new entry settingElement = new System.Configuration.SettingElement(key, System.Configuration.SettingsSerializeAs.String); settingElement.Value = new System.Configuration.SettingValueElement(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); settingElement.Value.ValueXml = doc.CreateElement("value"); // Set new value settingElement.Value.ValueXml.InnerXml = value; clientSettingsSection.Settings.Add(settingElement); } // Save changes config.Save(this.ConfigurationSaveMode); System.Configuration.ConfigurationManager.RefreshSection("applicationSettings"); } } catch (Exception ex) { HandleException(ex); } return; } #endregion #region appSettings //if (writeInto.Equals("appSettings")) { //<appSettings> // <add key="TheKey" value="TheValue" /> //</appSettings> // Does not save the new value into app.config file (only changed for app runtime): //System.Configuration.ConfigurationManager.AppSettings[key] = value; #region Get Configuration instance System.Configuration.Configuration config = null; if (null != ConfigurationInstanceProvider) { config = ConfigurationInstanceProvider(); } else { config = System.Configuration.ConfigurationManager.OpenExeConfiguration(this.ConfigurationUserLevel); } #endregion if (null == config.AppSettings.Settings[key]) { config.AppSettings.Settings.Add(key, value); } else { config.AppSettings.Settings[key].Value = value; } config.Save(this.ConfigurationSaveMode); System.Configuration.ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); //return; } #endregion }
internal void Save() { file.Save(System.Configuration.ConfigurationSaveMode.Modified); System.Configuration.ConfigurationManager.RefreshSection(file.AppSettings.SectionInformation.Name); }
/// <summary> /// Refresh authentication security key. /// </summary> public static void RefreshSecurityKey() { _Key = Guid.NewGuid().ToByteArray(); _Config.AppSettings.Settings.Add("ALEXFWAuthenticationKey", Convert.ToBase64String(_Key)); _Config.Save(); }
/// <summary> /// Updates the web.config as necessary to permit the generated domain service to be found. /// </summary> private void UpdateConfiguration() { // There is no work to do unless the user has selected some context // and chosen to expose the DomainService via [EnableClientAccess] or // to expose an OData endpoint. if (!this._isClientAccessEnabled && !this._isODataEndpointEnabled) { return; } // Get active project. Throws if not available. Project project = this.ActiveProject; // Get hierarchy. Throws if not available. IVsHierarchy vsHierarchy = this.GetVsHierarchy(project); IVsApplicationConfigurationManager cfgMgr = this.GetService(typeof(IVsApplicationConfigurationManager)) as IVsApplicationConfigurationManager; if (cfgMgr == null) { this.TerminateWizard(Resources.BusinessLogicClass_Error_No_ConfigurationManager); } // Return the current application's configuration file by using // the IVsApplicationConfiguration APIs. Make sure that the // instance that is returned is disposed of correctly in order // to clean up any event hooks or docdatas. // Note that this interface is aware of source control and text buffers, so it // works even if the file is currently open and modified. using (IVsApplicationConfiguration appCfg = cfgMgr.GetApplicationConfiguration(vsHierarchy, Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT)) { // Do not do anything unless the file already exists, else we will create an empty one if (appCfg != null && appCfg.FileExists()) { System.Configuration.Configuration cfg = appCfg.LoadConfiguration(); if (cfg != null) { WebConfigUtil webConfigUtil = new WebConfigUtil(cfg); // First check whether any work needs to done bool addHttpModule = webConfigUtil.DoWeNeedToAddHttpModule(); bool addModuleToWebServer = webConfigUtil.DoWeNeedToAddModuleToWebServer(); bool setAspNetCompatiblity = !webConfigUtil.IsAspNetCompatibilityEnabled(); bool setMultipleSiteBindingsEnabled = !webConfigUtil.IsMultipleSiteBindingsEnabled(); bool addValidationSection = webConfigUtil.DoWeNeedToValidateIntegratedModeToWebServer(); bool addODataEndpoint = this._isODataEndpointEnabled && !webConfigUtil.IsEndpointDeclared(BusinessLogicClassConstants.ODataEndpointName); // Modify the file only if we decided work is required if (addHttpModule || addModuleToWebServer || setAspNetCompatiblity || setMultipleSiteBindingsEnabled || addValidationSection || addODataEndpoint) { string domainServiceFactoryName = WebConfigUtil.GetDomainServiceModuleTypeName(); // Check the file out from Source Code Control if it exists. appCfg.QueryEditConfiguration(); if (addHttpModule) { webConfigUtil.AddHttpModule(domainServiceFactoryName); } if (addModuleToWebServer) { webConfigUtil.AddModuleToWebServer(domainServiceFactoryName); } if (setAspNetCompatiblity) { webConfigUtil.SetAspNetCompatibilityEnabled(true); } if (setMultipleSiteBindingsEnabled) { webConfigUtil.SetMultipleSiteBindingsEnabled(true); } if (addValidationSection) { webConfigUtil.AddValidateIntegratedModeToWebServer(); } if (addODataEndpoint) { string odataEndpointFactoryName = WebConfigUtil.GetODataEndpointFactoryTypeName(); webConfigUtil.AddEndpointDeclaration(BusinessLogicClassConstants.ODataEndpointName, odataEndpointFactoryName); } cfg.Save(); } } } } }
public static void UpdateAppSetting(string newVersion) { config.AppSettings.Settings.Remove("version"); config.AppSettings.Settings.Add("version", newVersion); config.Save(); }
private void btnOK_Click(object sender, EventArgs e) { if (cbxSpec.Checked) { double totalday = (dateTo.Value - dtDate.Value).TotalDays; if (totalday > 365) { dateTo.Focus(); MsgBoxEx.Info("Please select the time period within 365 days."); return; } else if (totalday < 0) { dtDate.Focus(); MsgBoxEx.Info("From date selection error."); return; } } if (cbxInterval.Checked && nudDay.Value <= 0) { MsgBoxEx.Info("date interval is greater than 0."); nudDay.Focus(); return; } System.Configuration.Configuration config = WR.Utils.Config.GetConfig(); config.AppSettings.Settings.Remove("notdone"); config.AppSettings.Settings.Add("notdone", (cbxNotdone.Checked ? "0" : "1")); config.AppSettings.Settings.Remove("theday"); config.AppSettings.Settings.Add("theday", (cbxDay.Checked ? "0" : "1")); config.AppSettings.Settings.Remove("lastday"); config.AppSettings.Settings.Add("lastday", (cbxLast.Checked ? "0" : "1")); config.AppSettings.Settings.Remove("specifiedday"); config.AppSettings.Settings.Add("specifiedday", (cbxSpec.Checked ? "0" : "1")); config.AppSettings.Settings.Remove("framday"); config.AppSettings.Settings.Add("framday", dtDate.Value.ToString("yyyyMMdd")); config.AppSettings.Settings.Remove("today"); config.AppSettings.Settings.Add("today", dateTo.Value.ToString("yyyyMMdd")); //设置间隔天 config.AppSettings.Settings.Remove("intervalDays"); config.AppSettings.Settings.Add("intervalDays", cbxInterval.Checked ? nudDay.Value.ToString() : "0"); config.AppSettings.Settings.Remove("duplicate_data_visible"); config.AppSettings.Settings.Add("duplicate_data_visible", (cbxFilter.Checked ? "0" : "1")); config.Save(); WR.Utils.Config.Refresh(); string done = WR.Utils.Config.GetAppSetting("notdone"); if (string.IsNullOrEmpty(done) || done != "1") { DataCache.UserInfo.notdone = true; } else { DataCache.UserInfo.notdone = false; } string theday = WR.Utils.Config.GetAppSetting("theday"); if (string.IsNullOrEmpty(theday) || theday != "1") { DataCache.UserInfo.theday = true; } else { DataCache.UserInfo.theday = false; } string lastday = WR.Utils.Config.GetAppSetting("lastday"); if (!string.IsNullOrEmpty(lastday) && lastday == "0") { DataCache.UserInfo.lastday = true; } else { DataCache.UserInfo.lastday = false; } string specifiedday = WR.Utils.Config.GetAppSetting("specifiedday"); if (!string.IsNullOrEmpty(specifiedday) && specifiedday == "0") { DataCache.UserInfo.specifiedday = true; string fromday = WR.Utils.Config.GetAppSetting("framday"); int day = 0; if (int.TryParse(fromday, out day)) { DataCache.UserInfo.fromday = day; } else { DataCache.UserInfo.fromday = int.Parse(DateTime.Today.ToString("yyyyMMdd")); } string today = WR.Utils.Config.GetAppSetting("today"); int tday = 0; if (int.TryParse(today, out tday)) { DataCache.UserInfo.today = tday; } else { DataCache.UserInfo.today = int.Parse(DateTime.Today.ToString("yyyyMMdd")); } } else { DataCache.UserInfo.specifiedday = false; } string intervalDays = WR.Utils.Config.GetAppSetting("intervalDays"); if (!string.IsNullOrEmpty(intervalDays)) { int idays = 0; if (int.TryParse(intervalDays, out idays)) { DataCache.UserInfo.IntervalDays = idays; } } string filterdata = WR.Utils.Config.GetAppSetting("duplicate_data_visible"); if (string.IsNullOrEmpty(filterdata) || filterdata != "1") { DataCache.UserInfo.FilterData = true; } else { DataCache.UserInfo.FilterData = false; } MsgBoxEx.Info("Save success, please refresh the data."); }
private void Login(string userid, string pwd) { IsysService service = sysService.GetService(); UserInfoEntity ent = service.Login(userid, pwd); if (ent.IsOK == 0) { DataCache.UserInfo = ent; LoadLocalSettings(DataCache.UserInfo); DataCache.CmnDict = service.GetCmn(""); DataCache.Tbmenus = service.GetMenuByUserId(userid); var msg = GetExamInfo(); if (!string.IsNullOrEmpty(msg)) { MsgBoxEx.Info(msg); return; } //加载数据 DataCache.RefreshCache(); if (this.InvokeRequired) { this.Invoke(new Action(() => { System.Configuration.Configuration config = WR.Utils.Config.GetConfig(); config.AppSettings.Settings.Remove("userid"); config.AppSettings.Settings.Add("userid", userid); config.Save(); WR.Utils.Config.Refresh(); frmMain.SetForm(); })); } else { System.Configuration.Configuration config = WR.Utils.Config.GetConfig(); config.AppSettings.Settings.Remove("userid"); config.AppSettings.Settings.Add("userid", userid); config.Save(); WR.Utils.Config.Refresh(); frmMain.SetForm(); } } else { string msg = MessageConst.frm_login_msg003; switch (ent.IsOK) { case -99: msg = MessageConst.frm_login_msg003; break; case -1: msg = MessageConst.const_msg001; break; case -2: msg = MessageConst.const_msg002; break; case -3: msg = MessageConst.const_msg003; break; case -4: msg = MessageConst.const_msg001; break; default: msg = MessageConst.const_msg001; break; } if (this.InvokeRequired) { this.Invoke(new Action(() => { MsgBoxEx.Info(msg); btnOK.Enabled = true; btnReset.Enabled = true; lblMsg.Visible = false; txtUser.Enabled = true; txtPwd.Enabled = true; txtPwd.Focus(); })); } else { MsgBoxEx.Info(msg); btnOK.Enabled = true; btnReset.Enabled = true; lblMsg.Visible = false; txtUser.Enabled = true; txtPwd.Enabled = true; txtPwd.Focus(); } } }
public void Save() { _config.Save(System.Configuration.ConfigurationSaveMode.Modified); }