public object Resolve(Type type, string name = null) { var mappingKey = new MappingKey(type, name); MappingValue mappingValue = null; if (!string.IsNullOrEmpty(name)) { var mapping = _mappings.FirstOrDefault(it => it.Key.InstanceName == mappingKey.InstanceName && it.Key.Type == mappingKey.Type).Value; mappingValue = mapping; } if (string.IsNullOrEmpty(name) && _mappings.Any(t => t.Key.Type == mappingKey.Type)) { mappingValue = _mappings.FirstOrDefault(t => t.Key.Type == mappingKey.Type).Value; } else if (mappingValue == null) { throw new NotFoundTypeFromResolveException($"Not contain definition registered for {type.Name} {name}"); } if (_mappingTypes.TryGetValue(mappingValue.TypeRegister, out Func <MappingValue, object> funcResult)) { return(funcResult.Invoke(mappingValue)); } return(null); }
public void ShouldFindKeyByValue() { var key = new MappingKey( "user_data_base64", new AttributePath("user_data_base64"), EventQueues.Ec2InstanceSchema.GetAttributeByPath("user_data_base64")); this.Q.Find(key).Should().NotBeNull(); }
public MethodInfo ResolveRedirect <TResolver>(TResolver resolver, out MappingKey genericMapping) where TResolver : struct, IGenericArgumentResolver { Debug.Assert(Mode == IntrinsicImplementationMode.Redirect); var result = ResolveTarget(resolver, out var args); genericMapping = new MappingKey(args); return(result); }
/// <summary> /// Find attribute mapping key by path. /// </summary> /// <param name="path">The path.</param> /// <returns>The event; else <c>null</c> if not found.</returns> public LinkedListNode <HclEvent> FindKeyByPath(string path) { var tempKey = new MappingKey( string.Empty, new AttributePath(path), ProviderResourceSchema.MissingFromSchemaValueSchema); return(this.Find(tempKey)); }
private void Register(RegisterType registerType, Type from, Type to, string instanceName = null, object obj = null) { var mappingKey = new MappingKey(from, instanceName); if (!_mappings.ContainsKey(mappingKey)) { var mappingValue = new MappingValue(registerType, to, from, instanceName, obj); _mappings.Add(mappingKey, mappingValue); } }
/// <summary> /// Emits a mapping key. /// </summary> /// <param name="event">A <see cref="MappingKey"/> event.</param> private void EmitMappingKey(HclEvent @event) { var key = GetTypedEvent <MappingKey>(@event); if (EmitLifecycle.ContainsKey(this.currentResourceType) && EmitLifecycle[this.currentResourceType].Contains(key.Path)) { this.lifecycleKeys.Add(key.Path); } // Don't push path for repeating block key if (!key.IsBlockKey) { if (!this.isJson) { this.currentPath = key.Path; } this.WriteIndent(); } else { // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault switch (key.InitialAnalysis) { case AttributeContent.BlockList: this.blockKeys.Push(key); this.currentBlockKey = key; this.PushState(this.state); this.state = EmitterState.BlockList; break; case AttributeContent.BlockObject: this.state = EmitterState.BlockObject; break; default: this.state = EmitterState.Mapping; break; } this.WriteBreak(); this.WriteIndent(); } this.EmitScalar(@event); if (this.state == EmitterState.Mapping) { this.WriteIndicator("=", true, false, false); } }
///<summary> /// This method creates (or retrieves from cache) a mapping between type and OID /// of all natively supported postgresql data types. /// This is needed as from one version to another, this mapping can be changed and /// so we avoid hardcoding them. /// </summary> /// <returns>NpgsqlTypeMapping containing all known data types. The mapping must be /// cloned before it is modified because it is cached; changes made by one connection may /// effect another connection. /// </returns> public static NpgsqlBackendTypeMapping CreateAndLoadInitialTypesMapping(NpgsqlConnector conn) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "LoadTypesMapping"); MappingKey key = new MappingKey(conn); // Check the cache for an initial types map. NpgsqlBackendTypeMapping oidToNameMapping = null; if (BackendTypeMappingCache.TryGetValue(key, out oidToNameMapping)) { return(oidToNameMapping); } // Not in cache, create a new one. oidToNameMapping = new NpgsqlBackendTypeMapping(); // Create a list of all natively supported postgresql data types. // Attempt to map each type info in the list to an OID on the backend and // add each mapped type to the new type mapping object. LoadTypesMappings(conn, oidToNameMapping, TypeInfoList(conn.UseExtendedTypes, conn.CompatVersion)); //We hold the lock for the least time possible on the least scope possible. //We must lock on BackendTypeMappingCache because it will be updated by this operation, //and we must not just add to it, but also check that another thread hasn't updated it //in the meantime. Strictly just doing : //return BackendTypeMappingCache[key] = oidToNameMapping; //as the only call within the locked section should be safe and correct, but we'll assume //there's some subtle problem with temporarily having two copies of the same mapping and //ensure only one is called. //It is of course wasteful that multiple threads could be creating mappings when only one //will be used, but we aim for better overall concurrency at the risk of causing some //threads the extra work. NpgsqlBackendTypeMapping mappingCheck = null; //First check without acquiring the lock; don't lock if we don't have to. if (BackendTypeMappingCache.TryGetValue(key, out mappingCheck))//Another thread built the mapping in the meantime. { return(mappingCheck); } lock (BackendTypeMappingCache) { //Final check. We have the lock now so if this fails it'll continue to fail. if (BackendTypeMappingCache.TryGetValue(key, out mappingCheck))//Another thread built the mapping in the meantime. { return(mappingCheck); } // Add this mapping to the per-server-version cache so we don't have to // do these expensive queries on every connection startup. BackendTypeMappingCache.Add(key, oidToNameMapping); } return(oidToNameMapping); }
private object ResolveInstanceFromSingleton(MappingValue mappingValue) { var mappingKey = new MappingKey(mappingValue.TypeBase, mappingValue.InstanceName); if (mappingValue.Instance == null) { var mappingVal = (MappingValue)mappingValue.Clone(); mappingVal.TypeRegister = Enum.RegisterType.Type; mappingValue.Instance = ResolveInstanceFromType(mappingVal); _mappings[mappingKey] = mappingValue; } return(mappingValue.Instance); }
async public Task <MappingKeyLookupResults> LookupMappingKeyValuesAsync(MappingKey key) { var keyDescription = GetValue(key); if (string.IsNullOrEmpty(keyDescription)) { throw new InvalidEnumArgumentException($"MappingKey must have a description"); } using (var message = await HttpClient.GetAsync(new Uri($"{this.KeyValuesUrl}{keyDescription}")).ConfigureAwait(false)) { message.EnsureSuccessStatusCode(); var json = await message.Content.ReadAsStringAsync().ConfigureAwait(false); var response = JsonConvert.DeserializeObject <MappingKeyLookupResults>(json, this.SerializerSettings); response.Key = key; return(response); } }
/// <summary> /// Analyzes an attribute's value to see whether it has a value, is null or is an empty collection. /// </summary> /// <param name="key">The attribute key.</param> /// <returns>Result of analysis.</returns> /// <exception cref="Firefly.PSCloudFormation.Terraform.HclSerializer.HclSerializerException">Expected MappingStart, SequenceStart or PolicyStart. Got {nextEvent.GetType().Name}</exception> private AttributeContent AnalyzeAttribute(MappingKey key) { var keyNode = this.queue.Find(key); if (keyNode == null) { return(AttributeContent.NotFound); } var nextEventNode = keyNode.Next; if (nextEventNode == null) { throw new InvalidOperationException($"Unexpected end of event queue after attribute {key.Path}"); } var nextEvent = nextEventNode.Value; var currentAnalysis = key.InitialAnalysis; switch (nextEvent) { case Scalar scalar: return(scalar.Analyze(key, this.traits)); case JsonStart _: return(AttributeContent.Value); } if (!(nextEvent is CollectionStart)) { throw new InvalidOperationException( $"Expected MappingStart, SequenceStart or JsonStart. Got {nextEvent.GetType().Name}"); } // Read ahead the entire collection var collection = this.queue.PeekUntil(nextEventNode, new CompoundAttributeGatherer().Done, true).ToList(); return(collection.Any(e => e is ScalarValue sv && !sv.IsEmpty) ? currentAnalysis : AttributeContent.EmptyCollection); }
/// <summary> /// Consume this key and its value (scalar or compound). /// </summary> /// <param name="key">The key to consume.</param> /// <returns><c>true</c> if the key was consumed; else <c>false</c> if it was not found.</returns> public bool ConsumeKey(MappingKey key) { var keyNode = this.queue.Find(key); if (keyNode == null) { // This key may already have been consumed because it was inside a schema already consumed earlier. return(false); } var valueNode = keyNode.Next; if (valueNode == null) { throw new InvalidOperationException($"End of queue when getting value for attribute \"{key.Path}\"."); } // Remove the key this.queue.Remove(keyNode); // Remove the value this.ConsumeUntil(valueNode, new CompoundAttributeGatherer().Done, true); return(true); }
/// <summary> /// Gets the mapping that matches this service type and attribute type /// </summary> /// <param name="ServiceType">Service type</param> /// <param name="AttributeType">Attribute type</param> /// <returns>The mapping associated with this service type and attribute type</returns> public IMapping GetMapping(Type ServiceType, Type AttributeType) { MappingKey Key = new MappingKey(ServiceType, AttributeType, ProviderManager, this); return(Mappings.FirstOrDefault(x => x.Equals(Key))); }
/// <summary> /// Gets the mapping that matches this service type /// </summary> /// <param name="ServiceType">Service type</param> /// <returns>The mapping associated with this service type</returns> public IMapping GetMapping(Type ServiceType) { MappingKey Key = new MappingKey(ServiceType, null, ProviderManager, this); return(Mappings.Find(x => x.Equals(Key))); }
public bool IsRegistered <T>(string name = null) { var mappingKey = new MappingKey(typeof(T), name); return(_mappings.ContainsKey(mappingKey)); }
/// <summary> /// Gets any attributes which conflict with the specified attribute. /// </summary> /// <param name="key">The attribute to test.</param> /// <returns>Enumerable of conflicts.</returns> public IEnumerable <MappingKey> GetConflictingAttributes(MappingKey key) { return(this.GetKeys().Where(k => key.Schema.ConflictsWith != null && key.Schema.ConflictsWith.Contains(k.Path))); }