public ContentTypeDefinition(string name, string displayName, IEnumerable<ContentTypePartDefinition> parts, SettingsDictionary settings) { Name = name; DisplayName = displayName; Parts = parts.ToReadOnlyCollection(); Settings = settings; }
private XElement NewElement(string name, SettingsDictionary settings) { var element = new XElement(XmlConvert.EncodeLocalName(name)); foreach(var settingAttribute in _settingsWriter.Map(settings).Attributes()) { element.Add(settingAttribute); } return element; }
public DropboxWebHookReceiverTests() { _settings = new SettingsDictionary(); _settings["MS_WebHookReceiverSecret_Dropbox"] = TestSecret; _config = HttpConfigurationMock.Create(new Dictionary<Type, object> { { typeof(SettingsDictionary), _settings } }); _context = new HttpRequestContext { Configuration = _config }; _receiverMock = new Mock<DropboxWebHookReceiver> { CallBase = true }; _getRequest = new HttpRequestMessage(); _getRequest.SetRequestContext(_context); _postRequest = new HttpRequestMessage() { Method = HttpMethod.Post }; _postRequest.SetRequestContext(_context); _postRequest.Content = new StringContent(TestContent, Encoding.UTF8, "application/json"); byte[] secret = Encoding.UTF8.GetBytes(TestSecret); using (var hasher = new HMACSHA256(secret)) { byte[] data = Encoding.UTF8.GetBytes(TestContent); byte[] testHash = hasher.ComputeHash(data); _testSignature = EncodingUtilities.ToHex(testHash); } }
/// <summary> /// Call this before ShowDialog to initialise the dialog with entry values to be edited /// </summary> /// <param name="BranchLocation">The path to the active branch</param> /// <param name="Index">The index of the favourite to be edited</param> /// <param name="LocalSettings">A reference to the local settings object used to persist personal preferences</param> public void InitializeDialog(string BranchLocation, int Index, SettingsDictionary LocalSettings) { BuildConfiguration dbCfg = new BuildConfiguration(BranchLocation, LocalSettings); string dbms, dbName, port, password, location, version; bool isBlank; dbCfg.GetStoredConfiguration(Index, out dbms, out dbName, out port, out password, out isBlank, out location, out version); cboDBMS.SelectedIndex = BuildConfiguration.GetDBMSIndex(dbms); txtDBName.Text = dbName; txtPort.Text = port; txtPassword.Text = password; chkBlankPW.Checked = isBlank; txtLocation.Text = location; if (String.Compare(dbms, "postgresql", true) == 0) { SetPostgreSQLVersionIndex(version); } else { cboVersion.SelectedIndex = 0; } SetEnabledStates(); }
public AzureWebHookSenderTests() { _settings = new SettingsDictionary(); _logger = new Mock<ILogger>().Object; _storageMock = StorageManagerMock.Create(); _sender = new AzureWebHookSender(_storageMock.Object, _settings, _logger); }
public ContentTypeDefinition(string name, string displayName) { Name = name; DisplayName = displayName; Parts = Enumerable.Empty<ContentTypePartDefinition>(); Settings = new SettingsDictionary(); }
public SettingsResponse(bool success, SettingsDictionary settings = null, int settingsVersion = -1, Exception exception = null, string message = null) { Success = success; Settings = settings; SettingsVersion = settingsVersion; Exception = exception; Message = message; }
/// <summary> /// Builds a new XML element with a given name and a settings dictionary. /// </summary> /// <param name="name">The name of the element to be mapped to XML.</param> /// <param name="settings">The settings dictionary to be used as the element's attributes.</param> /// <returns>The new XML element.</returns> private XElement NewElement(string name, SettingsDictionary settings) { XElement element = _settingsFormatter.Map(settings); element.Name = XmlConvert.EncodeLocalName(name); return element; }
public override Task EventProcessingAsync(EventContext context) { if (!context.Event.IsError()) return Task.CompletedTask; Error error = context.Event.GetError(); if (error == null) return Task.CompletedTask; if (String.IsNullOrWhiteSpace(context.Event.Message)) context.Event.Message = error.Message; string[] commonUserMethods = { "DataContext.SubmitChanges", "Entities.SaveChanges" }; if (context.HasProperty("CommonMethods")) commonUserMethods = context.GetProperty<string>("CommonMethods").SplitAndTrim(','); string[] userNamespaces = null; if (context.HasProperty("UserNamespaces")) userNamespaces = context.GetProperty<string>("UserNamespaces").SplitAndTrim(','); var signature = new ErrorSignature(error, userCommonMethods: commonUserMethods, userNamespaces: userNamespaces); if (signature.SignatureInfo.Count <= 0) return Task.CompletedTask; var targetInfo = new SettingsDictionary(signature.SignatureInfo); var stackingTarget = error.GetStackingTarget(); if (stackingTarget?.Error?.StackTrace != null && stackingTarget.Error.StackTrace.Count > 0 && !targetInfo.ContainsKey("Message")) targetInfo["Message"] = stackingTarget.Error.Message; error.Data[Error.KnownDataKeys.TargetInfo] = targetInfo; foreach (var key in signature.SignatureInfo.Keys) context.StackSignatureData.Add(key, signature.SignatureInfo[key]); return Task.CompletedTask; }
public TrelloWebHookReceiverTests() { _settings = new SettingsDictionary(); _settings["MS_WebHookReceiverSecret_Trello"] = TestSecret; _config = HttpConfigurationMock.Create(new Dictionary<Type, object> { { typeof(SettingsDictionary), _settings } }); _context = new HttpRequestContext { Configuration = _config }; _receiverMock = new Mock<TrelloWebHookReceiver> { CallBase = true }; _headRequest = new HttpRequestMessage() { Method = HttpMethod.Head }; _headRequest.SetRequestContext(_context); _postRequest = new HttpRequestMessage(HttpMethod.Post, TestAddress); _postRequest.SetRequestContext(_context); _postRequest.Content = new StringContent(TestContent, Encoding.UTF8, "application/json"); byte[] secret = Encoding.UTF8.GetBytes(TestSecret); using (var hasher = new HMACSHA1(secret)) { byte[] data = Encoding.UTF8.GetBytes(TestContent); byte[] requestUri = Encoding.UTF8.GetBytes(TestAddress); byte[] combo = new byte[data.Length + requestUri.Length]; Buffer.BlockCopy(data, 0, combo, 0, data.Length); Buffer.BlockCopy(requestUri, 0, combo, data.Length, requestUri.Length); byte[] testHash = hasher.ComputeHash(combo); _signature = EncodingUtilities.ToBase64(testHash, uriSafe: false); } }
public StripeWebHookReceiverTests() { _settings = new SettingsDictionary(); _settings["MS_WebHookReceiverSecret_Stripe"] = TestSecret; _config = HttpConfigurationMock.Create(new Dictionary<Type, object> { { typeof(SettingsDictionary), _settings } }); _context = new HttpRequestContext { Configuration = _config }; _stripeResponse = new HttpResponseMessage(); _stripeResponse.Content = new StringContent("{ \"type\": \"action\" }", Encoding.UTF8, "application/json"); _handlerMock = new HttpMessageHandlerMock(); _handlerMock.Handler = (req, counter) => { string expected = string.Format(CultureInfo.InvariantCulture, StripeWebHookReceiver.EventUriTemplate, TestId); Assert.Equal(req.RequestUri.AbsoluteUri, expected); return Task.FromResult(_stripeResponse); }; _httpClient = new HttpClient(_handlerMock); _receiverMock = new Mock<StripeWebHookReceiver>(_httpClient) { CallBase = true }; _postRequest = new HttpRequestMessage { Method = HttpMethod.Post }; _postRequest.SetRequestContext(_context); }
/************************************************************************************************************************************** * * Initialisation and GUI state routines * * ***********************************************************************************************************************************/ /// <summary> /// Constructor for the class /// </summary> public MainForm() { InitializeComponent(); string appVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion; _localSettings = new SettingsDictionary(GetDataFilePath(TPaths.Settings), appVersion); _localSettings.Load(); _externalLinks = new ExternalLinksDictionary(GetDataFilePath(TPaths.ExternalLinks)); _externalLinks.Load(); _externalLinks.PopulateListBox(lstExternalWebLinks); PopulateCombos(); this.Text = Program.APP_TITLE; cboCodeGeneration.SelectedIndex = _localSettings.CodeGenerationComboID; cboCompilation.SelectedIndex = _localSettings.CompilationComboID; cboMiscellaneous.SelectedIndex = _localSettings.MiscellaneousComboID; cboDatabase.SelectedIndex = _localSettings.DatabaseComboID; chkAutoStartServer.Checked = _localSettings.AutoStartServer; chkAutoStopServer.Checked = _localSettings.AutoStopServer; chkCheckForUpdatesAtStartup.Checked = _localSettings.AutoCheckForUpdates; chkMinimizeServer.Checked = _localSettings.MinimiseServerAtStartup; chkTreatWarningsAsErrors.Checked = _localSettings.TreatWarningsAsErrors; chkCompileWinform.Checked = _localSettings.CompileWinForm; chkStartClientAfterGenerateWinform.Checked = _localSettings.StartClientAfterCompileWinForm; txtBranchLocation.Text = _localSettings.BranchLocation; txtYAMLPath.Text = _localSettings.YAMLLocation; txtFlashAfterSeconds.Text = _localSettings.FlashAfterSeconds.ToString(); txtBazaarPath.Text = _localSettings.BazaarPath; ValidateBazaarPath(); _sequence = ConvertStringToSequenceList(_localSettings.Sequence); _altSequence = ConvertStringToSequenceList(_localSettings.AltSequence); ShowSequence(txtSequence, _sequence); ShowSequence(txtAltSequence, _altSequence); lblVersion.Text = "Version " + appVersion; SetBranchDependencies(); GetServerState(); SetEnabledStates(); SetToolTips(); // Check if we were launched using commandline switches // If so, we execute the instruction, start a timer, which then will close us down. if (Program.cmdLine.StartServer) { linkLabelStartServer_LinkClicked(null, null); ShutdownTimer.Enabled = true; } else if (Program.cmdLine.StopServer) { linkLabelStopServer_LinkClicked(null, null); ShutdownTimer.Enabled = true; } }
public static DiffDictionary<string, string> GetDiff(this SettingsDictionary oldSettings, SettingsDictionary newSettings) { var dictionary = new DiffDictionary<string, string>(); BuildDiff(dictionary, newSettings, oldSettings); BuildDiff(dictionary, oldSettings, newSettings); return dictionary; }
public BuildConfiguration(string BranchLocation, SettingsDictionary LocalSettings) { _branchLocation = BranchLocation; _localSettings = LocalSettings; // We can work out what our favourite configurations are whatever the branch location _storedDbBuildConfig.Clear(); string s = _localSettings.DbBuildConfigurations; if (s != String.Empty) { string[] sep = { "&&" }; string[] items = s.Split(sep, StringSplitOptions.None); for (int i = 0; i < items.Length; i++) { _storedDbBuildConfig.Add(items[i]); } } // Now we read the content of our working (current) config. For that we need a valid branch location if (_branchLocation == String.Empty) { return; } _DBMSType = DefaultString; _DBName = DefaultString; _password = DefaultString; _port = DefaultString; _target = DefaultString; _version = DefaultString; XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(BranchLocation + @"\OpenPetra.build.config"); _DBMSType = GetPropertyValue(xmlDoc, "DBMS.Type"); _DBName = GetPropertyValue(xmlDoc, "DBMS.DBName"); _password = GetPropertyValue(xmlDoc, "DBMS.Password"); _port = GetPropertyValue(xmlDoc, "DBMS.DBPort"); _target = GetPropertyValue(xmlDoc, "DBMS.DBHostOrFile"); if (String.Compare(_DBMSType, "postgresql", true) == 0) { _version = GetPropertyValue(xmlDoc, "PostgreSQL.Version"); } // Save the current configuration as a favourite SaveCurrentConfig(); } catch (Exception) { } }
/// <summary> /// Initializes a new instance of the <see cref="AzureWebHookStore"/> class with the given <paramref name="manager"/>, /// <paramref name="settings"/>, <paramref name="protector"/>, and <paramref name="logger"/>. /// Using this constructor, the data will be encrypted using the provided <paramref name="protector"/>. /// </summary> public AzureWebHookStore(IStorageManager manager, SettingsDictionary settings, IDataProtector protector, ILogger logger) : this(manager, settings, logger) { if (protector == null) { throw new ArgumentNullException(nameof(protector)); } _protector = protector; }
protected void UpdateSettings(FieldSettings model, SettingsDictionary settingsDictionary, string prefix) { model.HelpText = model.HelpText ?? string.Empty; settingsDictionary[prefix + ".HelpText"] = model.HelpText; settingsDictionary[prefix + ".Required"] = model.Required.ToString(); settingsDictionary[prefix + ".ReadOnly"] = model.ReadOnly.ToString(); settingsDictionary[prefix + ".AlwaysInLayout"] = model.AlwaysInLayout.ToString(); settingsDictionary[prefix + ".IsSystemField"] = model.IsSystemField.ToString(); settingsDictionary[prefix + ".IsAudit"] = model.IsAudit.ToString(); }
public override void CustomDeleteAction(string fieldType, string fieldName, SettingsDictionary settingsDictionary) { if (fieldType != "OptionSetField") { return; } var optionSet = _optionSetService.GetOptionSet(int.Parse(settingsDictionary["ReferenceFieldSettings.OptionSetId"])); if (optionSet == null) { return; } _optionSetService.DeleteOptionSet(optionSet); }
public override void UpdateFieldSettings(string fieldType, string fieldName, SettingsDictionary settingsDictionary, IUpdateModel updateModel) { if (fieldType != "PhoneField") { return; } var model = new PhoneFieldSettings(); if (updateModel.TryUpdateModel(model, "PhoneFieldSettings", null, null)) { UpdateSettings(model, settingsDictionary, "PhoneFieldSettings"); settingsDictionary["PhoneFieldSettings.DefaultValue"] = model.DefaultValue; } }
public ContentPartDefinitionBuilder(ContentPartDefinition existing) { if (existing == null) { _fields = new List<ContentPartFieldDefinition>(); _settings = new SettingsDictionary(); } else { _name = existing.Name; _fields = existing.Fields.ToList(); _settings = new SettingsDictionary(existing.Settings.ToDictionary(kv => kv.Key, kv => kv.Value)); } }
/// <summary> /// Maps a settings dictionary to an XML element. /// </summary> /// <param name="settingsDictionary">The settings dictionary.</param> /// <returns>The XML element.</returns> public XElement Map(SettingsDictionary settingsDictionary) { if (settingsDictionary == null) { return new XElement("settings"); } return new XElement( "settings", settingsDictionary .Where(kv => kv.Value != null) .Select(kv => new XAttribute(XmlConvert.EncodeLocalName(kv.Key), kv.Value))); }
public override void UpdateFieldSettings(string fieldType, string fieldName, SettingsDictionary settingsDictionary, IUpdateModel updateModel) { if (fieldType != "CoeveryTextField") { return; } var model = new CoeveryTextFieldSettings(); if (updateModel.TryUpdateModel(model, "CoeveryTextFieldSettings", null, null)) { UpdateSettings(model, settingsDictionary, "CoeveryTextFieldSettings"); settingsDictionary["CoeveryTextFieldSettings.MaxLength"] = model.MaxLength.ToString(); settingsDictionary["CoeveryTextFieldSettings.PlaceHolderText"] = model.PlaceHolderText; } }
public override void UpdateFieldSettings(ContentPartFieldDefinitionBuilder builder, SettingsDictionary settingsDictionary) { if (builder.FieldType != "PhoneField") { return; } var model = settingsDictionary.TryGetModel<PhoneFieldSettings>(); if (model != null) { UpdateSettings(model, builder, "PhoneFieldSettings"); builder.WithSetting("PhoneFieldSettings.DefaultValue", model.DefaultValue); } }
public override void UpdateFieldSettings(string fieldType, string fieldName, SettingsDictionary settingsDictionary, IUpdateModel updateModel) { if (fieldType != "BooleanField") { return; } var model = new BooleanFieldSettings(); if (updateModel.TryUpdateModel(model, "BooleanFieldSettings", null, null)) { UpdateSettings(model, settingsDictionary, "BooleanFieldSettings"); settingsDictionary["BooleanFieldSettings.SelectionMode"] = model.SelectionMode.ToString(); settingsDictionary["BooleanFieldSettings.DependencyMode"] = model.DependencyMode.ToString(); settingsDictionary["BooleanFieldSettings.DefaultValue"] = model.DefaultValue.ToString(); } }
public void CheckSqlStorageConnectionString_Throws_IfNullOrEmptyConnectionString(ConnectionSettings connectionSettings) { // Arrange SettingsDictionary settings = new SettingsDictionary(); settings.Connections.Add(WebHookStoreContext.ConnectionStringName, connectionSettings); // Act InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => SqlWebHookStore.CheckSqlStorageConnectionString(settings)); // Assert Assert.Equal("Please provide a SQL connection string with name 'MS_SqlStoreConnectionString' in the configuration string section of the 'Web.Config' file.", ex.Message); }
public override void UpdateFieldSettings(ContentPartFieldDefinitionBuilder builder, SettingsDictionary settingsDictionary) { if (builder.FieldType != "CoeveryTextField") { return; } var model = settingsDictionary.TryGetModel<CoeveryTextFieldSettings>(); if (model != null) { UpdateSettings(model, builder, "CoeveryTextFieldSettings"); builder.WithSetting("CoeveryTextFieldSettings.IsDispalyField", model.IsDispalyField.ToString()); builder.WithSetting("CoeveryTextFieldSettings.MaxLength", model.MaxLength.ToString()); builder.WithSetting("CoeveryTextFieldSettings.PlaceHolderText", model.PlaceHolderText); } }
public ContentTypeDefinitionBuilder(ContentTypeDefinition existing) { if (existing == null) { _parts = new List<ContentTypePartDefinition>(); _settings = new SettingsDictionary(); } else { _name = existing.Name; _displayName = existing.DisplayName; _parts = existing.Parts.ToList(); _settings = new SettingsDictionary(existing.Settings.ToDictionary(kv => kv.Key, kv => kv.Value)); } }
public override void UpdateFieldSettings(ContentPartFieldDefinitionBuilder builder, SettingsDictionary settingsDictionary) { if (builder.FieldType != "OptionSetField") { return; } var model = settingsDictionary.TryGetModel<OptionSetFieldSettings>(); if (model != null) { UpdateSettings(model, builder, "OptionSetFieldSettings"); builder.WithSetting("OptionSetFieldSettings.OptionSetId", model.OptionSetId.ToString()); builder.WithSetting("OptionSetFieldSettings.ListMode", model.ListMode.ToString()); } }
public override void UpdateFieldSettings(string fieldType, string fieldName, SettingsDictionary settingsDictionary, IUpdateModel updateModel) { if (fieldType != "NumberField") { return; } var model = new NumberFieldSettings(); if (updateModel.TryUpdateModel(model, "NumberFieldSettings", null, null)) { UpdateSettings(model, settingsDictionary, "NumberFieldSettings"); settingsDictionary["NumberFieldSettings.Length"] = model.Length.ToString("D"); settingsDictionary["NumberFieldSettings.DecimalPlaces"] = model.DecimalPlaces.ToString("D"); settingsDictionary["NumberFieldSettings.DefaultValue"] = model.DefaultValue.ToString(); } }
public static void AddOAuthAccount(this User user, string providerName, string providerUserId, string username, SettingsDictionary data = null) { var account = new OAuthAccount { Provider = providerName.ToLowerInvariant(), ProviderUserId = providerUserId, Username = username }; if (data != null) account.ExtraData.Apply(data); user.OAuthAccounts.Add(account); }
public override void UpdateFieldSettings(ContentPartFieldDefinitionBuilder builder, SettingsDictionary settingsDictionary) { if (builder.FieldType != "NumberField") { return; } var model = settingsDictionary.TryGetModel<NumberFieldSettings>(); if (model != null) { UpdateSettings(model, builder, "NumberFieldSettings"); builder.WithSetting("NumberFieldSettings.Length", model.Length.ToString()); builder.WithSetting("NumberFieldSettings.DecimalPlaces", model.DecimalPlaces.ToString()); builder.WithSetting("NumberFieldSettings.DefaultValue", model.DefaultValue.ToString()); } }
/// <summary> /// Must override this, this is the bit that matches up the designer properties to the dictionary values /// </summary> /// <param name="context"></param> /// <param name="collection"></param> /// <returns></returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { //load the file if (!_loaded) { _loaded = true; LoadValuesFromFile(); } //collection that will be returned. SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //itterate thought the properties we get from the designer, checking to see if the setting is in the dictionary foreach (SettingsProperty setting in collection) { SettingsPropertyValue value = new SettingsPropertyValue(setting); value.IsDirty = false; //need the type of the value for the strong typing var t = Type.GetType(setting.PropertyType.FullName); if (setting.PropertyType == typeof(System.Collections.Specialized.StringCollection)) { var xml = SettingsDictionary[setting.Name].value; var stringReader = new System.IO.StringReader(xml); var xmlreader = System.Xml.XmlReader.Create(stringReader); var ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.Specialized.StringCollection)); var obj = ser.Deserialize(xmlreader); var col = (System.Collections.Specialized.StringCollection)obj; value.PropertyValue = col; } else if (SettingsDictionary.ContainsKey(setting.Name)) { value.SerializedValue = SettingsDictionary[setting.Name].value; value.PropertyValue = Convert.ChangeType(SettingsDictionary[setting.Name].value, t); } else //use defaults in the case where there are no settings yet { value.SerializedValue = setting.DefaultValue; value.PropertyValue = Convert.ChangeType(setting.DefaultValue, t); } values.Add(value); } return(values); }
public void GetSettings_ReturnsDefaultInstance_IfEmptyDictionaryRegistered() { // Arrange SettingsDictionary instance = new SettingsDictionary(); instance.Clear(); _resolverMock.Setup(r => r.GetService(typeof(SettingsDictionary))) .Returns(instance) .Verifiable(); // Act SettingsDictionary actual = _resolverMock.Object.GetSettings(); // Assert Assert.NotSame(instance, actual); _resolverMock.Verify(); }
/// <summary> /// Initializes a new instance of the <see cref="SqlWebHookStore"/> class with the given <paramref name="settings"/> /// <paramref name="logger"/>, <paramref name="nameOrConnectionString"/>, <paramref name="schemaName"/> and <paramref name="tableName"/>. /// Using this constructor, the data will not be encrypted while persisted to the database. /// </summary> public SqlWebHookStore(SettingsDictionary settings, ILogger logger, string nameOrConnectionString, string schemaName, string tableName) : base(logger) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (string.IsNullOrEmpty(nameOrConnectionString)) { CheckSqlStorageConnectionString(settings); } _nameOrConnectionString = nameOrConnectionString; _schemaName = schemaName; _tableName = tableName; }
public void GetSettings_ReturnsDependencyInstance_IfRegistered() { // Arrange SettingsDictionary instance = new SettingsDictionary(); instance["key"] = "value"; _resolverMock.Setup(r => r.GetService(typeof(SettingsDictionary))) .Returns(instance) .Verifiable(); // Act SettingsDictionary actual = _resolverMock.Object.GetSettings(); // Assert Assert.Same(instance, actual); _resolverMock.Verify(); }
static void ConfigureConverter(SettingsDictionary settings, int channels, IntPtr converter) { Contract.Requires(settings != null); Contract.Requires(converter != IntPtr.Zero); // Set the quality if specified, otherwise select "High": Quality quality; if (string.IsNullOrEmpty(settings["Quality"]) || string.Compare(settings["Quality"], "High", StringComparison.OrdinalIgnoreCase) == 0) { quality = Quality.High; } else if (string.Compare(settings["Quality"], "Medium", StringComparison.OrdinalIgnoreCase) == 0) { quality = Quality.Medium; } else if (string.Compare(settings["Quality"], "Low", StringComparison.OrdinalIgnoreCase) == 0) { quality = Quality.Low; } else { throw new InvalidSettingException(string.Format(CultureInfo.CurrentCulture, Resources.AacSampleEncoderBadQuality, settings["Quality"])); } AudioConverterStatus status = SetConverterProperty(converter, AudioConverterPropertyId.CodecQuality, (uint)quality); if (status != AudioConverterStatus.Ok) { throw new IOException(string.Format(CultureInfo.CurrentCulture, Resources.SampleEncoderConverterQualityError, status)); } // Set a bitrate only if specified. Otherwise, default to a variable bitrate: if (!string.IsNullOrEmpty(settings["BitRate"])) { ConfigureConverterForBitRate(settings, channels, converter); } else { ConfigureConverterForQuality(settings, converter); } }
/// <summary> /// Loads the values of the file into memory. /// </summary> private void LoadValuesFromFile() { if (!File.Exists(UserConfigPath)) { //if the config file is not where it's supposed to be create a new one. CreateEmptyConfig(); } try { //load the xml var configXml = XDocument.Load(UserConfigPath); //get all of the <setting name="..." serializeAs="..."> elements. var settingElements = configXml.Element(CONFIG).Element(USER_SETTINGS) .Element(typeof(Settings).FullName)?.Elements(SETTING); if (settingElements is null) { File.Delete(UserConfigPath); LoadValuesFromFile(); return; } //iterate through, adding them to the dictionary, (checking for nulls, xml no likey nulls) //using "String" as default serializeAs...just in case, no real good reason. foreach (var element in settingElements) { var newSetting = new SettingStruct() { name = element.Attribute(NAME) == null ? String.Empty : element.Attribute(NAME).Value, serializeAs = element.Attribute(SERIALIZE_AS) == null ? "String" : element.Attribute(SERIALIZE_AS).Value, value = element.Value ?? String.Empty }; SettingsDictionary.Add(element.Attribute(NAME).Value, newSetting); } } catch { if (File.Exists(UserConfigPath)) { File.Delete(UserConfigPath); } } }
/// <summary> /// Configures a Microsoft Azure Table Storage implementation of <see cref="IWebHookStore"/> /// which provides a persistent store for registered WebHooks used by the custom WebHooks module. /// </summary> /// <param name="config">The current <see cref="HttpConfiguration"/>config.</param> public static void InitializeCustomWebHooksAzureStorage(this HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } WebHooksConfig.Initialize(config); ILogger logger = config.DependencyResolver.GetLogger(); SettingsDictionary settings = config.DependencyResolver.GetSettings(); IDataProtector protector = DataSecurity.GetDataProtector(); IStorageManager storageManager = StorageManager.GetInstance(logger); IWebHookStore store = new AzureWebHookStore(storageManager, settings, protector, logger); CustomServices.SetStore(store); }
public void Diff_OneValueChanges_CompatibleType_SameValue_ReturnsEmptySet() { SettingsDictionary settings1 = new SettingsDictionary { { Key1, BoolValue }, { Key2, IntValue }, }; SettingsDictionary settings2 = new SettingsDictionary { { Key1, BoolValue }, { Key2, (long)IntValue }, }; IReadOnlyDictionary <string, object> diff = settings1.Diff(settings2); Assert.AreEqual(0, diff.Count); }
static NativeOggStream IntializeOggStream(SettingsDictionary settings) { Contract.Requires(settings != null); int serialNumber; if (string.IsNullOrEmpty(settings["SerialNumber"])) { serialNumber = new Random().Next(); } else if (!int.TryParse(settings["SerialNumber"], out serialNumber) || serialNumber < 0) { throw new InvalidSettingException(string.Format(CultureInfo.CurrentCulture, Resources.SampleEncoderBadSerialNumber, settings["SerialNumber"])); } return(new NativeOggStream(serialNumber)); }
public ExceptionlessConfiguration(IDependencyResolver resolver) { ServerUrl = DEFAULT_SERVER_URL; UserAgent = DEFAULT_USER_AGENT; Enabled = true; EnableSSL = true; DefaultTags = new TagSet(); DefaultData = new DataDictionary(); Settings = new SettingsDictionary(); SubmissionBatchSize = 50; if (resolver == null) { throw new ArgumentNullException("resolver"); } _resolver = resolver; EventEnrichmentManager.AddDefaultEnrichments(this); }
internal static IDictionary <string, string> ReadSettings(SettingsDictionary settings, ILogger logger) { IDictionary <string, string> config = new Dictionary <string, string>(); foreach (var setting in settings) { var key = setting.Key; if (key.Length > ConfigKeyPrefix.Length && key.StartsWith(ConfigKeyPrefix, StringComparison.OrdinalIgnoreCase)) { // Extract receiver name var receiver = key.Substring(ConfigKeyPrefix.Length); // Parse values var segments = setting.Value.SplitAndTrim(','); foreach (var segment in segments) { var values = segment.SplitAndTrim('='); if (values.Length == 1) { AddKey(config, logger, receiver, string.Empty, values[0]); } else if (values.Length == 2) { AddKey(config, logger, receiver, values[0], values[1]); } else { var message = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Config_BadValue, key); logger.Error(message); throw new InvalidOperationException(message); } } } } if (config.Count == 0) { var format = ConfigKeyPrefix + "<receiver>"; var message = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Config_NoConfig, format); logger.Error(message); } return(config); }
// TODO: Add support for user public key token on signed assemblies public ErrorSignature(Error error, IEnumerable <string> userNamespaces = null, IEnumerable <string> userCommonMethods = null, bool emptyNamespaceIsUserMethod = true, bool shouldFlagSignatureTarget = true) { Error = error ?? throw new ArgumentNullException(nameof(error)); _userNamespaces = userNamespaces == null ? new HashSet <string>() : new HashSet <string>(userNamespaces); _userCommonMethods = userCommonMethods == null ? new HashSet <string>() : new HashSet <string>(userCommonMethods); EmptyNamespaceIsUserMethod = emptyNamespaceIsUserMethod; SignatureInfo = new SettingsDictionary(); ShouldFlagSignatureTarget = shouldFlagSignatureTarget; Parse(); }
public void KeyTransformation() { var dict = new SettingsDictionary() { [":prod.a"] = "a:prod", ["a:prod.b"] = "a.b:prod", ["a.b:prod.c"] = "a.b.c:prod", ["a.b.c:prod"] = "a.b.c:prod", ["a.b"] = "a.b", ["a"] = "a" }; var transformed = dict.WithNormalizedEnvironmentQualifiers(); foreach (var key in transformed.Keys) { Assert.AreEqual(key, transformed[key]); } }
public void Diff_OneValueChanges_CompatibleType_DifferntValue_ReturnsChangedValue() { SettingsDictionary settings1 = new SettingsDictionary { { Key1, BoolValue }, { Key2, IntValue }, }; SettingsDictionary settings2 = new SettingsDictionary { { Key1, BoolValue }, { Key2, IntValue + 1 }, }; IReadOnlyDictionary <string, object> diff = settings1.Diff(settings2); Assert.AreEqual(1, diff.Count); Assert.AreEqual(IntValue + 1, diff[Key2]); }
/// <summary> /// Initializes a new instance of the <see cref="AzureWebHookStore"/> class with the given <paramref name="manager"/>, /// <paramref name="settings"/>, and <paramref name="logger"/>. /// Using this constructor, the data will not be encrypted while persisted to Azure Storage. /// </summary> public AzureWebHookStore(IStorageManager manager, SettingsDictionary settings, ILogger logger) { if (manager == null) { throw new ArgumentNullException(nameof(manager)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _manager = manager; _connectionString = manager.GetAzureStorageConnectionString(settings); _logger = logger; }
public void set(string key, string value) { SystemSetting setting; if (SettingsDictionary.ContainsKey(key)) { setting = SettingsDictionary[key]; } else { setting = new SystemSetting(); setting.Name = key; SettingsDictionary[key] = setting; } setting.Value = value; setting.Commit(); }
public void InitialEnvironment() { var dictionary = new SettingsDictionary() { ["env"] = "staging", ["ExampleSettings.MyTimeSpan:staging"] = "00:15:00", ["ExampleSettings.MyTimeSpan"] = "00:10:00", ["ExampleSettings.RequiredInt"] = "200", ["ExampleSettings.MyReadonlyIntProperty"] = "200" }; var settings = new SettingsBuilder() .UseSettingsDictionary(dictionary) .SetEnvironment("${ENV}") .Build <ExampleSettings>(); Assert.AreEqual(TimeSpan.FromMinutes(15), settings.MyTimeSpan); Assert.AreEqual("staging", settings.Environment); }
private void Initialize() { if (_initialized) { return; } _initialized = true; if (!File.Exists(path)) { return; } _dictionary = null; _cachedJson = File.ReadAllText(path); EditorJsonUtility.FromJsonOverwrite(_cachedJson, this); _dictionary ??= new SettingsDictionary(); }
/// <summary> /// Initializes a new instance of the <see cref="SqlWebHookStore"/> class with the given <paramref name="settings"/>, /// <paramref name="protector"/>, and <paramref name="logger"/>. /// </summary> public SqlWebHookStore(SettingsDictionary settings, IDataProtector protector, ILogger logger) { if (settings == null) { throw new ArgumentNullException("settings"); } if (protector == null) { throw new ArgumentNullException("protector"); } if (logger == null) { throw new ArgumentNullException("logger"); } CheckSqlStorageConnectionString(settings); _protector = protector; _logger = logger; }
/// <summary> /// Must override this, this is the bit that matches up the designer properties to the dictionary values /// </summary> /// <param name="context"></param> /// <param name="collection"></param> /// <returns></returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { //load the file if (!_loaded) { _loaded = true; LoadValuesFromFile(); } //collection that will be returned. SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //iterate thought the properties we get from the designer, checking to see if the setting is in the dictionary foreach (SettingsProperty setting in collection) { SettingsPropertyValue value = new SettingsPropertyValue(setting); value.IsDirty = false; //need the type of the value for the strong typing var t = Type.GetType(setting.PropertyType.FullName); if (SettingsDictionary.ContainsKey(setting.Name)) { value.SerializedValue = SettingsDictionary[setting.Name].value; try { value.PropertyValue = Convert.ChangeType(SettingsDictionary[setting.Name].value, t); } catch { value.PropertyValue = Convert.ChangeType(setting.DefaultValue, t); } } else //use defaults in the case where there are no settings yet { value.SerializedValue = setting.DefaultValue; value.PropertyValue = Convert.ChangeType(setting.DefaultValue, t); } values.Add(value); } return(values); }
static byte[] GenerateIlst(Mp4 originalMp4, MetadataDictionary metadata, SettingsDictionary settings) { Contract.Requires(originalMp4 != null); Contract.Requires(metadata != null); Contract.Requires(settings != null); Contract.Ensures(Contract.Result <byte[]>() != null); using (var resultStream = new MemoryStream()) { var adaptedMetadata = new MetadataToAtomAdapter(metadata, settings); // "Reverse DNS" atoms may need to be preserved: foreach (ReverseDnsAtom reverseDnsAtom in from listAtom in originalMp4.GetChildAtomInfo() where listAtom.FourCC == "----" select new ReverseDnsAtom(originalMp4.ReadAtom(listAtom))) { switch (reverseDnsAtom.Name) { // Always preserve the iTunSMPB (gapless playback) atom: case "iTunSMPB": resultStream.Write(reverseDnsAtom.GetBytes(), 0, reverseDnsAtom.GetBytes().Length); break; // Preserve the existing iTunNORM atom if a new one isn't provided, and AddSoundCheck isn't explicitly False: case "iTunNORM": if (!adaptedMetadata.IncludesSoundCheck && string.Compare(settings["AddSoundCheck"], bool.FalseString, StringComparison.OrdinalIgnoreCase) != 0) { resultStream.Write(reverseDnsAtom.GetBytes(), 0, reverseDnsAtom.GetBytes().Length); } break; } } byte[] atomData = adaptedMetadata.GetBytes(); resultStream.Write(atomData, 0, atomData.Length); return(resultStream.ToArray()); } }
public void LogLevels_GetMinLogLevel_Settings_Order() { var settings = new SettingsDictionary { { "@@log:", "Info" }, { "@@log:*", "Debug" } }; Assert.Equal(LogLevel.Info, settings.GetMinLogLevel(null)); Assert.Equal(LogLevel.Info, settings.GetMinLogLevel(String.Empty)); Assert.Equal(LogLevel.Debug, settings.GetMinLogLevel("*")); settings = new SettingsDictionary { { "@@log:*", "Debug" }, { "@@log:", "Info" } }; Assert.Equal(LogLevel.Info, settings.GetMinLogLevel(String.Empty)); Assert.Equal(LogLevel.Debug, settings.GetMinLogLevel("*")); settings = new SettingsDictionary { { "@@log:*", "Fatal" }, { "@@log:", "Debug" }, { "@@log:abc*", "Off" }, { "@@log:abc.de*", "Debug" }, { "@@log:abc.def*", "Info" }, { "@@log:abc.def.ghi", "Trace" } }; Assert.Equal(LogLevel.Fatal, settings.GetMinLogLevel("other")); Assert.Equal(LogLevel.Debug, settings.GetMinLogLevel(null)); Assert.Equal(LogLevel.Debug, settings.GetMinLogLevel(String.Empty)); Assert.Equal(LogLevel.Off, settings.GetMinLogLevel("abc")); Assert.Equal(LogLevel.Info, settings.GetMinLogLevel("abc.def")); Assert.Equal(LogLevel.Trace, settings.GetMinLogLevel("abc.def.ghi")); settings = new SettingsDictionary { { "@@log:abc.def.ghi", "Trace" }, { "@@log:abc.def*", "Info" }, { "@@log:abc*", "Off" } }; Assert.Equal(LogLevel.Off, settings.GetMinLogLevel("abc")); Assert.Equal(LogLevel.Info, settings.GetMinLogLevel("abc.def")); Assert.Equal(LogLevel.Trace, settings.GetMinLogLevel("abc.def.ghi")); }
public void CanGetLogSettingsMultithreaded() { var settings = new SettingsDictionary { { "@@log:*", "Info" }, { "@@log:Source1", "Trace" }, { "@@log:Source2", "Debug" }, { "@@log:Source3", "Info" }, { "@@log:Source4", "Info" } }; var result = Parallel.For(0, 100, index => { var level = settings.GetMinLogLevel("Source1"); _writer.WriteLine("Source1 log level: {0}", level); }); while (!result.IsCompleted) { Thread.Yield(); } }
public ExceptionlessConfiguration(IDependencyResolver resolver) { ServerUrl = DEFAULT_SERVER_URL; UserAgent = DEFAULT_USER_AGENT; SubmissionBatchSize = DEFAULT_SUBMISSION_BATCH_SIZE; Enabled = true; EnableSSL = true; QueueMaxAge = TimeSpan.FromDays(7); QueueMaxAttempts = 3; DefaultTags = new TagSet(); DefaultData = new DataDictionary(); Settings = new SettingsDictionary(); if (resolver == null) { throw new ArgumentNullException("resolver"); } _resolver = resolver; EventPluginManager.AddDefaultPlugins(this); }
public string get(string key) { string result; if (SettingsDictionary == null) { globalInstance.LoadData(); } if (SettingsDictionary.ContainsKey(key)) { result = SettingsDictionary[key].Value; } else { result = null; } return(result); }
/// <summary> /// Entrypoint for the Plugin Task Execution for HPAC Client Plugin /// </summary> /// <param name="executionData"></param> /// <returns></returns> public PluginExecutionResult Execute(PluginExecutionData executionData) { _activityData = executionData.GetMetadata <HpacClientActivityData>(); _pluginSettings = executionData.Environment.PluginSettings; _hpacServerIP = executionData.Servers.FirstOrDefault().Address; try { LocalLockToken hpacClientLockToken = new LocalLockToken("HPACClient", new LockTimeoutData(TimeSpan.FromSeconds(60), TimeSpan.FromMinutes(10))); ExecutionServices.CriticalSection.Run(hpacClientLockToken, PluginTaskExecution); } catch (Exception exception) { return(new PluginExecutionResult(PluginResult.Failed, exception.Message)); } return(new PluginExecutionResult(PluginResult.Passed)); }
/// <summary> /// Configures a Microsoft SQL Server Storage implementation of <see cref="IWebHookStore"/> /// which provides a persistent store for registered WebHooks used by the custom WebHooks module. /// </summary> /// <param name="config">The current <see cref="HttpConfiguration"/>config.</param> public static void InitializeCustomWebHooksSqlStorage(this HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } WebHooksConfig.Initialize(config); ILogger logger = config.DependencyResolver.GetLogger(); SettingsDictionary settings = config.DependencyResolver.GetSettings(); // We explicitly set the DB initializer to null to avoid that an existing DB is initialized wrongly. Database.SetInitializer <WebHookStoreContext>(null); IDataProtector protector = DataSecurity.GetDataProtector(); IWebHookStore store = new SqlWebHookStore(settings, protector, logger); CustomServices.SetStore(store); }
public void UnqualifiedKeyInLowerLayerHidesQualifiedKeysInLayersAbove() { var cd = new CompositeSettingsDictionary(); var first = new SettingsDictionary() { ["a"] = "a" }; var second = new SettingsDictionary() { ["a:prod"] = "b" }; cd.Add(first); cd.Add(second); bool found = cd.TryGetValue("a", "prod", out var result); Assert.IsTrue(found); Assert.AreEqual("a", result); }
public void KeyInLowerLayerHidesOtherKeys() { var cd = new CompositeSettingsDictionary(); var first = new SettingsDictionary() { ["a"] = "a" }; var second = new SettingsDictionary() { ["a"] = "b" }; cd.Add(first); cd.Add(second); bool found = cd.TryGetValue("a", null, out var result); Assert.IsTrue(found); Assert.AreEqual("a", result); }
/// <summary> /// Must override this, this is the bit that matches up the designer properties to the dictionary values /// </summary> /// <param name="context"></param> /// <param name="collection"></param> /// <returns></returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { //load the file if (!_loaded) { _loaded = true; LoadValuesFromFile(); } //collection that will be returned. SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //itterate thought the properties we get from the designer, checking to see if the setting is in the dictionary foreach (SettingsProperty setting in collection) { SettingsPropertyValue value = new SettingsPropertyValue(setting); value.IsDirty = false; //need the type of the value for the strong typing var t = GetType(setting.PropertyType.FullName); if (SettingsDictionary.ContainsKey(setting.Name)) { value.SerializedValue = SettingsDictionary[setting.Name].value; // http://stackoverflow.com/questions/393731/generic-conversion-function-doesnt-seem-to-work-with-guids value.PropertyValue = TypeDescriptor.GetConverter(t).ConvertFromInvariantString(SettingsDictionary[setting.Name].value); //value.PropertyValue = Convert.ChangeType(SettingsDictionary[setting.Name].value, t); } else //use defaults in the case where there are no settings yet { value.SerializedValue = setting.DefaultValue; // http://stackoverflow.com/questions/393731/generic-conversion-function-doesnt-seem-to-work-with-guids value.PropertyValue = TypeDescriptor.GetConverter(t).ConvertFromInvariantString((string)setting.DefaultValue); // value.PropertyValue = Convert.ChangeType(setting.DefaultValue, t); } values.Add(value); } return(values); }