public static DescribedSerializationBase ToDescribedSerializationUsingSpecificFactory <T>( this T objectToPackageIntoDescribedSerializationBase, SerializerRepresentation serializerRepresentation, ISerializerFactory serializerFactory, SerializationFormat serializationFormat, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { if (serializerRepresentation == null) { throw new ArgumentNullException(nameof(serializerRepresentation)); } if (serializerFactory == null) { throw new ArgumentNullException(nameof(serializerFactory)); } if (serializationFormat == SerializationFormat.Invalid) { throw new ArgumentOutOfRangeException(Invariant($"'{nameof(serializationFormat)}' == '{SerializationFormat.Invalid}'"), (Exception)null); } var serializer = serializerFactory.BuildSerializer(serializerRepresentation, assemblyMatchStrategy); var ret = objectToPackageIntoDescribedSerializationBase.ToDescribedSerializationUsingSpecificSerializer(serializer, serializationFormat); return(ret); }
/// <inheritdoc /> public override ISerializer BuildSerializer( SerializerRepresentation serializerRepresentation, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { if (serializerRepresentation == null) { throw new ArgumentNullException(nameof(serializerRepresentation)); } // ReSharper disable once RedundantArgumentDefaultValue var configurationType = serializerRepresentation.SerializationConfigType?.ResolveFromLoadedTypes(assemblyMatchStrategy, throwIfCannotResolve: true); ISerializer serializer; switch (serializerRepresentation.SerializationKind) { case SerializationKind.PropertyBag: serializer = new ObcPropertyBagSerializer(configurationType?.ToPropertyBagSerializationConfigurationType()); break; default: throw new NotSupportedException(Invariant($"{nameof(serializerRepresentation)} from enumeration {nameof(SerializationKind)} of {serializerRepresentation.SerializationKind} is not supported.")); } var result = this.WrapInCompressingSerializerIfAppropriate(serializer, serializerRepresentation.CompressionKind); return(result); }
/// <summary> /// Resolve the assembly qualified name into a Type from the loaded Types. /// </summary> /// <param name="assemblyQualifiedName">The assembly qualified name.</param> /// <param name="assemblyMatchStrategy">Strategy to use for matching assemblies.</param> /// <param name="throwIfCannotResolve"> /// Optional value indicating whether to throw an exception if the required assembly(ies) or the type(s) cannot be found /// (generics, having generic type arguments, may cause the specified type representation to encapsulate multiple assemblies and/or multiple types). /// Default is true. /// </param> /// <returns> /// Resolved/matching Type. /// </returns> public static Type ResolveFromLoadedTypes( this string assemblyQualifiedName, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion, bool throwIfCannotResolve = true) { if (assemblyQualifiedName == null) { throw new ArgumentNullException(nameof(assemblyQualifiedName)); } if (string.IsNullOrWhiteSpace(assemblyQualifiedName)) { throw new ArgumentException(Invariant($"'{nameof(assemblyQualifiedName)}' is white space")); } var cacheKey = new ResolveFromLoadedTypesUsingAssemblyQualifiedNameCacheKey(assemblyQualifiedName, assemblyMatchStrategy, throwIfCannotResolve); if (CachedResolveFromLoadedTypesUsingAssemblyQualifiedNameCacheKeyToTypeMap.TryGetValue(cacheKey, out Type result)) { return(result); } result = assemblyQualifiedName.ToTypeRepresentationFromAssemblyQualifiedName().ResolveFromLoadedTypes(assemblyMatchStrategy, throwIfCannotResolve); CachedResolveFromLoadedTypesUsingAssemblyQualifiedNameCacheKeyToTypeMap.TryAdd(cacheKey, result); return(result); }
public static T DeserializePayloadUsingSpecificSerializer <T>( this DescribedSerializationBase describedSerializationBase, IDeserialize deserializer, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { var result = (T)DeserializePayloadUsingSpecificSerializer(describedSerializationBase, deserializer, assemblyMatchStrategy); return(result); }
public static T DeserializePayload <T>( this DescribedSerializationBase describedSerialization, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { var result = describedSerialization.DeserializePayloadUsingSpecificFactory <T>( SerializerFactory.Instance, assemblyMatchStrategy); return(result); }
/// <inheritdoc /> public ISerializer BuildSerializer( SerializerRepresentation serializerRepresentation, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { var fallbackSerializer = this.BackingSerializerFactory.BuildSerializer(serializerRepresentation, assemblyMatchStrategy); var result = new ObcSimplifyingSerializer(fallbackSerializer); return(result); }
/// <inheritdoc /> public override ISerializer BuildSerializer( SerializerRepresentation serializerRepresentation, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { if (serializerRepresentation == null) { throw new ArgumentNullException(nameof(serializerRepresentation)); } ISerializer result; if (CachedSerializerRepresentationToSerializerMap.TryGetValue(serializerRepresentation, out ConcurrentDictionary <AssemblyMatchStrategy, ISerializer> assemblyMatchStrategyToSerializerMap)) { if (assemblyMatchStrategyToSerializerMap.TryGetValue(assemblyMatchStrategy, out result)) { return(result); } } // ReSharper disable once RedundantArgumentDefaultValue var configurationType = serializerRepresentation.SerializationConfigType?.ResolveFromLoadedTypes(assemblyMatchStrategy, throwIfCannotResolve: true); ISerializer serializer; switch (serializerRepresentation.SerializationKind) { case SerializationKind.Bson: serializer = new ObcBsonSerializer(configurationType?.ToBsonSerializationConfigurationType()); break; case SerializationKind.Json: serializer = new ObcJsonSerializer(configurationType?.ToJsonSerializationConfigurationType()); break; case SerializationKind.PropertyBag: serializer = new ObcPropertyBagSerializer(configurationType?.ToPropertyBagSerializationConfigurationType()); break; default: throw new NotSupportedException(Invariant($"{nameof(serializerRepresentation)} from enumeration {nameof(SerializationKind)} of {serializerRepresentation.SerializationKind} is not supported.")); } result = this.WrapInCompressingSerializerIfAppropriate(serializer, serializerRepresentation.CompressionKind); CachedSerializerRepresentationToSerializerMap.TryAdd(serializerRepresentation, new ConcurrentDictionary <AssemblyMatchStrategy, ISerializer>()); CachedSerializerRepresentationToSerializerMap[serializerRepresentation].TryAdd(assemblyMatchStrategy, result); return(result); }
public static DescribedSerializationBase ToDescribedSerialization <T>( this T objectToPackageIntoDescribedSerialization, SerializerRepresentation serializerRepresentation, SerializationFormat serializationFormat, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { var result = objectToPackageIntoDescribedSerialization.ToDescribedSerializationUsingSpecificFactory( serializerRepresentation, SerializerFactory.Instance, serializationFormat, assemblyMatchStrategy); return(result); }
public static object DeserializePayloadUsingSpecificSerializer( this DescribedSerializationBase describedSerializationBase, IDeserialize deserializer, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { if (describedSerializationBase == null) { throw new ArgumentNullException(nameof(describedSerializationBase)); } if (deserializer == null) { throw new ArgumentNullException(nameof(deserializer)); } var targetType = describedSerializationBase.PayloadTypeRepresentation.ResolveFromLoadedTypes(assemblyMatchStrategy); object result; var serializationFormat = describedSerializationBase.GetSerializationFormat(); switch (serializationFormat) { case SerializationFormat.Binary: var describedSerializationBinary = (BinaryDescribedSerialization)describedSerializationBase; var serializedBytes = describedSerializationBinary.SerializedPayload; result = serializedBytes == null ? null : deserializer.Deserialize(serializedBytes, targetType); break; case SerializationFormat.String: var describedSerializationString = (StringDescribedSerialization)describedSerializationBase; var serializedString = describedSerializationString.SerializedPayload; result = serializedString == null ? null : deserializer.Deserialize(serializedString, targetType); break; default: throw new NotSupportedException(Invariant($"{nameof(SerializationFormat)} - {serializationFormat} is not supported.")); } return(result); }
/// <summary> /// Converts a self described serialization back into it's object. /// </summary> /// <param name="describedSerializationBase">Self described serialized object.</param> /// <param name="serializerFactory">Implementation of <see cref="ISerializerFactory" /> that can resolve the serializer.</param> /// <param name="assemblyMatchStrategy">Optional assembly match strategy for resolving the type of object as well as the configuration type if any; DEFAULT is <see cref="AssemblyMatchStrategy.AnySingleVersion" />.</param> /// <returns> /// Originally serialized object. /// </returns> public static object DeserializePayloadUsingSpecificFactory( this DescribedSerializationBase describedSerializationBase, ISerializerFactory serializerFactory, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion) { if (describedSerializationBase == null) { throw new ArgumentNullException(nameof(describedSerializationBase)); } if (serializerFactory == null) { throw new ArgumentNullException(nameof(serializerFactory)); } var serializer = serializerFactory.BuildSerializer(describedSerializationBase.SerializerRepresentation, assemblyMatchStrategy); var result = describedSerializationBase.DeserializePayloadUsingSpecificSerializer(serializer, assemblyMatchStrategy); return(result); }
/// <summary> /// Resolve the <see cref="TypeRepresentation" /> into a Type from the loaded Types. /// </summary> /// <param name="typeRepresentation">The representation of the type.</param> /// <param name="assemblyMatchStrategy">Strategy to use for matching assemblies.</param> /// <param name="throwIfCannotResolve"> /// Optional value indicating whether to throw an exception if the required assembly(ies) or the type(s) cannot be found /// (generics, having generic type arguments, may cause the specified type representation to encapsulate multiple assemblies and/or multiple types). /// Default is true. /// </param> /// <returns> /// Resolved/matching Type. /// </returns> public static Type ResolveFromLoadedTypes( this TypeRepresentation typeRepresentation, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion, bool throwIfCannotResolve = true) { if (typeRepresentation == null) { throw new ArgumentNullException(nameof(typeRepresentation)); } // If another version of the type is loaded after the type has been cached, then we potentially // may not be honoring the specified AssemblyMatchStrategy. While we could move the whole // chunk of cache code right before Type.GetType, which would save us the cost of that call, // we have found that the most expensive call in the below code is assigning matchingAssemblies // (in testing it was 2x more expensive). So another solution would be to cache the call to // AssemblyLoader.GetLoadedAssemblies() but then this would similarly not honor the specified // AssemblyMatchStrategy because the loaded assemblies would be cached upon the first call and // never refreshed. var cacheKey = new ResolveFromLoadedTypesUsingTypeRepresentationCacheKey(typeRepresentation, assemblyMatchStrategy, throwIfCannotResolve); if (CachedResolveFromLoadedTypesUsingTypeRepresentationCacheKeyToTypeMap.TryGetValue(cacheKey, out Type result)) { return(result); } var assemblyQualifiedName = typeRepresentation.BuildAssemblyQualifiedName(); var assemblyNamesInUse = typeRepresentation.GetAssemblyNamesInUse(); var matchingAssemblies = AssemblyLoader.GetLoadedAssemblies().Where(_ => assemblyNamesInUse.Contains(_.GetName().Name)).ToList(); var matchingAssembliesGroupedByName = matchingAssemblies.GroupBy(_ => _.GetName().Name).ToList(); var matchingAssemblyNames = new HashSet <string>(matchingAssembliesGroupedByName.Select(_ => _.Key)); var missingAssemblyNames = assemblyNamesInUse.Where(_ => !matchingAssemblyNames.Contains(_)).ToList(); var foundAssemblyNames = new List <string>(); foreach (var missingAssemblyName in missingAssemblyNames) { try { var loadedAssembly = Assembly.Load(missingAssemblyName); if (loadedAssembly != null) { foundAssemblyNames.Add(missingAssemblyName); } } catch (Exception) { } } missingAssemblyNames = missingAssemblyNames.Except(foundAssemblyNames).ToList(); if (missingAssemblyNames.Any()) { if (throwIfCannotResolve) { throw new InvalidOperationException(Invariant($"Unable to resolve the specified {nameof(TypeRepresentation)} ({assemblyQualifiedName}). These assemblies are not loaded: {missingAssemblyNames.ToDelimitedString(", ")}.")); } } else { switch (assemblyMatchStrategy) { case AssemblyMatchStrategy.AnySingleVersion: var assembliesWithMultipleVersions = matchingAssembliesGroupedByName.Where(_ => _.Count() > 1).SelectMany(_ => _).ToList(); if (assembliesWithMultipleVersions.Any()) { if (throwIfCannotResolve) { throw new InvalidOperationException(Invariant($"Unable to resolve the specified {nameof(TypeRepresentation)} ({assemblyQualifiedName}) with {nameof(AssemblyMatchStrategy)}.{nameof(AssemblyMatchStrategy.AnySingleVersion)}. There were multiple versions of the following assemblies loaded: {assembliesWithMultipleVersions.Select(_ => "[" + _.FullName + "]").ToDelimitedString(", ")}.")); } } else { result = Type.GetType(assemblyQualifiedName, throwIfCannotResolve, false); } break; default: throw new NotSupportedException(Invariant($"This {nameof(AssemblyMatchStrategy)} is not supported: {assemblyMatchStrategy}.")); } } if ((result == null) && throwIfCannotResolve) { throw new InvalidOperationException(Invariant($"Unable to resolve the specified {nameof(TypeRepresentation)} {assemblyQualifiedName} with {nameof(AssemblyMatchStrategy)}.{nameof(AssemblyMatchStrategy.AnySingleVersion)} for unknown reasons. We never expected to hit this line of code.")); } CachedResolveFromLoadedTypesUsingTypeRepresentationCacheKeyToTypeMap.TryAdd(cacheKey, result); return(result); }
/// <inheritdoc /> public abstract ISerializer BuildSerializer( SerializerRepresentation serializerRepresentation, AssemblyMatchStrategy assemblyMatchStrategy = AssemblyMatchStrategy.AnySingleVersion);