public static bool UpdateSetting(string key, string value) { try { 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); return(true); } catch (ConfigurationErrorsException) { return(false); } }
/// <summary> /// Returns merged settings collection /// </summary> private KeyValueConfigurationCollection Merge(List <String> paths) { var mergedSettings = new KeyValueConfigurationCollection(); foreach (var path in paths) { var settings = GetApplicationSettingsFromDirectory(path); if (settings == null) { continue; } foreach (var key in settings.AllKeys) { var value = settings[key].Value; mergedSettings.Remove(key); mergedSettings.Add(key, value); } } return(mergedSettings); }
static async Task Main() { string token = ConfigurationManager.AppSettings["token"]; if (token == null) { Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = configFile.AppSettings.Settings; Console.Write("Token: "); token = Console.ReadLine(); settings.Add("token", token); configFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name); } Client client = new(new ClientConfig { Identify = { Token = token, Intents = IdentifyIntent.Default }, Logger = { Level = LoggingLevel.Info }, }); client.Ready += Client_Ready; client.GuildCreate += Client_GuildCreate; client.MessageCreate += Client_MessageCreate; client.MessageUpdate += Client_MessageUpdate; client.MessageDelete += Client_MessageDelete; await client.Login(); }
/// <summary> /// App.config 에서 strKey에 strValue 내용을 설정함 /// </summary> /// <param name="strKey">설정할 키값</param> /// <param name="strValue">해당 키값에 넣을 데이터</param> /// <returns>성공 유무</returns> public static bool SetAppConfig(string strKey, string strValue) { bool bResult; Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection configCollection = config.AppSettings.Settings; try { configCollection.Remove(strKey); configCollection.Add(strKey, strValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); bResult = true; } catch { bResult = false; } return(bResult); }
public static void AddOrUpdateAppSettings(string key, string value) { try { 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); } catch (ConfigurationErrorsException) { Console.WriteLine("Error writing app settings"); } }
public AppDelegate() { PrepareCache(); ExtractImages(); controller = new MonodocDocumentController(); // Some UI feature we use rely on Lion or better, so special case it try { var version = new NSDictionary("/System/Library/CoreServices/SystemVersion.plist"); var osxVersion = Version.Parse(version.ObjectForKey(new NSString("ProductVersion")).ToString()); isOnLion = osxVersion.Major == 10 && osxVersion.Minor >= 7; } catch {} // Load documentation var args = Environment.GetCommandLineArgs(); IEnumerable <string> extraDocs = null, extraUncompiledDocs = null; if (args != null && args.Length > 1) { var extraDirs = args.Skip(1); extraDocs = extraDirs .Where(d => d.StartsWith("+")) .Select(d => d.Substring(1)) .Where(d => Directory.Exists(d)); extraUncompiledDocs = extraDirs .Where(d => d.StartsWith("@")) .Select(d => d.Substring(1)) .Where(d => Directory.Exists(d)); } if (extraUncompiledDocs != null) { foreach (var dir in extraUncompiledDocs) { RootTree.AddUncompiledSource(dir); } } if (ConfigurationManager.AppSettings == null) { Logger.Log("Setting default settings because ConfigurationManager.AppSettings is null"); var keyValueConfigurationCollection = new KeyValueConfigurationCollection(); keyValueConfigurationCollection.Add("docPath", "/Library/Frameworks/Mono.framework/Versions/Current/lib/monodoc/"); keyValueConfigurationCollection.Add("docExternalPath", ""); typeof(Config).GetField("exeConfig", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, keyValueConfigurationCollection); Lucene.Net.Support.AppSettings.Set("java.version", ""); Lucene.Net.Support.AppSettings.Set("java.vendor", ""); } Root = RootTree.LoadTree(); if (extraDocs != null) { foreach (var dir in extraDocs) { Root.AddSource(dir); } } var macDocPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "macdoc"); if (!Directory.Exists(macDocPath)) { Directory.CreateDirectory(macDocPath); } var helpSources = Root.HelpSources .Cast <HelpSource> () .Where(hs => !string.IsNullOrEmpty(hs.BaseFilePath) && !string.IsNullOrEmpty(hs.Name)) .Select(hs => Path.Combine(hs.BaseFilePath, hs.Name + ".zip")) .Where(File.Exists); IndexUpdateManager = new IndexUpdateManager(helpSources, macDocPath); BookmarkManager = new BookmarkManager(macDocPath); }
private static KeyValueConfigurationCollection GetConfiguration() { var args = Environment.GetCommandLineArgs(); var opts = new Dictionary <string, string>(); string configFile = null; KeyValueConfigurationCollection settings = null; for (var i = 1; i < args.Length - 1; ++i) { var opt = args[i]; if (opt[0] != '/') { break; } // analyze options var optname = opt.Substring(1); switch (optname) { case "ConfigFile": configFile = args[i + 1]; break; default: opts.Add(optname, args[i + 1]); break; } ++i; } // load different config file if (configFile != null) { string configPath = Path.Combine(Environment.CurrentDirectory, configFile); try { // Map the new configuration file. var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configPath }; // Get the mapped configuration file var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); settings = ((AppSettingsSection)config.GetSection("appSettings")).Settings; } catch (Exception ex) { Console.WriteLine("Could not load config file {0}, reason: {1}", configPath, ex.Message); } } if (settings == null) { settings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings; } // override config options with options from command line foreach (var pair in opts) { settings.Remove(pair.Key); settings.Add(pair.Key, pair.Value); } return(settings); }
private void btnSave_Click(object sender, EventArgs e) { string twitter = txtTwitter.Text; int speed = Convert.ToInt32(nudSpeed.Value); string speedMult = cmbSpeed.Text; int speedAvarage = Convert.ToInt32(nudSpeedAvarage.Value); int speedMinimum = Convert.ToInt32(nudSpeedMinimum.Value); int interval = Convert.ToInt32(nudInterval.Value); string consumerKey = txtConsumerKey.Text; string consumerSecret = txtConsumerSecret.Text; string accessToken = txtAccessToken.Text; string accessTokenSecret = txtAccessTokenSecret.Text; if (speedMinimum > speedAvarage) { MessageBox.Show("A velocidade mínima não pode ser maior que a velocidade média"); return; } else if (twitter.Length > 25) { MessageBox.Show("O Twitter pode ter no maximo 25 caracteres"); return; } if (speedMult == "Mb/s") { speed *= 1024; } Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = configFile.AppSettings.Settings; if (settings["TWITTER"] == null) { settings.Add("TWITTER", twitter); } else { settings["TWITTER"].Value = twitter; } if (settings["SPEED"] == null) { settings.Add("SPEED", speed.ToString()); } else { settings["SPEED"].Value = speed.ToString(); } if (settings["SPEED_AVG"] == null) { settings.Add("SPEED_AVG", speedAvarage.ToString()); } else { settings["SPEED_AVG"].Value = speedAvarage.ToString(); } if (settings["SPEED_MIN"] == null) { settings.Add("SPEED_MIN", speedMinimum.ToString()); } else { settings["SPEED_MIN"].Value = speedMinimum.ToString(); } if (settings["INTERVAL"] == null) { settings.Add("INTERVAL", interval.ToString()); } else { settings["INTERVAL"].Value = interval.ToString(); } if (settings["CONSUMER_KEY"] == null) { settings.Add("CONSUMER_KEY", consumerKey); } else { settings["CONSUMER_KEY"].Value = consumerKey; } if (settings["CONSUMER_SECRET"] == null) { settings.Add("CONSUMER_SECRET", consumerSecret); } else { settings["CONSUMER_SECRET"].Value = consumerSecret; } if (settings["ACCESS_TOKEN"] == null) { settings.Add("ACCESS_TOKEN", accessToken); } else { settings["ACCESS_TOKEN"].Value = accessToken; } if (settings["ACCESS_TOKEN_SECRET"] == null) { settings.Add("ACCESS_TOKEN_SECRET", accessTokenSecret); } else { settings["ACCESS_TOKEN_SECRET"].Value = accessTokenSecret; } try { configFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name); MessageBox.Show("As configurações foram salvas com sucesso"); } catch (Exception ex) { MessageBox.Show("Não foi possível salvar as configurações"); } this.Close(); }
/// <summary> /// Removes the specified key if it already exists and adds the new given value. /// </summary> /// <param name="key">Key to add to the settings</param> /// <param name="value">Value linked to this key</param> public static void Set(String key, String value) { appSettings.Remove(key); appSettings.Add(key, value); appConfiguration.Save(ConfigurationSaveMode.Minimal); }
public void SetSetting(string key, string value) { _settings.Remove(key); _settings.Add(key, value); Save(); }
private static void replaceSetting(KeyValueConfigurationCollection appSettings, string key, string value) { appSettings.Remove(key); appSettings.Add(key, value); }
protected override void SetSetting(string key, string valueString) { settings.Remove(key); settings.Add(key, valueString); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection Settings = Config.AppSettings.Settings; if (Settings["Certificate"] == null) { //Change this to include full address depending on platform/environment. Settings.Add("Certificate", "selfsigned.cer"); } else { Settings["Certificate"].Value = "selfsigned.cer"; } if (Settings["AccountDatasource"] == null) { Settings.Add("AccountsDatasource", "C:\\Accounts.db"); } else { Settings["AccountDatasource"].Value = "C:\\Accounts.db"; } Config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(Config.AppSettings.SectionInformation.Name); Console.WriteLine("Donald Trump has Tiny Hands, a TSO Server Emulator, v. 1.0"); Console.WriteLine("Creating SQLite Database..."); if (!DatabaseFacade.Initialize()) { Console.ReadLine(); Environment.Exit(0); } Console.WriteLine("Success!\n Creating tables..."); if (!DatabaseFacade.CreateTables()) { Console.ReadLine(); Environment.Exit(0); } Console.WriteLine("Success!\n Creating master account..."); DatabaseFacade.CreateAccount(1, "asdf", "hjkl", "2002", 10, "1337", "0", "0"); DatabaseFacade.CreateCityserver(1, "Alphaville", 49, 1, "Up", 2, 0, "Afr0", "Welcome!", "This server is hosted by Donald Trump Has Small Hands!"); //Test... DatabaseFacade.CreateAvatar(1337, "Donald Trump", "", 5000, 0, 10, 10, "AlphaVille", 0x1011, 0x1213, 0x1415, 0x1617, 0x1819, 0x1a1b, 0x1c1d, 0x1e1f, 0x2021, 0x2223, 0x2425, 0x2627, 0x00, 0x00, 5000, /*"0x000003A10000000D"*/ "0x0000018D0000000D", /*"0x0000024A0000000D"*/ "0x0000030000000D", "0x000002B70000000D", "0x000002B60000000D", "0x0000024E0000000D", 0, 0x84858687, 0x88898A8B, 0x8C8D8E8F, 0xbbbc); Console.WriteLine("Success!"); m_SSLSocket = new SslSocketMonitor(49100); //This is TSO Cityserver's port. m_SSLSocket.Connected += M_SSLSocket_Connected; m_SSLSocket.ReceivedData += M_SSLSocket_ReceivedData; m_SSLSocket.InitializeSocket(); }
public MainWindow() { SplashScreen splash = new SplashScreen("images/SplashScreen.png"); splash.Show(true, true); //load configuration NameValueCollection cfg = ConfigurationManager.AppSettings; Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection c = configuration.AppSettings.Settings; List <string> list = new List <string>(); list.AddRange(c.AllKeys); if (!list.Contains("Height")) { c.Add(new KeyValueConfigurationElement("Height", "720")); } if (!list.Contains("Width")) { c.Add(new KeyValueConfigurationElement("Width", "1280")); } if (!list.Contains("Account")) { c.Add(new KeyValueConfigurationElement("Account", "Steve")); } if (!list.Contains("Memory")) { c.Add(new KeyValueConfigurationElement("Memory", "1024")); } if (!list.Contains("JavaPath")) { c.Add(new KeyValueConfigurationElement("JavaPath", "")); } if (!list.Contains("MCPath")) { c.Add(new KeyValueConfigurationElement("MCPath", "")); } if (!list.Contains("DataShare")) { c.Add(new KeyValueConfigurationElement("DataShare", "true")); } if (!list.Contains("Online")) { c.Add(new KeyValueConfigurationElement("Online", "true")); } if (!list.Contains("FirstRun")) { c.Add(new KeyValueConfigurationElement("FirstRun", "true")); } configuration.Save(); ConfigurationManager.RefreshSection("appSettings"); Config.UpdateSettings(); //initialize UI InitializeComponent(); DataContext = this; (About.Content as About).ver.Content = "Version: 3.0"; //load plugins if (!Directory.Exists(Environment.CurrentDirectory + "\\plugins")) { Directory.CreateDirectory(Environment.CurrentDirectory + "\\plugins"); } foreach (string file in Directory.GetFiles(Environment.CurrentDirectory + "\\plugins")) { if (file.Substring(file.Length - 3) != "dll") { continue; } Assembly asm = Assembly.LoadFile(file); Type[] t = asm.GetExportedTypes(); foreach (Type type in t) { if (type.BaseType == typeof(MtbPlugin)) { MtbPlugin plugin = (MtbPlugin)Activator.CreateInstance(type); plugin.LoadPlugin(); if (plugin.CheckUpdate()) { Console.WriteLine(plugin.Name + ":" + plugin.UpdateMessage); } foreach (KeyValuePair <string, Tile[]> item in plugin.GetPages()) { WrapPanel wp = new WrapPanel { Orientation = Orientation.Vertical, Height = 252 }; foreach (Tile page in item.Value) { page.Height = page.Width = 120; page.Background = tileBrush; wp.Children.Add(page); } GroupBox grop = new GroupBox { Header = item.Key, Content = wp, Margin = new Thickness(5, 5, 10, 10), HorizontalAlignment = HorizontalAlignment.Left, Background = Brushes.Transparent, BorderBrush = groupBrush }; ControlsHelper.SetHeaderFontSize(grop, 14); GroupBoxHelper.SetHeaderForeground(grop, Brushes.White); panel.Children.Add(grop); } tasks.Children.Add(new TaskBarButton { Tip = plugin.Name, Source = plugin.Icon, Plugin = plugin }); } } } Task.Run(new Action(CheckUpdate)); }
private static void AtualizarConfiguracao(string key, string value) { Settings.Remove(key); Settings.Add(key, value); }
private static bool ExtractCommandLine() { string dispatcher = Path.GetFullPath(Process.GetCurrentProcess().MainModule.FileName); string dispatcher_dir = Path.GetDirectoryName(dispatcher); cwd = null; //inherit as_service = false; as_desktop_user = false; use_job = true; //ConfigurationManager.AppSettings do not expand exe short name (e.g. search for a missing C:\windows\system32\somelo~1.config file) KeyValueConfigurationCollection config = new KeyValueConfigurationCollection(); if (ConfigurationManager.AppSettings["PATH"] != null) { foreach (string key in ConfigurationManager.AppSettings) { config.Add(key, ConfigurationManager.AppSettings[key]); } } else { config = ConfigurationManager.OpenExeConfiguration(dispatcher).AppSettings.Settings; } args = String.Empty; #if DISPACHER_WIN use_showwindow = false; #else use_showwindow = true; #endif exePath = config["PATH"].Value; if (config[FLAG_USE_SHOWWINDOW] != null) { use_showwindow = !(config[FLAG_USE_SHOWWINDOW].Value == "0" || config[FLAG_USE_SHOWWINDOW].Value == ""); } if (String.IsNullOrEmpty(exePath)) { Console.Error.WriteLine("Cannot resolve cmd"); return(false); } string dispatched_cmd = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); string exefoo = Path.GetFullPath(Path.Combine(dispatcher_dir, exePath)); if (File.Exists(exefoo)) { exePath = exefoo; //let windows resolve it } Dictionary <string, string> replaces = new Dictionary <string, string> { { "%dwd%", dispatcher_dir }, { "%Y%", DateTime.Now.ToString("yyyy") }, { "%m%", DateTime.Now.ToString("MM") }, { "%d%", DateTime.Now.ToString("dd") }, { "%H%", DateTime.Now.ToString("HH") }, { "%i%", DateTime.Now.ToString("mm") }, { "%s%", DateTime.Now.ToString("ss") }, }; foreach (string key in config.AllKeys) { string value = config[key].Value; value = Replace(value, replaces); value = Environment.ExpandEnvironmentVariables(value); if (key.StartsWith("ARGV")) { args += (Regex.IsMatch(value, "^[a-zA-Z0-9_./:^,=-]+$") ? value : "\"" + value + "\"") + " "; } if (key.StartsWith("ENV_")) { envs[key.Remove(0, 4)] = value; } if (key == "PRESTART_CMD") { execPreCmd = value; } if (key == "CWD") { cwd = value; } if (key == "AS_SERVICE") { as_service = true; } if (key == "AS_DESKTOP_USER") { as_desktop_user = true; } if (key == "OUTPUT") { logsPath = value; } if (key == "USE_JOB") { use_job = !isFalse(value); } } var argv = System.Environment.GetCommandLineArgs(); for (var i = 1; i < argv.Length; i++) { string value = argv[i]; args += (Regex.IsMatch(value, "^[a-zA-Z0-9_./:^,=-]+$") ? value : "\"" + value + "\"") + " "; } return(true); }
public void VerifyAppSettings(bool overwrite) { try { foreach (string name in Enum.GetNames(typeof(AppSettingNames))) { if (!_appSettings.AllKeys.Contains(name)) { _appSettings.Add(name, string.Empty); } // set default settings if (!overwrite && !string.IsNullOrEmpty(_appSettings[name].Value)) { continue; } switch ((AppSettingNames)Enum.Parse(typeof(AppSettingNames), name)) { case AppSettingNames.AutoSave: { _appSettings[name].Value = "False"; break; } case AppSettingNames.AutoPopulateColors: { _appSettings[name].Value = "True"; break; } case AppSettingNames.BackgroundColor: { _appSettings[name].Value = "Black"; break; } case AppSettingNames.CountMaskedMatches: { _appSettings[name].Value = "True"; break; } case AppSettingNames.CurrentFilterFiles: { _appSettings[name].Value = ""; break; } case AppSettingNames.CurrentLogFiles: { _appSettings[name].Value = ""; break; } case AppSettingNames.DebugFile: { _appSettings[name].Value = ""; break; } case AppSettingNames.FileExtensions: { _appSettings[name].Value = ".log;.rvf;.rvconfig"; break; } case AppSettingNames.FileHistoryCount: { _appSettings[name].Value = "20"; break; } case AppSettingNames.FilterHide: { _appSettings[name].Value = "False"; break; } case AppSettingNames.FilterIndexVisible: { _appSettings[name].Value = "True"; break; } case AppSettingNames.FontName: { _appSettings[name].Value = "Lucida Console"; break; } case AppSettingNames.FontSize: { _appSettings[name].Value = "12"; break; } case AppSettingNames.ForegroundColor: { _appSettings[name].Value = "Azure"; break; } case AppSettingNames.HelpUrl: { _appSettings[name].Value = "https://github.com/jasonagilbertson/TextFilter"; break; } case AppSettingNames.MaxMultiFileCount: { _appSettings[name].Value = "10"; break; } case AppSettingNames.RecentFilterFiles: { _appSettings[name].Value = ""; break; } case AppSettingNames.RecentLogFiles: { _appSettings[name].Value = ""; break; } case AppSettingNames.SaveSessionInformation: { _appSettings[name].Value = "False"; break; } case AppSettingNames.VersionCheckFile: { _appSettings[name].Value = "https://raw.githubusercontent.com/jasonagilbertson/TextFilter/master/TextFilter/version.xml"; break; } case AppSettingNames.WordWrap: { _appSettings[name].Value = "True"; break; } default: { break; } } } } catch (Exception e) { SetStatus("Exception:verifyappsetings:" + e.ToString()); } }
public void Test() { KeyValueConfigurationCollection collection = new KeyValueConfigurationCollection(); collection.Add("key", "value"); }
public void EditRecord(string key, string value) { _appSettingsKeyCollection.Remove(key); _appSettingsKeyCollection.Add(key, value); _configuration.Save(); }