//設定Config public static void SetConfig <T>(ConfigKey configType, T configValue) { #region Update userConfigType //Bool if (configValue is bool) { if (!userConfigTypeTable.ContainsKey(configType)) { userConfigTypeTable.Add(configType, ConfigType.Bool); } } //Int else if (configValue is int) { if (!userConfigTypeTable.ContainsKey(configType)) { userConfigTypeTable.Add(configType, ConfigType.Int); } } #endregion if (!userConfigTable.ContainsKey(configType)) { userConfigTable.Add(configType, configValue); } else { //有則更新 userConfigTable[configType] = configValue; } }
static void OnSetConfigsFile(string info, object sender, ConfigKey key) { var message = (sender as ToolStripItem).Text; var current = Configs.Current.Get(key); OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = message + " " + info; dialog.CheckPathExists = true; dialog.InitialDirectory = File.Exists(current) ? Path.GetDirectoryName(current) : null; if (key == ConfigKey.FilepathCoordMusicMainPy) { dialog.DefaultExt = ".py"; dialog.Filter = "Py files (*.py)|*.py"; } else { dialog.DefaultExt = ".exe"; dialog.Filter = "Exe files (*.exe)|*.exe"; } if (dialog.ShowDialog() == DialogResult.OK) { Configs.Current.Set(key, dialog.FileName); } }
private void DrawIPAddrField(ConfigKey key) { bool clicked = GUILayout.Button(key.Value.ToString(), panelSkin.button); if (clicked) { // Make a new picker if it's closed, or close it if it's already open. if (ipAddrPicker == null) { ipAddrPicker = this.gameObject.AddComponent <ListPickerDialog>(); kOS.Screen.ListPickerDialog.ChangeAction onChange = delegate(String s) { bool ok = TelnetMainServer.Instance.SetBindAddrFromString(s); if (ok) { key.Value = s; } return(ok); }; kOS.Screen.ListPickerDialog.CloseAction onClose = delegate() { ipAddrPicker = null; }; ipAddrPicker.Summon(windowRect.x, windowRect.y + windowRect.height, 300, "Telnet address (restart telnet to take effect)\n", null, "current: " + key.Value.ToString(), TelnetMainServer.GetAllAddresses(), onChange, onClose ); } else { ipAddrPicker.Close(); ipAddrPicker = null; } } }
public ConfigKeyChangingEventArgs(ConfigKey key, string oldValue, string newValue) { Key = key; OldValue = oldValue; NewValue = newValue; Cancel = false; }
public async Task <KvpConfig> GetConfigSetting(ConfigKey config) { var key = new ConfigKey(config); if (_configCache.ContainsKey(key)) { var success = _configCache.TryGetValue(key, out KvpConfig val); if (success) { return(val); } } var kvpConfig = await _fabricProvider.GetConfigSetting(config); if (kvpConfig == null) { return(kvpConfig); } var addSuccess = _configCache.TryAdd(key, new KvpConfig(kvpConfig)); if (!addSuccess) { _logger.Log(LogLevel.Warning, 0, "The given config was not added to cache", null, (val, ex) => val); } return(kvpConfig); }
/// <summary> /// /// </summary> /// <param name="vendor"></param> /// <param name="company"></param> /// <returns></returns> public Response VendorCreateUpdate(PMVendor vendor, string company) { var response = new Response(); string VendorXML; string server = ConfigKey.ReadSetting("SERVER"); //var server = Properties.Settings.Default.SERVER.ToString(); string CNX = "data source=" + server + ";initial catalog=" + company + ";integrated security=SSPI;persist security info=False;packet size=4096"; var eConnect = new eConnectRequest(); taUpdateCreateVendorRcd pmVendorCreateUpdate; try { pmVendorCreateUpdate = SetVendorValues(vendor); VendorXML = SerializeVendor(pmVendorCreateUpdate); response = eConnect.CreateGPMaster(CNX, VendorXML); return(response); } catch (Exception ex) { response = new Response(); response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; return(response); } }
public string Get(ConfigKey key) { var ret = _dict.TryGetValue(key, out string s) ? s : ""; ConfirmChecksums.Check(key, ret); return(ret); }
static bool DoSetValue(ConfigKey key, string newValue) { string oldValue = Values[(int)key]; if (oldValue != newValue) { if (!RaiseKeyChangingEvent(key, oldValue, ref newValue)) { return(false); } Values[(int)key] = newValue; bool enabledCache; if (Boolean.TryParse(newValue, out enabledCache)) { SettingsUseEnabledCache[(int)key] = true; SettingsEnabledCache[(int)key] = enabledCache; } else { SettingsUseEnabledCache[(int)key] = false; SettingsEnabledCache[(int)key] = false; } ApplyKeyChange(key); RaiseKeyChangedEvent(key, oldValue, newValue); } return(true); }
private Config <T> GetConfig <T>(bool isReadOnly, string category, string key, T defaultValue) { var lookupKey = new ConfigKey(category, key); Config existing; Config <T> e; if (!_configLookup.TryGetValue(lookupKey, out existing)) { T value; if (!_valueProvider.TryGetValue(category, key, out value)) { value = defaultValue; } e = new Config <T>(value, defaultValue, isReadOnly); _configLookup.Add(lookupKey, e); } else { if (existing.Type != typeof(T)) { throw new InvalidOperationException( $"Config {category}.{key} has already been used with a different type."); } e = (Config <T>)existing; } return(e); }
private static void ApplyEnum <TEnum>([NotNull] ComboBox box, ConfigKey key, TEnum def) where TEnum : struct { if (box == null) { throw new ArgumentNullException("box"); } if (!typeof(TEnum).IsEnum) { throw new ArgumentException("Enum type required"); } try { if (key.IsBlank()) { box.SelectedIndex = (int)(object)def; } else { box.SelectedIndex = (int)Enum.Parse(typeof(TEnum), key.GetString(), true); } } catch (ArgumentException) { box.SelectedIndex = (int)(object)def; } }
public Response CreateCustomerClass(string line_of_business, string policy_type, string vehicle_type, string zone, string country, string channel, string supervisor, int supervisor_code, string custclass, string GpProductID) { RMCustomerClass rmcustclass = new RMCustomerClass(); AccountBuilder aBuilder = new AccountBuilder(); Response response; Customers custom = new Customers(); string taxid = ConfigKey.ReadSetting("TAXID"); string accountREC = ConfigKey.ReadSetting("IDREC"); string company = ConfigKey.ReadSetting("Company"); try { rmcustclass.CLASSID = custclass; rmcustclass.CLASDSCR = custclass; rmcustclass.CRLMTTYP = 1; rmcustclass.TAXSCHID = taxid; rmcustclass.STMTCYCL = 5; rmcustclass.CUSTPRIORITY = 1; rmcustclass.ORDERFULFILLDEFAULT = 1; rmcustclass.ACCTRECACCT = aBuilder.BuildARAccount(Convert.ToInt32(accountREC), line_of_business, policy_type, vehicle_type, country, channel, supervisor, supervisor_code, GpProductID); response = custom.CreateCustomerClass(rmcustclass, company); return(response); } catch (Exception ex) { log.LogExeption("Ocurrió un error: ", 2, ex); throw; } }
public void Set(ConfigArea area, ConfigKey key, object value, bool persist = false) { if (area == null) { throw new ArgumentNullException("area"); } if (key == null) { throw new ArgumentNullException("key"); } try { var entryExist = EntryExist(area, key); if (entryExist) { var entry = GetEntry(area, key); entry.Value = value; entry.Persist = persist; } else { var entry = new ConfigEntry(area.Name, key.Name, value, persist); _entries.Add(entry); } } catch (Exception e) { var message = String.Format("Error setting value {0} for key {1} in area {2} ({3})", value, key.Name, area.Name, persist ? "persistent" : "non-persistent"); throw new ConfigurationException(message, e); } }
public async void ShouldThrowInvalidOpEx_WhenConfigAlreadyExists() { var dict = await _service.StateManager.GetOrAddAsync <IReliableDictionary <ConfigKey, KvpConfig> >(CoreService.KvpDictionaryName); KvpConfig config = null; using (var tx = new MockTransaction()) { config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); await tx.CommitAsync(); } KvpConfig newconfig = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; await Assert.ThrowsAnyAsync <InvalidOperationException>(() => _service.AddConfigSetting(newconfig)); }
public Response CustomerClassCreate(RMCustomerClass customerClass, string company) { var response = new Response(); string CustomerCLassXML; string server = ConfigKey.ReadSetting("SERVER"); string CNX = "data source=" + server + ";initial catalog=" + company + ";integrated security=SSPI;persist security info=False;packet size=4096"; var eConnect = new eConnectRequest(); taCreateCustomerClass rmCustomerClass; try { rmCustomerClass = SetCustomerClassValues(customerClass); CustomerCLassXML = SerializeCustomerClass(rmCustomerClass); response = eConnect.CreateGPMaster(CNX, CustomerCLassXML); return(response); } catch (Exception ex) { response = new Response(); response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; return(response); } }
public Response SalesPresonCreate(RMSalesPerson salesperson, string company) { var response = new Response(); string SalesPersonXML; string server = ConfigKey.ReadSetting("SERVER"); string CNX = "data source=" + server + ";initial catalog=" + company + ";integrated security=SSPI;persist security info=False;packet size=4096"; var eConnect = new eConnectRequest(); taCreateSalesperson rmSalesPerson; try { rmSalesPerson = SetSalesPersonValues(salesperson); SalesPersonXML = SerializeSalesPerson(rmSalesPerson); response = eConnect.CreateGPMaster(CNX, SalesPersonXML); return(response); } catch (Exception ex) { response = new Response(); response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; return(response); } }
public Response VoidTransaction(RMVoidTransaction rmvoidtran, string company) { Response response; string server = ConfigKey.ReadSetting("SERVER"); string transactionXML = string.Empty; string CNX = "data source=" + server + ";initial catalog=" + company + ";integrated security=SSPI;persist security info=False;packet size=4096"; var eConnect = new eConnectRequest(); RMVoidTransactionType rmvoidtransaction = new RMVoidTransactionType(); try { rmvoidtransaction.taRMVoidTransaction = SetVoidValues(rmvoidtran); transactionXML = SerializeRMVoid(rmvoidtransaction); response = eConnect.CreateGPTransaction(CNX, transactionXML); return(response); } catch (Exception ex) { response = new Response(); response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; return(response); //throw; } }
public static ConfigKey Merge(ConfigKey first, ConfigKey second) { var newKey = first.Key + ":" + second.Key; var newPrefix = Prefix.Merge(first.Prefix, second.Prefix); return(new ConfigKey(newKey, newPrefix, second.VersionRange, second.Segment)); }
///<summary> ///Backs up config settings to mongodb store. Currently abandons all hope of saving if an exception is thrown. that's what ///stateful services are for anyways right? lol ///</summary> //TODO add some way to add failures to a queue of shit that needs to be backed up private async Task RemoveConfigFromBackup(ConfigKey config) { var db = DbClient.GetDatabase(_backupDbName); var collection = db.GetCollection <BsonDocument>(_backupKvpCollection); var toDelete = new BsonDocument { { "Name", config.Name }, { "Version", config.Version }, }; try { var exists = await collection.FindAsync(toDelete); if (!exists.Any()) { _logger.Log(LogLevel.Warning, 0, $"Attempted to remove a config from backup which does not exists {config.Name}: {config.Version}. Aborting", null, (msg, exx) => msg); return; } await collection.DeleteOneAsync(toDelete); } catch (Exception ex) { _logger.Log(LogLevel.Error, 0, "Exception of type {0} occured while saving config to backup: {1} | {2}", ex, (msg, exx) => String.Format(msg, exx.Message, exx.Source, exx.StackTrace)); } }
/// <summary> Sets value of a specified config key. /// Note that this method may throw exceptions if the given value is not acceptible. /// Use Config.TrySetValue() if you'd like to suppress exceptions in favor of a boolean return value. </summary> /// <param name="key"> Config key to set. </param> /// <param name="rawValue"> Value to assign to the key. If passed object is not a string, rawValue.ToString() is used. </param> /// <exception cref="T:System.ArgumentNullException" /> /// <exception cref="T:System.FormatException" /> /// <returns> True if value is valid and has been assigned. /// False if value is valid, but assignment was cancelled by an event handler/plugin. </returns> public static bool SetValue(this ConfigKey key, object rawValue) { if (rawValue == null) { throw new ArgumentNullException("rawValue", key + ": ConfigKey values cannot be null. Use an empty string to indicate unset value."); } string value = (rawValue as string ?? rawValue.ToString()); if (value == null) { throw new NullReferenceException(key + ": rawValue.ToString() returned null."); } // LEGACY if (LegacyConfigValues.ContainsKey(key)) { foreach (var pair in LegacyConfigValues.Values) { if (pair.Key.Equals(value, StringComparison.OrdinalIgnoreCase)) { value = pair.Value; break; } } } // throws various exceptions (most commonly FormatException) if invalid KeyMetadata[key].Validate(value); return(DoSetValue(key, value)); }
public async void ShouldNotGetNonExistantKvpConfig() { var dict = await _service.StateManager.GetOrAddAsync <IReliableDictionary <ConfigKey, KvpConfig> >(CoreService.KvpDictionaryName); KvpConfig config = null; using (var tx = new MockTransaction()) { config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); await tx.CommitAsync(); } if (await dict.GetCountAsync(new MockTransaction()) != 1) { Assert.False(true, "The config key was not saved. The test will not proceed"); } var val = await _service.GetConfigSetting(new ConfigKey("NotAKey", "1.0.0")); Assert.True(val == null, "The service returned a response.... That ain't right"); }
private static string GetPathToBinary(ConfigKey key, string name, string[] hints) { var current = Configs.Current.Get(key); if (File.Exists(current)) { return(current); } foreach (var hint in hints) { if (File.Exists(hint)) { SimpleLog.Current.WriteLog("automatically detected location of " + name + Utils.NL + hint); Configs.Current.Set(key, hint); return(hint); } } while (true) { var file = Utils.AskOpenFileDialog("Please find " + name); if (file != null) { Configs.Current.Set(key, file); return(file); } else if (!Utils.AskToConfirm("Program " + name + " still not found. Continue?")) { throw new CsDownloadVidException("Program " + name + " not found."); } } }
public static T GetAppSetting <T>(ConfigKey key, T defaultValue) { //get the app setting value object appSetting = GetAppSetting(key); //if the app setting value is null then return the default if (appSetting == null) { return(defaultValue); } //otherwise attempt to cast to the correct type Type targetType = typeof(T); try { if (targetType.IsSubclassOf(typeof(Enum))) { return((T)Enum.Parse(targetType, appSetting.ToString())); } else { return((T)Convert.ChangeType(appSetting, targetType)); } } catch { throw new Exception(string.Format("Requested configuration value with key '{0}' and value '{1}' cannot be converted to type '{2}'", key, appSetting, typeof(T))); } }
//讀檔並存入Dictionary private static void ReadConfigFromFile() { string[] configString = File.ReadAllLines(userConfigPath); //每一行 foreach (string line in configString) { ConfigKey eachKey = (ConfigKey)Enum.Parse(typeof(ConfigKey), line.Split(':')[0]); string valueString = line.Split(':')[1]; bool boolValue; int intValue; //Bool <有例外> if (Boolean.TryParse(valueString, out boolValue)) { SetConfig(eachKey, boolValue); Console.WriteLine("[Set Bool]" + eachKey.ToString() + ":" + boolValue.ToString()); } //Int else if (int.TryParse(valueString, out intValue)) { SetConfig(eachKey, intValue); Console.WriteLine("[Set Int]" + eachKey.ToString() + ":" + intValue.ToString()); } else { MessageBox.Show("Fatal error:無法解析 Config"); //刪除config並關閉程式 <待寫> } } }
static Config() { int keyCount = Enum.GetValues(typeof(ConfigKey)).Length; Values = new string[keyCount]; SettingsEnabledCache = new bool[keyCount]; SettingsUseEnabledCache = new bool[keyCount]; KeyMetadata = new ConfigKeyAttribute[keyCount]; // gather metadata for ConfigKeys foreach (var keyField in typeof(ConfigKey).GetFields()) { foreach (var attribute in (ConfigKeyAttribute[])keyField.GetCustomAttributes(typeof(ConfigKeyAttribute), false)) { ConfigKey key = (ConfigKey)keyField.GetValue(null); attribute.Key = key; KeyMetadata[(int)key] = attribute; } } // organize ConfigKeys into categories, based on metadata foreach (ConfigSection section in Enum.GetValues(typeof(ConfigSection))) { ConfigSection sec = section; KeySections.Add(section, KeyMetadata.Where(meta => (meta.Section == sec)) .Select(meta => meta.Key) .ToArray()); } LoadDefaults(); }
public static string GetConfig(ConfigKey key, string defaultValue = "") { if (!File.Exists(ConfigFile)) { return(defaultValue); } return(IniUtils.Read(ConfigFile, CONFIGKEY, key.ToString(), defaultValue).Trim()); }
/// <summary> /// Get the value from the config /// </summary> public float GetConfigValue(ConfigKey eventKey, CrewMember member = null) { if (eventKey == ConfigKey.StatRevealCost && member != null) { return((int)(member.RevealedSkills.Count(s => s.Value != 0) * GetConfigValue(ConfigKey.StatRevealCost)) + (member.RevealedSkills.All(s => s.Value != 0) ? 0 : 1)); } return(eventKey.GetValue()); }
public string GetValueString(ConfigKey key) { if (!_config.ContainsKey(key)) { throw new Exception($"Missing key {key}"); } return(_config[key]); }
/// <summary> Attempts to parse a given key's value as an enumeration. /// An ArgumentException is thrown if value could not be parsed. /// Note the parsing is done in a case-insensitive way. </summary> /// <typeparam name="TEnum"> Enum to use for parsing. /// An ArgumentException will be thrown if this is not an enum. </typeparam> public static TEnum GetEnum <TEnum>(this ConfigKey key) where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new ArgumentException("Enum type required"); } return((TEnum)Enum.Parse(typeof(TEnum), GetString(key), true)); }
public object GetConfig(ConfigKey Key) { if (conf.ContainsKey(Key)) { return(conf[Key]); } return(null); }
public void GetSettingIsAnswered(int value, Setting setting, ConfigKey configKey) { _databaseHandler.GetSetting(configKey).Returns(value); _communicationInterface.When(item => item.StartListening(Arg.Any<string>())) .Do(ci => _communicationInterface.SolarEvent += Raise.EventWith<SolarCollectorEventArg>(new object(), new SolarCollectorSettingEventArg("TIME:60315 REQ: GET_SETTING "+ ((int)setting)))); _main.Start(); _communicationInterface.Received().AddSetSetting(setting, value); }
void ApplyEnum( ComboBox box, ConfigKey key, int def, params string[] options ) { int index = Array.IndexOf<string>( options, Config.GetString( key ) ); if( index != -1 ) { box.SelectedIndex = index; } else { box.SelectedIndex = def; } }
static void RaiseKeyChangedEvent(ConfigKey key, string oldValue, string newValue) { var h = KeyChanged; if (h != null) { h(null, new ConfigKeyChangedEventArgs(key, oldValue, newValue)); } }
public static string GetAppSettingValue(ConfigKey key) { switch (key) { case ConfigKey.RecaptchaKey: return ConfigurationManager.AppSettings["RecaptchaPrivateKey"]; case ConfigKey.RecaptchaUrl: return ConfigurationManager.AppSettings["RecaptchaUrl"]; } return string.Empty; }
public static string Get(ConfigKey opt) { return OptionStrings[opt]; }
public string Read(ConfigKey key) { return ConfigurationManager.AppSettings[key.ToString()]; }
static MenuState ShowKeyList() { ShowSeparator(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Keys in section {0}:", currentSection); Console.ResetColor(); Console.WriteLine(" 0. .."); ConfigKey[] keys = currentSection.GetKeys(); int maxLen = keys.Select(key => key.ToString().Length).Max(); for (int i = 0; i < keys.Length; i++) { var meta = keys[i].GetMetadata(); string formattedValue; if (meta.ValueType == typeof(int) || meta.ValueType == typeof(bool)) { formattedValue = keys[i].GetString(); } else { formattedValue = "\"" + keys[i].GetString() + "\""; } string str = String.Format(" {0,2}. {1," + maxLen + "} = {2}", i + 1, keys[i], formattedValue); if (!keys[i].IsDefault()) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(str); Console.ResetColor(); } else { Console.WriteLine(str); } } string replyString; int reply; do { Console.Write("Enter key number: "); replyString = Console.ReadLine(); } while (!Int32.TryParse(replyString, out reply) || reply < 0 || reply > keys.Length); if (reply == 0) { return MenuState.SectionList; } else { currentKey = keys[reply - 1]; return MenuState.Key; } }
public static bool GetBool( ConfigKey key ) { return Boolean.Parse( settings[key] ); }
protected void btnG1Click(object sender, EventArgs e) { ConfigKey configKeyDialog = new ConfigKey(1); configKeyDialog.Show(); }
void WriteEnum( ComboBox box, ConfigKey value, params string[] options ) { Config.SetValue( value, options[box.SelectedIndex] ); }
static MenuState ShowKeyList() { Refresh( "Section {0}", currentSection ); TextMenu menu = new TextMenu(); TextOption optionBack = menu.AddOption( "B", "Back to sections" ); TextOption optionDefaults = menu.AddOption( "D", "Use defaults" ); menu.AddSpacer(); ConfigKey[] keys = currentSection.GetKeys(); int maxLen = keys.Select( key => key.ToString().Length ).Max(); for( int i = 0; i < keys.Length; i++ ) { string str = String.Format( "{0} = {1}", keys[i].ToString().PadLeft( maxLen, '.' ), keys[i].GetPresentationString() ); TextOption option = new TextOption( ( i + 1 ).ToString( CultureInfo.InvariantCulture ), str, Column.Left ); if( !keys[i].IsDefault() ) { option.ForeColor = ConsoleColor.White; } option.Tag = keys[i]; menu.AddOption( option ); } TextOption choice = menu.Show(); if( choice == optionBack ) { return MenuState.SectionList; } else if( choice == optionDefaults ) { if( TextMenu.ShowYesNo( "Reset everything in section {0} to defaults?", currentSection ) ) { Config.LoadDefaults( currentSection ); } } else { currentKey = (ConfigKey)choice.Tag; return MenuState.Key; } return MenuState.KeyList; }
static bool ValidateBool( ConfigKey key, string value ) { bool temp; if( Boolean.TryParse( value, out temp ) ) { settings[key] = temp.ToString(); return true; } else { Log( "Config.SetValue: Specified value for {0} could not be parsed. Expected 'true' or 'false'. Using default ({1}).", LogType.Warning, key, settings[key] ); return false; } }
public static bool SetValue( ConfigKey key, string value ) { switch( key ) { case ConfigKey.ServerName: return ValidateString( key, value, 1, 64 ); case ConfigKey.MOTD: return ValidateString( key, value, 0, 64 ); case ConfigKey.MaxPlayers: return ValidateInt( key, value, 1, MaxPlayersSupported ); case ConfigKey.DefaultClass: if( value != "" ) { if( ClassList.ParseClass( value ) != null ) { settings[key] = ClassList.ParseClass( value ).name; return true; } else { Log( "DefaultClass could not be parsed. It should be either blank (indicating \"use lowest class\") or a valid class name", LogType.Warning ); return false; } } else { settings[key] = ""; return true; } case ConfigKey.Port: case ConfigKey.IRCBotPort: return ValidateInt( key, value, 1, 65535 ); case ConfigKey.UploadBandwidth: return ValidateInt( key, value, 1, 10000 ); case ConfigKey.IRCBotNick: return ValidateString( key, value, 1, 32 ); //case "IRCBotNetwork": //case "IRCBotChannels": // don't bother validating network and channel list case ConfigKey.IsPublic: case ConfigKey.ClassColorsInChat: case ConfigKey.ClassPrefixesInChat: case ConfigKey.ClassPrefixesInList: case ConfigKey.SaveOnShutdown: case ConfigKey.BackupOnStartup: case ConfigKey.BackupOnJoin: case ConfigKey.BackupOnlyWhenChanged: case ConfigKey.SendRedundantBlockUpdates: case ConfigKey.NoPartialPositionUpdates: case ConfigKey.IRCBot: case ConfigKey.IRCBotForwardFromServer: case ConfigKey.IRCBotForwardFromIRC: return ValidateBool( key, value ); case ConfigKey.SystemMessageColor: case ConfigKey.HelpColor: case ConfigKey.SayColor: return ValidateColor( key, value ); case ConfigKey.VerifyNames: return ValidateEnum( key, value, "Always", "Balanced", "Never" ); case ConfigKey.AntispamMessageCount: return ValidateInt( key, value, 2, 50 ); case ConfigKey.AntispamInterval: return ValidateInt( key, value, 0, 60 ); case ConfigKey.AntigriefBlockCount: return ValidateInt( key, value, 2, 500 ); case ConfigKey.AntigriefInterval: return ValidateInt( key, value, 0, 60 ); case ConfigKey.AntispamMuteDuration: return ValidateInt( key, value, 0, 3600 ); case ConfigKey.AntispamMaxWarnings: return ValidateInt( key, value, 0, 50 ); case ConfigKey.SaveInterval: return ValidateInt( key, value, 1, 100000 ); case ConfigKey.BackupInterval: return ValidateInt( key, value, 0, 100000 ); case ConfigKey.MaxBackups: return ValidateInt( key, value, 0, 100000 ); case ConfigKey.MaxBackupSize: return ValidateInt( key, value, 0, 1000000 ); case ConfigKey.LogMode: return ValidateEnum( key, value, "None", "OneFile", "SplitBySession", "SplitByDay" ); case ConfigKey.MaxLogs: return ValidateInt( key, value, 0, 100000 ); case ConfigKey.PolicyColorCodesInChat: case ConfigKey.PolicyIllegalCharacters: return ValidateEnum( key, value, "Allow", "ConsoleOnly", "Disallow" ); case ConfigKey.ProcessPriority: return ValidateEnum( key, value, "", "High", "AboveNormal", "Normal", "BelowNormal", "Low" ); case ConfigKey.RunOnStartup: return ValidateEnum( key, value, "Always", "OnUnexpectedShutdown", "Never" ); case ConfigKey.AutomaticUpdates: return ValidateEnum( key, value, "Disabled", "Notify", "Prompt", "Auto" ); case ConfigKey.BlockUpdateThrottling: return ValidateInt( key, value, 10, 100000 ); case ConfigKey.TickInterval: return ValidateInt( key, value, 20, 1000 ); default: settings[key] = value; return true; } }
static bool ValidateEnum( ConfigKey key, string value, params string[] options ) { for( int i = 0; i < options.Length; i++ ) { if( value.ToLower() == options[i].ToLower() ) { settings[key] = options[i]; return true; } } Log( "Config.SetValue: Invalid option specified for {0}. " + "See documentation for the list of permitted options. Using default: {1}", LogType.Warning, key, settings[key] ); return false; }
static bool ValidateColor( ConfigKey key, string value ) { if( Color.Parse( value ) != null ) { settings[key] = value; return true; } else { Log( "Config.SetValue: Specified value for {0} could not be parsed. Using default ({1}).", LogType.Warning, key, settings[key] ); return false; } }
static bool ValidateInt( ConfigKey key, string value, int minRange, int maxRange ) { int temp; if( Int32.TryParse( value, out temp ) ) { if( temp >= minRange && temp <= maxRange ) { settings[key] = temp.ToString(); } else { Log( "Config.SetValue: Specified value for {0} is not within valid range ({1}...{2}). Using default ({3}).", LogType.Warning, key, minRange, maxRange, settings[key] ); } return true; } else { Log( "Config.SetValue: Specified value for {0} could not be parsed. Using default ({1}).", LogType.Warning, key, settings[key] ); return false; } }
static bool ValidateString( ConfigKey key, string value, int minLength, int maxLength ) { if( value.Length < minLength ) { Log( "Config.SetValue: Specified value for {0} is too short (expected length: {1}...{2}). Using default ({3}).", LogType.Warning, key, minLength, maxLength, settings[key] ); return false; } else if( value.Length > maxLength ) { settings[key] = value.Substring( 0, maxLength ); Log( "Config.SetValue: Specified value for {0} is too long (expected length: {1}...{2}). The value has been truncated to \"{3}\".", LogType.Warning, key, minLength, maxLength, settings[key] ); return true; } else { settings[key] = value; return true; } }
public static ConfigKey Merge(ConfigKey first, ConfigKey second) { var newKey = string.Format("{0}:{1}", first.Key, second.Key); var newPrefix = Prefix.Merge(first.Prefix, second.Prefix); return new ConfigKey(newKey, newPrefix); }
/// <summary> /// Gets the setting from the Web.Config or App.Config /// </summary> /// <param name="webConfigEnum">The key, as a ConfigKey enum</param> /// <returns>String value or empty string</returns> public static string GetSetting(ConfigKey webConfigEnum) { string key = webConfigEnum.ToString(); //Use for *required* config keys; Nick wants to throw an exception if it's missing. var value = ConfigurationManager.AppSettings[webConfigEnum.ToString()]; if (value == null) throw new Exception("Missing config key: " + key); return value.ToString(); }
public static string GetString( ConfigKey key ) { return settings[key]; }
public static string Get(ConfigKey ConfigKey) { return Configs[ConfigKey]; }
public static int GetInt( ConfigKey key ) { return Int32.Parse( settings[key] ); }
public ConfigKey Merge(ConfigKey other) { return Merge(this, other); }
public string GetSetting(ConfigKey configKey) { return ConfigurationManager.AppSettings[configKey.ToString()]; }