public Stream OpenFile(string filename, bool forceReload) { if (!_files.Contains(filename) || forceReload) { StreamReader sr = new StreamReader(filename); _currentBufferSize += sr.BaseStream.Length; EnsureCapacity(); _files.Add(filename, CloneStream(sr.BaseStream)); sr.Close(); } return(_files[filename]); }
/// <summary> /// Evaluates the rule against the specified list of attribute changes /// </summary> /// <param name="attributeChanges">The list of attribute changes made to the object</param> /// <returns>A value indicating whether the conditions of the rule were met</returns> private bool EvaulateRuleOnAttributeChanges(KeyedCollection <string, AttributeChange> attributeChanges) { if (attributeChanges.Contains(this.Attribute.Name)) { if (this.TriggerEvents == Acma.TriggerEvents.None) { this.RaiseRuleFailure("An attribute change was present for attribute: {{{0}}}", this.Attribute.Name); return(false); } else if (this.EvaluateRuleOnAttributeChange(attributeChanges[this.Attribute.Name])) { return(true); } else { this.RaiseRuleFailure("The change type on {{{0}}} was not one of the specified trigger events: {1}", this.Attribute.Name, this.TriggerEvents.ToSmartString()); return(false); } } else { if (this.TriggerEvents == Acma.TriggerEvents.None) { return(true); } else { this.RaiseRuleFailure("{{{0}}} was not in the list of attribute changes for the object", this.Attribute.Name); return(false); } } }
/// <summary> /// Retrieves the configuration section and identifies if the section data has changeds /// </summary> /// <param name="traceId">A unique identifier used to correlate debugging and diagnostics messages</param> /// <param name="sections">Collection of keyed ConfigurationSections.</param> void LoadConfigurationSection(Guid traceId, KeyedCollection <string, ConfigurationSection> sections) { if (sections.Contains(this.serviceNameUri.AbsoluteUri)) { this.logger.Verbose(traceId, ComponentName, "Configuration for service found ({0})", new object[] { this.serviceNameUri.AbsoluteUri }); ConfigurationSection section = sections[this.serviceNameUri.AbsoluteUri]; // Create an MD5 to hash the values to determine if they have changed. using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(section.ToString())); if (!this.CompareHashes(hash, this.configSectionHash)) { this.logger.Informational(traceId, ComponentName, "MD5 matched"); // Set the provider values. this.configSection = section; this.configSectionHash = hash; // If necessary, call the property changed event. this.ConfigurationPropertyChangedEvent?.Invoke(this, EventArgs.Empty); } else { this.logger.Verbose(traceId, ComponentName, "MD5 matched"); } } } else { this.logger.Informational(traceId, ComponentName, "Configuration for service not found ({0})", new object[] { this.serviceNameUri.AbsoluteUri }); } }
/// <summary> /// Creates Animations from a xnaMugen.IO.TextFile. /// </summary> /// <param name="textfile">A textfile whose xnaMugen.IO.TextSection can be used to create Animations.</param> /// <returns>A collection of Animations created from the supplied textfile.</returns> public KeyedCollection <Int32, Animation> LoadAnimations(TextFile textfile) { if (textfile == null) { throw new ArgumentNullException("textfile"); } KeyedCollection <Int32, Animation> animations = new KeyedCollection <Int32, Animation>(x => x.Number); foreach (TextSection section in textfile) { Animation animation = CreateAnimation(section); if (animation != null) { if (animations.Contains(animation.Number) == false) { animations.Add(animation); } else { Log.Write(LogLevel.Warning, LogSystem.AnimationSystem, "Duplicate animation #{0}. Discarding duplicate.", animation.Number); } } } return(animations); }
public virtual PluginBase LoadPlugin(PluginLoadInfo plugin) { if (this.PluginsLoaded.Contains(plugin.ClassName)) { return(this.PluginsLoaded[plugin.ClassName]); } Assembly ass = null; if (_Assemblies.Contains(plugin.Filename)) { ass = _Assemblies[plugin.Filename]; } else { string path = Path.Combine(this.AssemblySearchPath, plugin.Filename); ass = Assembly.LoadFile(path); _Assemblies.Add(plugin.Filename, ass); } PluginBase plug = (PluginBase)ass.CreateInstance(plugin.ClassName); this.PluginsLoaded.Add(plugin.ClassName, plug); if (plug.ShowMenuItem) { AddToPluginsMenu(plug); } return(plug); }
/// <summary> /// Loads the configuration. /// </summary> /// <param name="path">Path to the directory containing configuration information.</param> /// <param name="sections">Collection of keyed ConfigurationSections.</param> /// <remarks>Loads the configuration with the same name as the service type (e.g. [ServiceTypeName].XML. This /// method was constructed this way to enable some level of unit testing. ConfigurationSection cannot be created or mocked.</remarks> internal void LoadConfiguration(string path, KeyedCollection <string, ConfigurationSection> sections) { Guard.ArgumentNotNullOrWhitespace(path, nameof(path)); Guard.ArgumentNotNull(sections, nameof(sections)); _eventSource?.ServicePartitionConfigurationChanged(_serviceName, _partitionId, _replicaOrInstanceId); try { // Create an MD5 to hash the values to determine if they have changed. using (MD5 md5 = MD5.Create()) { // First load the configuration section for this service type. if (sections.Contains(_serviceNameUri.AbsoluteUri)) { // Get the section and calculate the hash. ConfigurationSection section = sections[_serviceNameUri.AbsoluteUri]; string sectionContent = string.Join("|", section.Parameters.Select(p => $"{p.Name}~{p.Value}")); byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(sectionContent)); if (false == CompareHashes(hash, _configSectionHash)) { // Set the provider values. _configSection = section; _configSectionHash = hash; // If necessary, call the property changed event. OnConfigurationPropertyChangedEvent?.Invoke(this, EventArgs.Empty); } } // Second, attempt to load a file of the format <service name>.json. Use the last segment of the service name Uri for the file name. string filepath = Path.Combine(path, $"{_serviceName}.json"); // Stream the file while calculating the MD5 hash of the contents. using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) using (CryptoStream cs = new CryptoStream(fs, md5, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(cs)) { string json = reader.ReadToEnd(); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new IsoDateTimeConverter()); TConfiguration result = JsonConvert.DeserializeObject <TConfiguration>(json, settings); byte[] fileHash = md5.Hash; if (false == CompareHashes(fileHash, _configFileHash)) { // If necessary, call the class changed event. OnConfigurationClassChangedEvent?.Invoke(this, new ConfigurationClassChangedEventArgs <TConfiguration>(_serviceName, _configFile, result)); // Set the provider values. _configFileHash = fileHash; _configFile = result; } } } } catch (FileNotFoundException) { } }
public ProxyHandler(ConfigurationSettings configSettings) { KeyedCollection <string, ConfigurationProperty> parameters = configSettings.Sections["WebServiceConfig"].Parameters; if (parameters.Contains("SecureClusterCertThumbprint")) { this.secureClusterCertThumbprint = parameters["SecureClusterCertThumbprint"].Value; } }
/// <summary> /// Gets a value indicating whether a variable exists in this document. /// </summary> /// <param name="varName"> /// The name of the variable in question. /// </param> /// <returns> /// True if the variable already exists in the document. False otherwise. /// </returns> public bool Contains(string varName) { if (varName == null || varName.Length == 0) { throw new ArgumentNullException("varName"); } return(variablesLookup.Contains(varName)); }
internal static SecureString GetEncryptedParameterValue(KeyedCollection <string, ConfigParameter> configParameters, string keyName) { if (configParameters.Contains(keyName) && configParameters[keyName].IsEncrypted) { return(configParameters[keyName].SecureValue); } throw new ExtensibleExtensionException($"Expected encrypted parameter was not found: {keyName}"); }
/// <summary> /// Attempts to add a new option. /// </summary> /// <typeparam name="T">The type of option to add.</typeparam> /// <param name="option">The option to add.</param> /// <returns>True if the option was added; otherwise, false.</returns> /// <remarks>This method can be used to handle a scenarios where an option /// of the same type might be added more than once.</remarks> public bool TryAdd <T>(T option) where T : class { if (items.Contains(option.GetType())) { return(false); } items.Add(option); return(true); }
public TItem GetItem(TKey key) { TItem item = default(TItem); if (_buffer.Contains(key)) { item = _buffer[key]; } return(item); }
public static bool GetBoolValueOrDefault(this KeyedCollection <string, ConfigParameter> parameters, string parameterName, bool defaultValue) { if (!parameters.Contains(parameterName)) { return(defaultValue); } ConfigParameter p = parameters[parameterName]; return(p.Value == "1"); }
/// <summary> /// Processes an attribute delete request on the specified CSEntryChange /// </summary> /// <param name="csentry">The CSEntryChange to process</param> /// <param name="attribute">The attribute associated with this request</param> public static void DeleteAttribute(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute) { if (attributeChanges.Contains(attribute.Name)) { ConvertAttributeChangeToDelete(attributeChanges, objectModificationType, attribute, attributeChanges[attribute.Name]); } else { CreateAttributeChangeDelete(attributeChanges, objectModificationType, attribute); } }
public static bool TryGetValue <TKey, TValue>(this KeyedCollection <TKey, TValue> self, TKey key, out TValue item) { item = default; if (!self.Contains(key)) { return(false); } item = self[key]; return(true); }
public static string TryReadConfigurationString(this KeyedCollection <string, ConfigurationProperty> parameters, string parameterName) { if (parameters.Contains(parameterName)) { return(parameters[parameterName].Value); } else { return(null); } }
private static void RemoveAttributeChangeIfEmpty(this KeyedCollection <string, AttributeChange> attributeChanges, string attributeName) { if (attributeChanges.Contains(attributeName)) { AttributeChange change = attributeChanges[attributeName]; if (change.ValueChanges.Count == 0 && change.ModificationType != AttributeModificationType.Delete) { attributeChanges.Remove(attributeName); } } }
IDictionary <string, string> IGetSettings.GetSettings(string sectionName) { if (!_configurationSections.Contains(sectionName)) { throw new ArgumentException( $"Section with specified name '{sectionName}' cannot be found in the Service Fabric application configuration."); } return(_configurationSections[sectionName] .Parameters .ToDictionary(k => k.Name, v => v.Value)); }
/// <summary> /// Gets the config section /// </summary> /// <param name="context">Code package activation context</param> /// <param name="sectionName">Name of the section to get</param> /// <param name="configurationPackageName">Name of the config package</param> /// <returns>Config section</returns> public static ConfigurationSection GetConfigurationSection(this ICodePackageActivationContext context, string sectionName, string configurationPackageName = "Config") { if (context == null) { throw new ArgumentNullException(nameof(context)); } ConfigurationPackage package = context.GetConfigurationPackageObject(configurationPackageName); KeyedCollection <string, ConfigurationSection> configSettings = package.Settings.Sections; return(configSettings.Contains(sectionName) ? configSettings[sectionName] : null); }
public static void AddOrReplaceAttributeChange(this KeyedCollection <string, AttributeChange> attributeChanges, AttributeChange newAttributeChange) { if (!attributeChanges.Contains(newAttributeChange.Name)) { attributeChanges.Add(newAttributeChange); } else { attributeChanges.Remove(newAttributeChange.Name); attributeChanges.Add(newAttributeChange); } }
/// <summary> /// Returns the endpoint description with the provided name, throwing an exception if it is not present. /// </summary> /// <param name="endpoints">The endpoint collection.</param> /// <param name="endpointName">the name of the endpoint to return.</param> /// <returns>The endpoint with the provided name.</returns> /// <exception cref="KeyNotFoundException">The endpoint with the provided name was not found.</exception> private static EndpointResourceDescription GetEndpoint( KeyedCollection<string, EndpointResourceDescription> endpoints, string endpointName) { if (!endpoints.Contains(endpointName)) { throw new KeyNotFoundException( $"Endpoint \"{endpointName}\" not found in service manifest. Ensure the service has a TCP endpoint with that name."); } return endpoints[endpointName]; }
public async void DoRefresh() { Exception exception = null; try { IEnumerable <Server> newServers = await _serverList.Refresh(); ISet <ServerObservable> removedServers = new HashSet <ServerObservable>(_servers.Values); foreach (Server serverData in newServers) { ServerObservable server = Mapper.Map <Server, ServerObservable>(serverData); if (_servers.Contains(server.Key)) { ServerObservable existingServer = _servers[serverData.Address]; Mapper.Map(server, existingServer); } else { _servers.Add(server); } removedServers.Remove(server); } foreach (ServerObservable serverData in removedServers) { _servers.Remove(serverData.Key); } DoPingAll(); } catch (Exception e) { exception = e; } if (exception != null) { await _popupService.ShowMessageBox("Error refreshing server list", "Could not refresh the server list. " + exception.Message, MessageBoxImage.Error); } }
public static void Verify <TKey, TValue>( this KeyedCollection <TKey, TValue> collection, TKey[] expectedKeys, TValue[] expectedItems, TValue[] expectedItemsWithKeys) { if (expectedItemsWithKeys.Length != expectedKeys.Length) { throw new ArgumentException( "Expected Keys length and Expected Items length must be the same"); } Assert.Equal(expectedItems.Length, collection.Count); // uses enumerator CollectionAssert.Equal(expectedItems, collection); // use int indexer for (var i = 0; i < expectedItems.Length; ++i) { Assert.Equal(expectedItems[i], collection[i]); } // use key indexer for (var i = 0; i < expectedItemsWithKeys.Length; ++i) { Assert.Equal( expectedItemsWithKeys[i], collection[expectedKeys[i]]); } // check that all keys are contained Assert.DoesNotContain( expectedKeys, key => !collection.Contains(key)); // check that all values are contained Assert.DoesNotContain( expectedItems, item => !collection.Contains(item)); }
public static bool TryReadConfiguration(this KeyedCollection <string, ConfigurationProperty> parameters, string parmaeterName, out ConfigurationProperty value) { if (parameters.Contains(parmaeterName)) { value = parameters[parmaeterName]; return(true); } else { value = null; return(false); } }
/// <summary> /// Validates the configuration file parameters, and ensures the configuration file is valid and can be opened /// </summary> /// <param name="configParameters">The configuration parameters from the user interface</param> /// <param name="page">The configuration page</param> /// <returns>A ParameterValidationResult containing the validation status</returns> public static ParameterValidationResult ValidateConfigFile(KeyedCollection <string, ConfigParameter> configParameters, ConfigParameterPage page) { ParameterValidationResult myResults = new ParameterValidationResult(); string path = string.Empty; if (!configParameters.Contains(MAParameterNames.MAConfigurationFile)) { myResults.Code = ParameterValidationResultCode.Failure; myResults.ErrorMessage = "A configuration file must be specified"; myResults.ErrorParameter = MAParameterNames.MAConfigurationFile; return(myResults); } else { path = configParameters[MAParameterNames.MAConfigurationFile].Value; if (!System.IO.Path.IsPathRooted(path)) { path = System.IO.Path.Combine(Utils.ExtensionsDirectory, path); } } if (!System.IO.File.Exists(path)) { myResults.Code = ParameterValidationResultCode.Failure; myResults.ErrorMessage = "The configuration file does not exist"; myResults.ErrorParameter = MAParameterNames.MAConfigurationFile; return(myResults); } else { try { MAConfig.Load(path); } catch (Exception ex) { myResults.Code = ParameterValidationResultCode.Failure; myResults.ErrorMessage = string.Format("The configuration file could not be loaded\n{0}\n{1}", ex.Message, ex.InnerException == null ? string.Empty : ex.InnerException.Message); myResults.ErrorParameter = MAParameterNames.MAConfigurationFile; return(myResults); } } myResults.Code = ParameterValidationResultCode.Success; return(myResults); }
internal static bool TryGetValue( this KeyedCollection <string, CsvProperty> kColl, string key, [NotNullWhen(true)] out CsvProperty?value) { Debug.Assert(kColl != null); Debug.Assert(key != null); if (kColl.Contains(key)) { value = kColl[key]; return(true); } value = null; return(false); }
protected override ICommunicationListener CreateCommunicationListener() { ConfigurationSettings configSettings = this.ServiceInitializationParameters.CodePackageActivationContext.GetConfigurationPackageObject("Config").Settings; KeyedCollection <string, ConfigurationProperty> parameters = configSettings.Sections["WebServiceConfig"].Parameters; string appRoot = "dartShooting"; if (parameters.Contains("appRoot")) { appRoot = parameters["appRoot"].Value; } // TODO: Replace this with an ICommunicationListener implementation if your service needs to handle user requests. return(new OwinCommunicationListener(appRoot, new StartUp(configSettings)));; }
public StateManager CreateManager(Combat.Character character, ReadOnlyList <String> filepaths) { if (character == null) { throw new ArgumentNullException("character"); } if (filepaths == null) { throw new ArgumentNullException("filepaths"); } KeyedCollection <Int32, State> states = new KeyedCollection <Int32, State>(x => x.Number); foreach (String filepath in filepaths) { ReadOnlyKeyedCollection <Int32, State> loadedstates = GetStates(filepath); foreach (State state in loadedstates) { if (states.Contains(state.Number) == true) { states.Remove(state.Number); } states.Add(state); } } foreach (State state in m_internalstates) { if (states.Contains(state.Number) == false) { states.Add(state); } } return(new StateManager(this, character, new ReadOnlyKeyedCollection <Int32, State>(states))); }
public StateManager CreateManager(Combat.Character character, ReadOnlyList <string> filepaths) { if (character == null) { throw new ArgumentNullException(nameof(character)); } if (filepaths == null) { throw new ArgumentNullException(nameof(filepaths)); } var states = new KeyedCollection <int, State>(x => x.Number); foreach (var filepath in filepaths) { var loadedstates = GetStates(filepath); foreach (var state in loadedstates) { if (states.Contains(state.Number)) { states.Remove(state.Number); } states.Add(state); } } foreach (var state in _internalstates) { if (states.Contains(state.Number) == false) { states.Add(state); } } return(new StateManager(this, character, new ReadOnlyKeyedCollection <int, State>(states))); }
public StateManager CreateManager(Combat.Character character, ReadOnlyList<String> filepaths) { if (character == null) throw new ArgumentNullException("character"); if (filepaths == null) throw new ArgumentNullException("filepaths"); KeyedCollection<Int32, State> states = new KeyedCollection<Int32, State>(x => x.Number); foreach (String filepath in filepaths) { ReadOnlyKeyedCollection<Int32, State> loadedstates = GetStates(filepath); foreach (State state in loadedstates) { if (states.Contains(state.Number) == true) states.Remove(state.Number); states.Add(state); } } foreach (State state in m_internalstates) { if (states.Contains(state.Number) == false) states.Add(state); } return new StateManager(this, character, new ReadOnlyKeyedCollection<Int32, State>(states)); }
public static string GetParamString(this KeyedCollection <string, ConfigParameter> parameters, string name) { if (!parameters.Contains(name)) { throw new KeyNotFoundException($"A configuration parameter with the name {name} could not be found"); } var v = parameters[name]; if (v.IsEncrypted) { return(v.SecureValue.ConvertToUnsecureString()); } return(v.Value); }
/// <summary> /// Processes an attribute update request on the specified CSEntryChange /// </summary> /// <param name="csentry">The CSEntryChange to process</param> /// <param name="attribute">The attribute associated with this request</param> /// <param name="valueChanges">The value changes to apply to the attribute</param> public static void UpdateAttribute(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges) { if (valueChanges == null) { throw new ArgumentNullException("valueChanges"); } if (!attribute.IsMultivalued && valueChanges.Count(t => t.ModificationType == ValueModificationType.Add) > 1) { throw new TooManyValuesException(attribute.Name); } valueChanges = RemoveDuplicateValueChanges(attribute, valueChanges); if (attributeChanges.Contains(attribute.Name)) { AttributeChange existingChange = attributeChanges[attribute.Name]; switch (existingChange.ModificationType) { case AttributeModificationType.Add: ConvertAttributeChangeUpdateFromAdd(attributeChanges, objectModificationType, attribute, valueChanges, existingChange); break; case AttributeModificationType.Delete: ConvertAttributeChangeUpdateFromDelete(attributeChanges, objectModificationType, attribute, valueChanges, existingChange); break; case AttributeModificationType.Replace: ConvertAttributeChangeUpdateFromReplace(attributeChanges, objectModificationType, attribute, valueChanges, existingChange); break; case AttributeModificationType.Update: ConvertAttributeChangeUpdateFromUpdate(attributeChanges, objectModificationType, attribute, valueChanges, existingChange); break; case AttributeModificationType.Unconfigured: default: throw new UnknownOrUnsupportedModificationTypeException(existingChange.ModificationType); } } else { CreateAttributeChangeUpdate(attributeChanges, objectModificationType, attribute, valueChanges); } RemoveAttributeChangeIfEmpty(attributeChanges, attribute.Name); }
public MergeResult Merge(IEnumerable<SubscriptionItem> previousItems, IEnumerable<FeedItem> currentItems) { var result = new MergeResult(); var previousAuxList = new KeyedCollection<string, SubscriptionItem>(x => x.Id, previousItems); var currentAuxList = new KeyedCollection<string, FeedItem>(x => x.Id, currentItems); var previousIds = previousAuxList.Select(x => x.Id).ToArray(); foreach (var id in previousIds) { if (!currentAuxList.Contains(id)) ChooseRemovedItem(id, previousAuxList, result); else ChooseMergeItem(id, previousAuxList, currentAuxList, result); } var newIds = currentAuxList.Select(x => x.Id).ToArray(); foreach (var id in newIds) ChooseNewItem(id, currentAuxList, result); return result; }
/// <summary> /// Creates Animations from a xnaMugen.IO.TextFile. /// </summary> /// <param name="textfile">A textfile whose xnaMugen.IO.TextSection can be used to create Animations.</param> /// <returns>A collection of Animations created from the supplied textfile.</returns> public KeyedCollection<Int32, Animation> LoadAnimations(TextFile textfile) { if (textfile == null) throw new ArgumentNullException("textfile"); KeyedCollection<Int32, Animation> animations = new KeyedCollection<Int32, Animation>(x => x.Number); foreach (TextSection section in textfile) { Animation animation = CreateAnimation(section); if (animation != null) { if (animations.Contains(animation.Number) == false) { animations.Add(animation); } else { Log.Write(LogLevel.Warning, LogSystem.AnimationSystem, "Duplicate animation #{0}. Discarding duplicate.", animation.Number); } } } return animations; }
public void Update(FeedItem item) { LastUpdatedTime = item.LastUpdatedTime; Summary = item.Summary; Title = item.Title; Categories = item.Categories; var previousLinksAux = new KeyedCollection<Uri, SubscriptionItemLink>(x => x.Uri, Links); foreach (var currentLink in item.Links) { if (previousLinksAux.Contains(currentLink.Uri)) { var previousLink = previousLinksAux[currentLink.Uri]; if (previousLink.IsDownloaded && previousLink.Length != currentLink.Length) { previousLink.Length = currentLink.Length; previousLink.MarkAsNotDownloaded(); } previousLink.MediaType = currentLink.MediaType; previousLink.RelationshipType = currentLink.RelationshipType; previousLink.Title = currentLink.Title; previousLinksAux.Remove(currentLink.Uri); } else { var newLink = CreateLink(currentLink); Links.Add(newLink); } } foreach (var previousLink in previousLinksAux) previousLink.Deleted = true; }
static void AddStateToCollection(KeyedCollection<Int32, State> collection, State state) { if (collection == null) throw new ArgumentNullException("collection"); if (state == null) throw new ArgumentNullException("state"); if (collection.Contains(state.Number) == true) { Log.Write(LogLevel.Warning, LogSystem.StateSystem, "Duplicate state #{0}. Discarding duplicate", state.Number); } else { collection.Add(state); } }