Save() публичный Метод

public Save ( ) : void
Результат void
Пример #1
0
        ///<summary> 
        ///创建ConnectionString(如果存在,先删除再创建) 
        ///</summary> 
        ///<param name="config">Configuration实例</param>
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param>         
        public static Boolean CreateConnectionStringsConfig(Configuration config, string newName, string newConString, string newProviderName)
        {
            if (config == null && string.IsNullOrEmpty(newName) && string.IsNullOrEmpty(newConString) && string.IsNullOrEmpty(newProviderName))
            {
                return false;
            }

            bool isModified = false;
            //记录该连接串是否已经存在
            //如果要更改的连接串已经存在
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            { isModified = true; }

            //新建一个连接字符串实例
            ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName);

            // 如果连接串已存在,首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);

            return true;
        }
Пример #2
0
        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();
        }
Пример #3
0
 /// <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;
     }
 }
Пример #4
0
 private static void UpdateConfig(Configuration config)
 {
     // Save the configuration file.
     config.Save(ConfigurationSaveMode.Modified, true);
     // Force a reload of a changed section.
     ConfigurationManager.RefreshSection("appSettings");
 }
Пример #5
0
 /// <summary>
 /// Sample 
 /// Configuration configuration = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public static void UpdateAppSetting(Configuration configuration, string key, string value)
 {
     configuration.AppSettings.Settings[key].Value = value;
     configuration.AppSettings.SectionInformation.ForceSave = true;
     configuration.Save(ConfigurationSaveMode.Modified);
     ConfigurationManager.RefreshSection("appSettings");
 }
Пример #6
0
 private static void CrearArchivoConfig()
 {
     XmlTextWriter.Create(Assembly.GetExecutingAssembly().Location + ".config");
     _config =
         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     _config.Save();
 }
		/// <summary>
		/// Retrieves the current UserSettingsSection from the specified configuration, if none
		/// exists a new one is created.  If a previous version of the userSettings exists they
		/// will be copied to the UserSettingsSection.
		/// </summary>
		public static UserSettingsSection UserSettingsFrom(Configuration config)
		{
			UserSettingsSection settings = null;

			try { settings = (UserSettingsSection)config.Sections[SECTION_NAME]; }
			catch(InvalidCastException)
			{ config.Sections.Remove(SECTION_NAME); }

			if (settings == null)
			{
				settings = new UserSettingsSection();
				settings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
				settings.SectionInformation.RestartOnExternalChanges = false;
				settings.SectionInformation.Type = String.Format("{0}, {1}", typeof(UserSettingsSection).FullName, typeof(UserSettingsSection).Assembly.GetName().Name);

				UpgradeUserSettings(config, settings);

				config.Sections.Add(SECTION_NAME, settings);
			}
			else if (!config.HasFile)
				UpgradeUserSettings(config, settings);

			if (settings.IsModified())
			{
				try { config.Save(); }
				catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to save configuration."); }
			}

			return settings;
		}
Пример #8
0
        /// <summary>
        /// Clears configuration (app.config) of all settings.
        /// </summary>
        /// <param name="config">Configuration to be cleared.</param>
        public static void ClearConfiguration(Configuration config)
        {
            for (int i = config.Sections.Count - 1; i >= 0; i--)
            {
                ConfigurationSection section = config.Sections[i];

                // Ensure that this section came from the file we provided and not elsewhere, such as machine.config
                if (section.SectionInformation.IsDeclared || (section.ElementInformation.Source != null && section.ElementInformation.Source.Equals(config.FilePath)))
                {
                    string parentSectionName = section.SectionInformation.GetParentSection().SectionInformation.SectionName;
                    config.Sections.RemoveAt(i);
                    config.Save(ConfigurationSaveMode.Full, false);
                    ConfigurationManager.RefreshSection(parentSectionName);
                }
            }
            config.Save(ConfigurationSaveMode.Full, false);
        }
Пример #9
0
        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 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();
            }
        }
Пример #12
0
        public Config(string configPath)
        {
            CreateConfigDir(configPath);

            var configFile = Path.Combine(configPath, "config.xml");

            _config = GetFileConfig(configFile);

            Init(_config);

            _config.Save(ConfigurationSaveMode.Modified);
        }
Пример #13
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();
     }
 }
Пример #14
0
        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;
        }
Пример #15
0
        private static void Set(string property, string value, Configuration config)
        {
            if (config == null)
                return;

            var item = config.AppSettings.Settings[property];
            if (item == null)
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement(property, value));
            else
                item.Value = value;

            config.Save();
        }
Пример #16
0
 /// <summary>
 /// Write key value
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public static void SetValue(string key, string value)
 {
     config = ConfigAppSettingsto(ConfigAppSettings.configfile);
     if (config.AppSettings.Settings[key] == null)
     {
         config.AppSettings.Settings.Add(key, value);
     }
     else
     {
         config.AppSettings.Settings[key].Value = value;
     }
     config.Save(ConfigurationSaveMode.Modified);
     ConfigurationManager.RefreshSection("appSettings");//Reload new config file contents.
 }
Пример #17
0
 /// <summary>
 /// Updates/Saves the config added or modified using the --install option.
 /// </summary>
 private static void SaveConfig()
 {
     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     config.AppSettings.Settings.Remove("Hub.Port");
     config.AppSettings.Settings.Add("Hub.Port", ConfigManager.GetValue("Hub.Port"));
     config.AppSettings.Settings.Remove("Security.CertificateFile");
     config.AppSettings.Settings.Add("Security.CertificateFile", ConfigManager.GetValue("Security.CertificateFile"));
     config.AppSettings.Settings.Remove("Logger.LogFile");
     config.AppSettings.Settings.Add("Logger.LogFile", ConfigManager.GetValue("Logger.LogFile"));
     config.AppSettings.Settings.Remove("Hub.IP");
     config.AppSettings.Settings.Add("Hub.IP", ConfigManager.GetValue("Hub.IP"));
     config.Save(System.Configuration.ConfigurationSaveMode.Modified);
     ConfigurationManager.RefreshSection("appSettings");
     Console.WriteLine("Configuration saved.");
 }
Пример #18
0
        public static void Main(string[] args)
        {
            String provider = args[0];  // example: DataProtectionConfigurationProvider

            System.Configuration.Configuration machineConfig =
                System.Configuration.ConfigurationManager.OpenMachineConfiguration();
            ProtectedConfigurationSection pcSection =
                (System.Configuration.ProtectedConfigurationSection)machineConfig.GetSection("configProtectedData");
            string oldEncryptionProviderName = pcSection.DefaultProvider;

            Console.WriteLine("The default provider is currently: " + oldEncryptionProviderName);
            Console.WriteLine("Changing the default provider to: " + provider);
            pcSection.DefaultProvider = provider;
            machineConfig.Save();
        }
        public void CanReadAndWriteLoggingHandler()
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            fileMap.ExeConfigFilename = "test.exe.config";
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            config.Sections.Remove(ExceptionHandlingSettings.SectionName);
            config.Sections.Add(ExceptionHandlingSettings.SectionName, CreateSettings());
            config.Save(ConfigurationSaveMode.Full);
            config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            ExceptionHandlingSettings   settings = (ExceptionHandlingSettings)config.Sections[ExceptionHandlingSettings.SectionName];
            LoggingExceptionHandlerData data     = (LoggingExceptionHandlerData)settings.ExceptionPolicies.Get("test").ExceptionTypes.Get("test").ExceptionHandlers.Get("test");

            config.Sections.Remove(ExceptionHandlingSettings.SectionName);
            config.Save(ConfigurationSaveMode.Full);
            Assert.AreEqual("test", data.Name);
            Assert.AreEqual("cat1", data.LogCategory);
            Assert.AreEqual(false, data.UseDefaultLogger);
            Assert.AreEqual(1, data.EventId);
            Assert.AreEqual(TraceEventType.Error, data.Severity);
            Assert.AreEqual("title", data.Title);
            Assert.AreEqual(typeof(XmlExceptionFormatter), data.FormatterType);
            Assert.AreEqual(4, data.Priority);
        }
Пример #20
0
        private void SaveDBSettings()
        {
            Properties.Settings.Default.DBServer   = DBServer.Text;
            Properties.Settings.Default.DBData     = DBData.Text;
            Properties.Settings.Default.DBUser     = DBUser.Text;
            Properties.Settings.Default.DBPassword = DBPassword.Password;
            Properties.Settings.Default.Save();
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var    connectionString = (ConnectionStringsSection)config.GetSection("connectionStrings");
            string cs = $"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string={"\""}data source={DBServer.Text};initial catalog={DBData.Text};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework{"\""}";

            connectionString.ConnectionStrings["CompanyEntities"].ConnectionString = cs;
            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");
        }
Пример #21
0
 private static void UpdateConnectionString(string connectionString)
 {
     try
     {
         System.Configuration.Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         configFile.ConnectionStrings.ConnectionStrings.Clear();
         configFile.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(nameof(FocaContextDb), connectionString, "System.Data.SQLCLient"));
         configFile.Save(ConfigurationSaveMode.Modified);
         ConfigurationManager.RefreshSection(configFile.ConnectionStrings.SectionInformation.Name);
     }
     catch (ConfigurationErrorsException)
     {
         MessageBox.Show("The database connection string could not be saved to the configuration file.", "Unsaved connection string", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
 }
Пример #22
0
        private static void SetConfigValue(string key, string value)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
Пример #23
0
 /// <summary>
 /// 写入值
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public static void SetValue(string key, string value)
 {
     //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     if (config.AppSettings.Settings[key] == null)
     {
         config.AppSettings.Settings.Add(key, value);
     }
     else
     {
         config.AppSettings.Settings[key].Value = value;
     }
     config.Save(ConfigurationSaveMode.Modified);
     ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
 }
Пример #24
0
 public static void StartWithWindows()
 {
     if (ConfigurationManager.AppSettings["autoStart"] == "0")
     {
         RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
         regKey = regKey.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
         regKey.SetValue(@"AUTOMOTOR Backup", Application.ExecutablePath);
         regKey.Close();
         System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         config.AppSettings.Settings.Remove("autoStart");
         config.AppSettings.Settings.Add("autoStart", "1");
         ConfigurationManager.RefreshSection("appSettings");
         config.Save(ConfigurationSaveMode.Modified);
     }
 }
Пример #25
0
 public static void UpdateSqlVersionConfig()
 {
     System.Configuration.Configuration config =
         WebConfigurationManager.OpenWebConfiguration("~");
     if (config.AppSettings.Settings.AllKeys.Contains("SqlVersion"))
     {
         config.AppSettings.Settings["SqlVersion"].Value = DXInfo.Business.Helper.SqlVersion;
     }
     else
     {
         config.AppSettings.Settings.Add("SqlVersion", DXInfo.Business.Helper.SqlVersion);
     }
     config.Save(ConfigurationSaveMode.Modified, false);
     ConfigurationManager.RefreshSection("appSettings");
 }
Пример #26
0
        private void setHomeButton_Click(object sender, EventArgs e)
        {
            if (cellphoneText.Text.Length < 10)
            {
                MessageBox.Show("Invalid cell phone number", "Cell number Error");
                return;
            }
            if (workPhoneText.Text.Length < 10)
            {
                MessageBox.Show("Invalid work phone number", "Work number Error");
                return;
            }
            if (homePhoneText.Text.Length < 10)
            {
                MessageBox.Show("Invalid home phone number", "Cell number Error");
                return;
            }

            myCell = cellphoneText.Text;
            if (cellRadioButton.Checked == true)
            {
                myNumber = myCell;
            }
            myWork = workPhoneText.Text;
            if (workRadioButton.Checked == true)
            {
                myNumber = myWork;
            }
            myHome = homePhoneText.Text;
            if (homeRadioButton.Checked == true)
            {
                myNumber = myHome;
            }

            // save number settings to app data
            System.Configuration.Configuration cfg =
                ConfigurationManager.OpenExeConfiguration(configFile);
            cfg.AppSettings.Settings.Remove("myCell");
            cfg.AppSettings.Settings.Remove("myWork");
            cfg.AppSettings.Settings.Remove("myHome");
            cfg.AppSettings.Settings.Add("myCell", myCell);
            cfg.AppSettings.Settings.Add("myWork", myWork);
            cfg.AppSettings.Settings.Add("myHome", myHome);

            // Save the configuration file.
            cfg.Save(ConfigurationSaveMode.Full, true);
            MessageBox.Show("Numbers saved.", "My numbers saved");
        }
Пример #27
0
        static public void SaveUserSettingDefault(string clientSectionName, string settingName, object settingValue)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // find section group
            ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];

            if (group == null)
            {
                return;
            }

            // find client section
            ClientSettingsSection clientSection = group.Sections[clientSectionName] as ClientSettingsSection;

            if (clientSection == null)
            {
                return;
            }

            // find setting element
            SettingElement settingElement = null;

            foreach (SettingElement s in clientSection.Settings)
            {
                if (s.Name == settingName)
                {
                    settingElement = s;
                    break;
                }
            }
            if (settingElement == null)
            {
                return;
            }

            // remove the current value
            clientSection.Settings.Remove(settingElement);

            // change the value
            settingElement.Value.ValueXml.InnerText = settingValue.ToString();

            // add the setting
            clientSection.Settings.Add(settingElement);

            // save changes
            config.Save(ConfigurationSaveMode.Full);
        }
Пример #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, System.EventArgs e)
        {
            using (new LengthyOperation(this))
            {
                try
                {
                    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    // Sets preference settings
                    PreferenceConfigHandler preferenceHandler = (PreferenceConfigHandler)config.GetSection("PreferenceConfig");
                    preferenceHandler.SearchRecursivly   = chkSearchRecursivly.Checked;
                    preferenceHandler.FileTreeShowFiles  = chkShowFiles.Checked;
                    preferenceHandler.FileTreeShowHidden = chkShowHidden.Checked;
                    preferenceHandler.FileTreeShowSystem = chkShowSystem.Checked;

                    // Sets backup settings
                    BackupConfigHandler backupHandler = (BackupConfigHandler)config.GetSection("BackupConfig");
                    backupHandler.BackupDirectory = txtBackupDirectory.Text;
                    backupHandler.EnableBackup    = chkEnableBackup.Checked;

                    // Sets editor and compiler settings
                    EditorCompilerConfigHandler editorCompilerConfigHandler = (EditorCompilerConfigHandler)config.GetSection("EditorCompilerConfig");
                    editorCompilerConfigHandler.CompilerTypeName = txtCodeDomCompilerType.Text;
                    if (cbSimpleTemplate.SelectedItem.ToString().Equals(Resources.TEXT_NOT_SPECIFIED) ||
                        cbGTemplate.SelectedItem.ToString().Equals(Resources.TEXT_NOT_SPECIFIED) ||
                        cbSyntaxFile.SelectedItem.ToString().Equals(Resources.TEXT_NOT_SPECIFIED))
                    {
                        MessageBox.Show(Resources.TEXT_SCRIPT_MUST_SPECIFY,
                                        Resources.TEXT_ERROR,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);

                        // forbid closing
                        DialogResult = DialogResult.None;
                        return;
                    }
                    editorCompilerConfigHandler.SimpleTemplate = cbSimpleTemplate.SelectedItem.ToString();
                    editorCompilerConfigHandler.GTemplate      = cbGTemplate.SelectedItem.ToString();
                    editorCompilerConfigHandler.SyntaxFileName = cbSyntaxFile.SelectedItem.ToString();

                    config.Save(ConfigurationSaveMode.Full);
                    DialogResult = DialogResult.OK;
                }
                catch (Exception ex)
                {
                    ExceptionMessageBox.ShowDialog(ex, true);
                }
            }
        }
Пример #29
0
        static void Main(string[] args)
        {
            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the <sessionPageState> section.
            SessionPageStateSection sessionPageState =
                (SessionPageStateSection)configuration.GetSection(
                    "system.web/sessionPageState");

            // </Snippet1>

            // <Snippet2>

            // Get the history size.
            int historySize =
                sessionPageState.HistorySize;

            string msg = String.Format(
                "Current history size: {0}\n",
                historySize.ToString());

            Console.Write(msg);

            if (!sessionPageState.IsReadOnly())
            {
                // Double current history size.
                sessionPageState.HistorySize =
                    2 * sessionPageState.HistorySize;

                configuration.Save();

                historySize =
                    sessionPageState.HistorySize;

                msg = String.Format(
                    "New history size: {0}\n",
                    historySize.ToString());

                Console.Write(msg);
            }

            // </Snippet2>
        }
Пример #30
0
        public void AddMachineConfigurationInfo()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenMachineConfiguration();
            Debug.Assert(config != null, "Machine.Config returned null");
            ServiceModelSectionGroup sectionGroup = config.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;

            if (sectionGroup != null)
            {
                bool          channelEndpointElementExists = false;
                ClientSection clientSection = sectionGroup.Client;
                foreach (ChannelEndpointElement elem in clientSection.Endpoints)
                {
                    if (elem.Binding.Equals(BINDING_NAME, StringComparison.OrdinalIgnoreCase) && elem.Name.Equals(BINDING_SCHEME, StringComparison.OrdinalIgnoreCase) && elem.Contract.Equals("IMetadataExchange", StringComparison.OrdinalIgnoreCase))
                    {
                        channelEndpointElementExists = true;
                        break;
                    }
                }
                if (!channelEndpointElementExists)
                {
                    Debug.WriteLine("Adding ChannelEndpointElement for : " + BINDING_NAME);
                    ChannelEndpointElement elem = new ChannelEndpointElement();
                    elem.Binding  = BINDING_NAME;
                    elem.Name     = BINDING_SCHEME;
                    elem.Contract = "IMetadataExchange";
                    sectionGroup.Client.Endpoints.Add(elem);
                    Debug.WriteLine("Added ChannelEndpointElement for : " + BINDING_NAME);
                }

                if (!sectionGroup.Extensions.BindingElementExtensions.ContainsKey(BINDINGELEM_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDINGELEM_NAME, bindingElementExtensionType.FullName + "," + bindingElementExtensionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingElementExtensions.Add(ext);
                }

                if (!sectionGroup.Extensions.BindingExtensions.ContainsKey(BINDING_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDING_NAME, bindingSectionType.FullName + "," + bindingSectionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingExtensions.Add(ext);
                }

                config.Save();
            }
            else
            {
                throw new InstallException("Machine.Config doesn't contain system.serviceModel node");
            }
        }
Пример #31
0
        //<Snippet12>
        static void ForceDeclaration(
            ConfigurationSectionGroup sectionGroup)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            sectionGroup.ForceDeclaration();

            config.Save(ConfigurationSaveMode.Full);

            Console.WriteLine(
                "Forced declaration for the group: {0}",
                sectionGroup.Name);
        }
Пример #32
0
        public static void SaveConfig(string key, string value)
        {
            // Open App.Config of executable
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration
                    (ConfigurationUserLevel.None);

            // Add an Application Setting.
            config.AppSettings.Settings.Add(key, value);

            // Save the changes in App.config file.
            config.Save(ConfigurationSaveMode.Modified);

            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
        }
Пример #33
0
 /// <summary>
 /// 修改配置文件
 /// </summary>
 /// <param name="cname">The cname.</param>
 /// <param name="cvalue">The cvalue.</param>
 public static bool UpdateConfig(string cname, string cvalue, bool CreateKeyAuto)
 {
     try
     {
         GetConfigString(cname, "", CreateKeyAuto);
         System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         config.AppSettings.Settings[cname].Value = cvalue;
         config.Save(ConfigurationSaveMode.Modified);
         ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Пример #34
0
        public void Get_Config_Section()
        {
            System.Configuration.Configuration configSection = ConfigurationManager.OpenExeConfiguration(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MvcInstaller.UnitTests.dll.config"));
            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();
        }
Пример #35
0
 /// <summary>
 /// configuracion del epos desde codigo
 /// </summary>
 /// <param name="empresa"></param>
 /// <param name="e_pos"></param>
 /// <param name="localhost"></param>
 private void update_config(string empresa, string e_pos, string localhost)
 {
     try
     {
         System.Configuration.Configuration wConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap {
             ExeConfigFilename = @"D:\INTERFA\FEPERU\bata_proceso\ServiceWin_FE.exe.config"
         }, System.Configuration.ConfigurationUserLevel.None);
         wConfig.AppSettings.Settings["epos"].Value        = e_pos;
         wConfig.AppSettings.Settings["empresa"].Value     = empresa;
         wConfig.AppSettings.Settings["socket_host"].Value = localhost;
         wConfig.Save(ConfigurationSaveMode.Modified);
     }
     catch
     {
     }
 }
Пример #36
0
        public void SaveForAllServices(IService service)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service), "Parent service is expected, but null found.");
            }
            System.Configuration.Configuration configuration = this.OpenConfiguration();
            GeneratorSection section = configuration.GetSection("WCFGenerator") as GeneratorSection;

            section.ForAllRootService = new ServiceSettingsElement();
            this.ExportServicesToConfig(section.ForAllRootService, (ServiceSettingsElement)null, new List <IService>((IEnumerable <IService>) new IService[1]
            {
                service
            }));
            configuration.Save();
        }
Пример #37
0
        public static void AddDBConnString(ConnectionStringSettings setting)
        {
            try
            {
                System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.ConnectionStrings.ConnectionStrings.Add(setting);
                config.Save(ConfigurationSaveMode.Modified, true);
                ConfigurationManager.RefreshSection("connectionStrings");
            }
            catch (Exception e)
            {
                Util.Helper.Log(e);
            }
        }
        /// <summary>
        /// - hàm thực hiện lưu vào config, thông tin ChuyenCS
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        private bool SaveChuyenCSConfig(string Value)
        {
            try
            {
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.AppSettings.Settings["ChuyenCS"].Value = Value;
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 /// <summary>
 ///     Saves this instance.
 /// </summary>
 public void Save()
 {
     try
     {
         _config.Save(ConfigurationSaveMode.Full);
         ConfigurationManager.RefreshSection("appSettings");
     }
     catch (ConfigurationErrorsException cee)
     {
         throw;
     }
     catch (System.Exception ex)
     {
         throw;
     }
 }
Пример #40
0
        private void SetTracingFlag(bool tracingEnabled)
        {
            ConfigurationChangeFileWatcher.SetDefaultPollDelayInMilliseconds(100);
            SystemConfigurationSource.ResetImplementation(true);
            Logger.Reset();

            SysConfig.Configuration config = SysConfig.ConfigurationManager.OpenExeConfiguration(SysConfig.ConfigurationUserLevel.None);
            Logging.Configuration.LoggingSettings loggingSettings = config.GetSection(Logging.Configuration.LoggingSettings.SectionName) as Logging.Configuration.LoggingSettings;
            loggingSettings.TracingEnabled = tracingEnabled;
            config.Save();

            SysConfig.ConfigurationManager.RefreshSection(Logging.Configuration.LoggingSettings.SectionName);
            SystemConfigurationSource.Implementation.ConfigSourceChanged(string.Empty);

            Thread.Sleep(200);
        }
        public void TestRunCommand()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            config.AppSettings.Settings.Add("vixPath", @"C:\Program Files (x86)\VMware\VMware VIX");
            config.AppSettings.Settings.Add("vSphereHost", "vsphere-eng.quinton.com");
            config.AppSettings.Settings.Add("vSphereUser", "ENGDOM\\pyramiswebbuilder");
            config.AppSettings.Settings.Add("vSpherePass", "Gilbert93");

            config.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("appSettings");

            Console.WriteLine(VIXAPI.RunCommand("list"));
        }
Пример #42
0
        public static IConfigurationSource SaveSectionsAndGetConfigurationSource(LoggingSettings loggingSettings)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            fileMap.ExeConfigFilename = "test.exe.config";
            System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            rwConfiguration.Sections.Remove(LoggingSettings.SectionName);
            rwConfiguration.Sections.Add(LoggingSettings.SectionName, loggingSettings);

            File.SetAttributes(fileMap.ExeConfigFilename, FileAttributes.Normal);
            rwConfiguration.Save();
            rwConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            FileConfigurationSource.ResetImplementation(fileMap.ExeConfigFilename, false);
            return(new FileConfigurationSource(fileMap.ExeConfigFilename));
        }
Пример #43
0
        public void SerializeAndDeserializeAByteArray()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConverterSection section = new ConverterSection();

            section.ByteArray = new byte[] { 1, 2, 3, 4 };
            config.Sections.Add(sectionName, section);
            config.Save();

            config  = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            section = config.Sections[sectionName] as ConverterSection;
            Assert.IsNotNull(section);
            byte actual = 1;

            Assert.AreEqual(section.ByteArray[0], actual);
        }
Пример #44
0
        /* END BLOCK THAT READS
         **************************************************************
         **************************************************************
         * *************************************************************
         */



        /* BLOCK THAT WRITES
         **************************************************************
         **************************************************************
         * *************************************************************
         */
        public static void writeConfig(string key, string value)
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);



            //Write a new value
            config.AppSettings.Settings.Remove(key);
            config.AppSettings.Settings.Add(key, value);

            //Read the value
            MessageBox.Show(config.AppSettings.Settings[key].Value);
            //Save the configuration file.
            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
Пример #45
0
        private void directoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            fileMap.ExeConfigFilename = @"NadzornikServis.exe.config";
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            folderBrowserDialog1.SelectedPath = config.AppSettings.Settings["Path"].Value.ToString();
            folderBrowserDialog1.ShowDialog();
            config.AppSettings.Settings["Path"].Value = folderBrowserDialog1.SelectedPath.ToString();
            config.Save();
            //od 128-256. Manje od 128 su system reserved!
            if (nadzornikServis.Status == ServiceControllerStatus.Running)
            {
                nadzornikServis.ExecuteCommand(128);
            }
        }
Пример #46
0
        public static void AddUpdateAppSettings(string key, string value)
        {
            System.Configuration.Configuration _configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection    _settings   = _configFile.AppSettings.Settings;

            if (_settings[key] == null)
            {
                _settings.Add(key, value);
            }
            else
            {
                _settings[key].Value = value;
            }
            _configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(_configFile.AppSettings.SectionInformation.Name);
        }
Пример #47
0
Файл: Main.cs Проект: cjswin/SiK
		public AppLogic ()
		{
			// Get the current configuration file.
			config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
		
			// Look for our settings and add/create them if missing
			if (config.Sections [config_name] == null) {
				config_section = new ConfigSection ();
				config.Sections.Add (config_name, config_section);
				config_section.SectionInformation.ForceSave = true;
				config.Save (ConfigurationSaveMode.Full);
			}
			config_section = config.GetSection (config_name) as ConfigSection;

			// Hook up main window events
			win = new MainWindow ();
			win.MonitorEvent += show_monitor;
			win.UploadEvent += do_upload;
			win.LogEvent += log;
			win.QuitEvent += at_exit;
			
			// restore the last path that we uploaded
			win.FileName = config_section.lastPath;
			
			// restore the last port that we opened
			win.PortName = config_section.lastPort;
			
			// Create the intelhex loader
			ihex = new IHex ();
			ihex.LogEvent += log;
			
			// And the uploader
			upl = new Uploader ();
			upl.LogEvent += log;
			upl.ProgressEvent += win.set_progress;
			
			// Emit some basic help
			log ("Select a serial port and a .hex file to be uploaded, then hit Upload.\n");
			
			win.Show ();
		}
Пример #48
0
 public virtual void SaveConfiguration(Configuration config)
 {
     config.Save(ConfigurationSaveMode.Full);
     ConfigurationManager.RefreshSection(sectionName);
 }
Пример #49
0
        // 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.");
                }
            }
        }
Пример #50
0
		/// <summary>
		/// Stores the settings values for a given settings class.
		/// </summary>
        /// <param name="configuration">the configuration where the values will be stored</param>
		/// <param name="settingsClass">the settings class for which to store the values</param>
		/// <param name="dirtyValues">contains the values to be stored</param>
        public static void PutSettingsValues(SystemConfiguration configuration, Type settingsClass, Dictionary<string, string> dirtyValues)
		{
			var applicationScopedProperties = GetProperties(settingsClass, SettingScope.Application);
			var userScopedProperties = GetProperties(settingsClass, SettingScope.User);

			bool modified = false;
			if (applicationScopedProperties.Count > 0)
			{
				var sectionPath = new ConfigurationSectionPath(settingsClass, SettingScope.Application);
				var group = sectionPath.GroupPath.GetSectionGroup(configuration, true);
				modified = StoreSettings(group, sectionPath.SectionName, applicationScopedProperties, dirtyValues);
			}
			if (userScopedProperties.Count > 0)
			{
				var sectionPath = new ConfigurationSectionPath(settingsClass, SettingScope.User);
				var group = sectionPath.GroupPath.GetSectionGroup(configuration, true);
				if (StoreSettings(group, sectionPath.SectionName, userScopedProperties, dirtyValues))
					modified = true;
			}

			if (modified)
				configuration.Save(ConfigurationSaveMode.Minimal, true);
		}
Пример #51
0
		public static void RemoveSettingsValues(SystemConfiguration configuration, Type settingsClass)
		{
			var sectionPath = new ConfigurationSectionPath(settingsClass, SettingScope.Application);
			ConfigurationSectionGroup group = configuration.GetSectionGroup(sectionPath.GroupPath);
			if (group != null)
				group.Sections.Remove(sectionPath.SectionName);

			sectionPath = new ConfigurationSectionPath(settingsClass, SettingScope.User);
			group = configuration.GetSectionGroup(sectionPath.GroupPath);
			if (group != null)
				group.Sections.Remove(sectionPath.SectionName);

			configuration.Save(ConfigurationSaveMode.Minimal, true);
		}
Пример #52
0
        public void SaveConfig(Configuration config)
        {
            RemotingManager.ShutdownTargetApplication();

            // check if session expired
            if (String.IsNullOrEmpty(ApplicationPath) || String.IsNullOrEmpty((string)Session[APP_PHYSICAL_PATH])) {
                Server.Transfer("~/home2.aspx");
            }

            config.Save(ConfigurationSaveMode.Minimal);
        }
Пример #53
0
 private void InitConfig()
 {
     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.config");
     _Config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
     _ConfigSection = _Config.Sections["Scheduler"] as SchedulerSection;
     if (_ConfigSection == null)
     {
         _ConfigSection = new SchedulerSection();
         _Config.Sections.Add("Scheduler", _ConfigSection);
         _ConfigSection = _Config.GetSection("Scheduler") as SchedulerSection;
         _ConfigSection.SectionInformation.ForceSave = false;
         _Config.Save(ConfigurationSaveMode.Full);
     }
 }
Пример #54
0
        // Enable or disable replace function in web.config
        public virtual void SetReplaceFunctionFeature(string filePath, bool includeWcfDataServicesGroupInWebConfig, bool replaceFunctionEnabled)
        {
#if !ClientSKUFramework

            this.configFile = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(filePath, "Web.Config") };
            this.config = ConfigurationManager.OpenMappedExeConfiguration(this.configFile, ConfigurationUserLevel.None);

            this.config.SectionGroups.Remove("wcfDataServices");

            if (includeWcfDataServicesGroupInWebConfig)
            {
                DataServicesSectionGroup dataServicesSectionGroup = new DataServicesSectionGroup();
                this.config.SectionGroups.Add("wcfDataServices", dataServicesSectionGroup);

                DataServicesFeaturesSection dataServicesFeaturesSection = new DataServicesFeaturesSection();
                dataServicesSectionGroup.Sections.Add("features", dataServicesFeaturesSection);

                dataServicesFeaturesSection.ReplaceFunction.Enable = replaceFunctionEnabled;
            }

            config.Save();
#endif
        }
Пример #55
0
        public TestEasyConfig(string workingDir)
        {
            if (string.IsNullOrEmpty(workingDir))
            {
                workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
            }

            var fileMap = new ExeConfigurationFileMap
                {
                    ExeConfigFilename = Path.Combine(workingDir, ConfigTestsuite),
                    LocalUserConfigFilename = Path.Combine(workingDir, ConfigContext)
                };

            // try to find default.config
            var toolsPath = workingDir; // first try current directory
            if (!File.Exists(Path.Combine(toolsPath, ConfigDefault)))
            {
                // then try some custom path
                toolsPath = Environment.ExpandEnvironmentVariables(TestEasySupportEnvVar);
                if (string.IsNullOrEmpty(toolsPath) || toolsPath.Equals(TestEasySupportEnvVar))
                {
                    // finally use hardcoded - default location that we use internally
                    toolsPath = ConfigurationManager.AppSettings[TestEasySupportKey];
                }
            }

            var defaultConfigPath = Path.Combine(toolsPath ?? "", ConfigDefault);
            if (File.Exists(defaultConfigPath))
            {
                fileMap.MachineConfigFilename = defaultConfigPath;
            }
            else
            {
                // if default.config is not found, then sections in testsuite.config are undefined,
                // thus we need to define them here to unblock a user (since all settings also can
                // be specified in testsuite configs if users would like that)
                _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                // add sections to config (users may forget to add them)          
                AddSafeSection("webServer", new WebServerSection());
                AddSafeSection("client", new ClientSection());
                AddSafeSection("azure", new AzureSection());
                AddSafeSection("tools", new ToolsSection());

                _configuration.Save();
            }

            // reopen config and reparse it
            _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);          

            SetEnvironmentVariables();            
        }
Пример #56
0
 private void SaveConfiguration(Configuration configuration)
 {
     configuration.Save(ConfigurationSaveMode.Modified, true);
 }
 // sets a config option from conf, save should be true if you want to save instantly
 public static void SetConfigurationOption(Configuration conf, string key, string value, bool save)
 {
     if (conf.AppSettings.Settings[key] != null)
         conf.AppSettings.Settings[key].Value = value;
     else
         conf.AppSettings.Settings.Add(key, value);
     if (save)
         conf.Save(ConfigurationSaveMode.Modified);
 }
Пример #58
0
		public static WindowSettings GetRoamingConfiguration(out SysConfig config)
		{
			// Define the custom section to add to the
			// configuration file.
			string sectionName = "windowSettings";
			WindowSettings currentSection = null;

			// Get the roaming configuration 
			// that applies to the current user.
			SysConfig roamingConfig =
				ConfigurationManager.OpenExeConfiguration(
				 ConfigurationUserLevel.PerUserRoamingAndLocal);

			// Map the roaming configuration file. This
			// enables the application to access 
			// the configuration file using the
			// System.Configuration.Configuration class
			ExeConfigurationFileMap configFileMap =
				new ExeConfigurationFileMap();
			configFileMap.ExeConfigFilename =
				roamingConfig.FilePath;

			// Get the mapped configuration file.
			config =
				ConfigurationManager.OpenMappedExeConfiguration(
					configFileMap, ConfigurationUserLevel.None);

			try
			{
				currentSection =
						 (WindowSettings)config.GetSection(
							 sectionName);

				// Synchronize the application configuration
				// if needed. The following two steps seem
				// to solve some out of synch issues 
				// between roaming and default
				// configuration.
				//config.Save(ConfigurationSaveMode.Full);

				// Force a reload of the changed section, 
				// if needed. This makes the new values available 
				// for reading.
				//ConfigurationManager.RefreshSection(sectionName);

				if (currentSection == null)
				{
					// Create a custom configuration section.
					currentSection = new WindowSettings();

					// Define where in the configuration file 
					// hierarchy the associated 
					// configuration section can be declared.
					// The following assignment assures that 
					// the configuration information can be 
					// defined in the user.config file in the 
					// roaming user directory. 
					currentSection.SectionInformation.AllowExeDefinition =
						ConfigurationAllowExeDefinition.MachineToLocalUser;

					// Allow the configuration section to be 
					// overridden by lower-level configuration files.
					// This means that lower-level files can contain
					// the section (use the same name) and assign 
					// different values to it as done by the
					// function GetApplicationConfiguration() in this
					// example.
					currentSection.SectionInformation.AllowOverride =
						true;
					// Add configuration information to 
					// the configuration file.
					config.Sections.Add(sectionName, currentSection);

					currentSection.StartupDirectory = new StringConfigElement();
					currentSection.ImageViewFullScreen = new BoolConfigElement();
					currentSection.MainViewFullScreen = new BoolConfigElement();

					currentSection.ImageViewHeight = new IntConfigElement() { Value = 800 };
					currentSection.ImageViewWidth = new IntConfigElement() { Value = 800 };
					currentSection.MainViewHeight = new IntConfigElement() { Value = 800 };
					currentSection.MainViewWidth = new IntConfigElement() { Value = 800 };

				}
				config.Save(ConfigurationSaveMode.Modified);
				// Force a reload of the changed section. This 
				// makes the new values available for reading.
				ConfigurationManager.RefreshSection(
					sectionName);

				return currentSection;
			}
			catch (ConfigurationErrorsException e)
			{
				System.Diagnostics.Debug.WriteLine("[Exception error: {0}]",
						e.ToString());
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("[Exception error: {0}]",
						e.ToString());
			}
			return null;
		}
Пример #59
0
        internal TestEasyConfig(object dummy)
        {
            var workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";

            var fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = Path.Combine(workingDir, ConfigTestsuite),
                LocalUserConfigFilename = Path.Combine(workingDir, ConfigContext)
            };

            // try to find default.config
            var toolsPath = workingDir; // first try current directory
            var defaultConfigPath = Path.Combine(toolsPath ?? "", ConfigDefault);
            if (File.Exists(defaultConfigPath))
            {
                fileMap.MachineConfigFilename = defaultConfigPath;
            }
            else
            {
                // if default.config is not found, then sections in testsuite.config are undefined,
                // thus we need to define them here to unblock a user (since all settings also can
                // be specified in testsuite configs if users would like that)
                _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                // add sections to config (users may forget to add them)          
                AddSafeSection("webServer", new WebServerSection());
                AddSafeSection("client", new ClientSection());
                AddSafeSection("azure", new AzureSection());
                AddSafeSection("tools", new ToolsSection());

                _configuration.Save();
            }

            // reopen config and reparse it
            _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            SetEnvironmentVariables();            
        }
Пример #60
0
        private static void GenerateEnvironmentConfiguration(Configuration envConfig, Configuration mainConfig)
        {
            // Connection strings
            foreach (ConnectionStringSettings connectionString in envConfig.ConnectionStrings.ConnectionStrings)
            {
                if (connectionString.Name == "LocalSqlServer") continue;
                mainConfig.ConnectionStrings.ConnectionStrings[connectionString.Name].ConnectionString =
                    connectionString.ConnectionString;
            }

            // app settings
            foreach (KeyValueConfigurationElement setting in envConfig.AppSettings.Settings)
            {
                mainConfig.AppSettings.Settings[setting.Key].Value = setting.Value;
            }

            // applicationSettings
            var group = envConfig.GetSectionGroup("applicationSettings");
            if (group != null)
            {
                foreach (ConfigurationSection section in group.Sections)
                {
                    if (!(section is ClientSettingsSection)) continue;

                    var s = (ClientSettingsSection)section;

                    var mainGroup = mainConfig.GetSectionGroup("applicationSettings");
                    if (mainGroup == null)
                    {
                        mainConfig.SectionGroups.Add("applicationSettings", group);
                        break;
                    }

                    var mainS = mainGroup.Sections.Get(s.SectionInformation.Name) as ClientSettingsSection;
                    if (mainS == null)
                    {
                        mainGroup.Sections.Add(s.SectionInformation.Name, s);
                    }
                    else
                    {
                        foreach (SettingElement setting in s.Settings)
                        {
                            var toRemove = mainS.Settings.Get(setting.Name);
                            if (toRemove != null)
                            {
                                mainS.Settings.Remove(toRemove);
                            }

                            mainS.Settings.Add(setting);
                        }
                    }
                }
            }

            mainConfig.Save();
        }