/// <summary> /// The serialization strategy tries to serialize the type with the first serializer and if /// it fails it uses the next one. /// </summary> /// <param name="option"></param> /// <returns></returns> private static IServiceSerializer CreateSerializationStrategy(SerializationOption option) { IServiceSerializer serviceSerializer = null; switch (option) { case SerializationOption.JsonSerializer: serviceSerializer = new JsonSerializer() { Next = new BinarySerializer() }; break; case SerializationOption.BinarySerializer: serviceSerializer = new BinarySerializer() { Next = new JsonSerializer() }; break; case SerializationOption.XmlSerializer: serviceSerializer = new XmlSerializer() { Next = new JsonSerializer() }; break; } Log.Write("CreateSerializationStrategy - SerializationOption is valid : {0}", option); return(serviceSerializer); }
public RockOptions(OptimizationSetting level = OptimizationSetting.Release, CodeFileOption codeFile = CodeFileOption.None, SerializationOption serialization = SerializationOption.NotSupported, CachingOption caching = CachingOption.UseCache, AllowWarning allowWarning = AllowWarning.No, string?codeFileDirectory = null) => (this.Optimization, this.CodeFile, this.Serialization, this.Caching, this.AllowWarning, this.CodeFileDirectory) =
/// <summary> /// Deserializes data with specified option. /// Use <see cref="SerializationOption.Internal"/> to deserialize internal data. /// Use <see cref="SerializationOption.TypedInternal"/> if deserializable internal data has type names information. /// Use <see cref="SerializationOption.User"/> to deserialize user data like arguments and parameters, /// configurable via <see cref="SetUserSerializerSettings"/>. /// </summary> public static T Deserialize <T>([CanBeNull] string value, SerializationOption option) { if (value == null) { return(default(T)); } return((T)Deserialize(value, typeof(T), option)); }
public Inspection(List <string> assemblies, string typeToRetrieveFullName, string typeNamespace, string typeName, SerializationOption serializationOption) { _serializationOption = serializationOption; _typeNamespace = typeNamespace; _typeName = typeName; _assemblies = assemblies; _typeToRetrieveFullName = TypeNameHelper.RemoveSystemNamespaces(typeToRetrieveFullName); }
public void BroadCastData(object target, Stream outgoingData) { //configure once the vs version string vsVersion = VisualStudioVersionHelper.FindCurrentVisualStudioVersion(); RavenWrapper.VisualStudioVersion = vsVersion; Log.VisualStudioVersion = vsVersion; try { Type targetType = GetInterfaceTypeIfIsIterator(target); string targetTypeFullName = TypeNameHelper.GetDisplayName(targetType, fullName: true); string targetTypeName = TypeNameHelper.GetDisplayName(targetType, fullName: false); //I'm lazy I know... Regex pattern1 = new Regex("[<]"); Regex pattern2 = new Regex("[>]"); Regex pattern3 = new Regex("[,]"); Regex pattern4 = new Regex("[`]"); Regex pattern5 = new Regex("[ ]"); string fileName = pattern1.Replace(targetTypeFullName, "("); fileName = pattern2.Replace(fileName, ")"); string typeName = pattern1.Replace(targetTypeName, string.Empty); typeName = pattern2.Replace(typeName, string.Empty); typeName = pattern3.Replace(typeName, string.Empty); typeName = pattern4.Replace(typeName, string.Empty); typeName = pattern5.Replace(typeName, string.Empty); fileName = TypeNameHelper.RemoveSystemNamespaces(fileName); Message message = new Message { FileName = string.Format(FileNameFormat, fileName), TypeName = typeName.Trim(), TypeFullName = targetTypeFullName, TypeNamespace = targetType.Namespace, AssemblyQualifiedName = targetType.AssemblyQualifiedName, AssemblyName = targetType.Assembly.GetName().Name }; BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(outgoingData, message); Log.Write("BroadCastData to LINQBridgeVsTruck"); SerializationOption serializationOption = CommonRegistryConfigurations.GetSerializationOption(vsVersion); Truck truck = new Truck("LINQBridgeVsTruck", serializationOption); truck.LoadCargo(target); bool res = truck.DeliverTo(typeName); Log.Write("Data Succesfully Shipped to Grapple"); } catch (Exception exception) { Log.Write(exception, "Error in BroadCastData"); RavenWrapper.Instance.Capture(exception, message: "Error broadcasting the data to linqpad"); throw; } }
public JsonWriter(JsonProperties jsonProperties, SerializationOption option) { _stringBuilder = new StringBuilder(); _jsonProperties = jsonProperties; isDefault = SerializationOption.Default == (option & SerializationOption.Default); isLeaveNull = SerializationOption.LeaveNull == (option & SerializationOption.LeaveNull); isToLowerCamelCase = SerializationOption.ToLowerCamelCase == (option & SerializationOption.ToLowerCamelCase); }
internal Inspection(Message message) { _truckId = message.TruckId; _typeNamespace = message.TypeNamespace; _typeName = message.TypeName; _assemblies = message.ReferencedAssemblies; _typeToRetrieveFullName = TypeNameHelper.RemoveSystemNamespaces(message.TypeFullName); //if the type is anonymous or it's a nested class then use the generic object _typeName = _typeToRetrieveFullName.Contains("AnonymousType") || _typeToRetrieveFullName.Contains("+") ? "object" : _typeToRetrieveFullName; _serializationType = message.SerializationOption; }
private static JsonSerializerSettings GetSerializerSettings(SerializationOption serializationOption) { switch (serializationOption) { case SerializationOption.Internal: case SerializationOption.TypedInternal: return(InternalSerializerSettings.Value); case SerializationOption.User: return(GetUserSerializerSettings()); default: throw new ArgumentOutOfRangeException(nameof(serializationOption), serializationOption, null); } }
public Message(string truckId, SerializationOption serializationOption, Type type) { Type targetType = GetInterfaceTypeIfIsIterator(type); SerializationOption = serializationOption; FileName = CalculateFileNameFromType(targetType); TypeName = CalculateTypeNameFromType(targetType).Trim(); TypeFullName = targetType.GetDisplayName(fullName: true); TypeNamespace = targetType.Namespace; AssemblyQualifiedName = targetType.AssemblyQualifiedName; AssemblyName = targetType.Assembly.GetName().Name; TruckId = truckId; }
/// <summary> /// /// </summary> /// <param name="truckName"></param> public Truck(string truckName, SerializationOption serializationOption = SerializationOption.Binary) { _truckName = truckName; if (serializationOption == SerializationOption.Binary) { _grapple = new BinaryGrapple(new DefaultSerializer()); } else { _grapple = new BinaryGrapple(new JsonSerializer()); } Init(); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="item">The object to serialize</param> /// <param name="truckId">the unique id used to save the serialize item to disk</param> /// <param name="serializationOption"> the proposed serialization strategy</param> /// <returns>Returns the actual serialization strategy used to serialize the <paramref name="item"/> </returns> public static SerializationOption?SendCargo <T>(T item, string truckId, SerializationOption serializationOption) { byte[] byteStream = null; Try: IServiceSerializer serializer = CreateSerializationStrategy(serializationOption); Log.Write($"SendCargo - Type {typeof(T).FullName} - Serialization strategy: {serializer}"); do { try { byteStream = serializer.Serialize(item); } catch (ThreadAbortException tae) { Thread.ResetAbort(); Log.Write(tae, "SendCargo - Thread Exception."); goto Try; } catch (Exception e) { Log.Write(e, "SendCargo - Error During serializing cargo"); serializer = serializer.Next; } }while (byteStream == null || byteStream.Length == 0 && serializer != null); if (byteStream.Length > 0) { string filePath = Path.Combine(Path.GetTempPath(), truckId); File.WriteAllBytes(filePath, byteStream); if (serializer == null) { return(null); } SerializationOption successfulSerialization = (SerializationOption)Enum.Parse(typeof(SerializationOption), serializer.ToString()); Log.Write($"SendCargo - Cargo Sent - Byte sent: {byteStream.Length} - File Created: {filePath} - Serialization Used: {successfulSerialization}"); return(successfulSerialization); } Log.Write($"SendCargo - It was not possible to serialize at all the type {typeof(T).FullName}"); return(null); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T ReceiveCargo <T>(string truckId, SerializationOption serializationOption) { Log.Write("ReceiveCargo - Receiving Cargo of Type {0}", typeof(T).FullName); try { byte[] byteStream = File.ReadAllBytes(Path.Combine(FileSystemFactory.FileSystem.Path.GetTempPath(), truckId)); IServiceSerializer serviceSerializer = CreateDeserializationStrategy(serializationOption); return(serviceSerializer != null?serviceSerializer.Deserialize <T>(byteStream) : default(T)); } catch (Exception e) { Log.Write(e, $"ReceiveCargo - Error while deserializing type {typeof(T).FullName}"); throw; } }
public static object ReceiveCargo(string truckId, SerializationOption serializationOption, Type type) { Log.Write("ReceiveCargo - UnLoading Cargo for Typeless object"); try { byte[] byteStream = File.ReadAllBytes(Path.Combine(FileSystemFactory.FileSystem.Path.GetTempPath(), truckId)); IServiceSerializer serviceSerializer = CreateDeserializationStrategy(serializationOption); return(serviceSerializer?.Deserialize(byteStream, type)); } catch (Exception e) { Log.Write(e, "ReceiveCargo - Error while deserializing"); throw; } }
/// <summary> /// The deserialization strategy strictly uses the strategy chosen and doesn't try to deserialize /// with a different <seealso cref="IServiceSerializer"/> /// </summary> /// <param name="option"></param> /// <returns></returns> private static IServiceSerializer CreateDeserializationStrategy(SerializationOption option) { switch (option) { case SerializationOption.JsonSerializer: return(new JsonSerializer()); case SerializationOption.BinarySerializer: return(new BinarySerializer()); case SerializationOption.XmlSerializer: return(new XmlSerializer()); } Log.Write("CreateDeserializationStrategy - SerializationOption is not valid Value: {0}", option); return(null); }
public static IApplicationBuilder UseSerialization(this IApplicationBuilder builder, SerializationOption option) { return(builder.UseMiddleware <SerializationMiddleware>(option)); }
/// <summary> /// Serializes data with specified option. /// Use <see cref="SerializationOption.Internal"/> option to serialize internal data. /// Use <see cref="SerializationOption.TypedInternal"/> option if you need to store type information. /// Use <see cref="SerializationOption.User"/> option to serialize user data like arguments and parameters, /// configurable via <see cref="SetUserSerializerSettings"/>. /// </summary> public static string Serialize([CanBeNull] object value, [CanBeNull] Type type, SerializationOption option) { if (value == null) { return(null); } if (GlobalConfiguration.HasCompatibilityLevel(CompatibilityLevel.Version_170)) { var serializerSettings = GetSerializerSettings(option); if (option == SerializationOption.User) { var formatting = serializerSettings?.Formatting ?? Formatting.None; return(JsonConvert.SerializeObject(value, type, formatting, serializerSettings)); } // For internal purposes we should ensure that JsonConvert.DefaultSettings don't affect // the serialization process, and the only way is to create a custom serializer. using (var stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var serializer = JsonSerializer.Create(serializerSettings); serializer.Serialize(jsonWriter, value, type); return(stringWriter.ToString()); } } else { // Previously almost all the data was serialized with the user settings, except // when we explicitly needed to persist the type information. In the latter case // custom settings passed to serializer, identical to TypedInternal. var serializerSettings = option == SerializationOption.TypedInternal ? GetLegacyTypedSerializerSettings() : GetUserSerializerSettings(); // JsonConvert is used here, because previously global default settings affected // the serialization process. var formatting = serializerSettings?.Formatting ?? Formatting.None; return(JsonConvert.SerializeObject(value, type, formatting, serializerSettings)); } }
/// <summary> /// Deserializes data with specified option. /// Use <see cref="SerializationOption.Internal"/> to deserialize internal data. /// Use <see cref="SerializationOption.TypedInternal"/> if deserializable internal data has type names information. /// Use <see cref="SerializationOption.User"/> to deserialize user data like arguments and parameters, /// configurable via <see cref="SetUserSerializerSettings"/>. /// </summary> public static object Deserialize([CanBeNull] string value, [NotNull] Type type, SerializationOption option) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (value == null) { return(null); } Exception exception = null; if (option != SerializationOption.User) { var serializerSettings = GetSerializerSettings(option); try { // For internal purposes we should ensure that JsonConvert.DefaultSettings don't affect // the deserialization process, and the only way is to create a custom serializer. using (var stringReader = new StringReader(value)) using (var jsonReader = new JsonTextReader(stringReader)) { var serializer = JsonSerializer.Create(serializerSettings); return(serializer.Deserialize(jsonReader, type)); } } catch (Exception ex) { // If there was an exception, we should try to deserialize the value using user-based // settings, because prior to 1.7.0 they were used for almost everything. So we are saving // the exception to re-throw it if even serializer based on user settings couldn't handle // our value. In that case an original exception should be thrown as it is the reason. exception = ex; } } try { return(JsonConvert.DeserializeObject(value, type, GetSerializerSettings(SerializationOption.User))); } catch (Exception) when(exception != null) { ExceptionDispatchInfo.Capture(exception).Throw(); throw; } }
private static void AssertOptions(RockOptions options, OptimizationSetting level, CodeFileOption codeFile, SerializationOption serialization, CachingOption caching, AllowWarning allowWarnings, string codeFileDirectory) { Assert.That(options.Optimization, Is.EqualTo(level), nameof(options.Optimization)); Assert.That(options.CodeFile, Is.EqualTo(codeFile), nameof(options.CodeFile)); Assert.That(options.Serialization, Is.EqualTo(serialization), nameof(options.Serialization)); Assert.That(options.Caching, Is.EqualTo(caching), nameof(options.Caching)); Assert.That(options.AllowWarning, Is.EqualTo(allowWarnings), nameof(options.AllowWarning)); Assert.That(options.CodeFileDirectory, Is.EqualTo(codeFileDirectory), nameof(options.CodeFileDirectory)); }
public override string SerializeObject(object o, SerializationOption option) { throw new NotImplementedException(); }
public abstract string SerializeObject(object o, SerializationOption option);
/// <summary> /// Serializes data with specified option. /// Use <see cref="SerializationOption.Internal"/> option to serialize internal data. /// Use <see cref="SerializationOption.TypedInternal"/> option if you need to store type information. /// Use <see cref="SerializationOption.User"/> option to serialize user data like arguments and parameters, /// configurable via <see cref="SetUserSerializerSettings"/>. /// </summary> public static string Serialize <T>([CanBeNull] T value, SerializationOption option) { return(Serialize(value, typeof(T), option)); }
public SerializationMiddleware(RequestDelegate next, SerializationOption option) { _next = next; _option = option; }
public JSONSeriallzationBase() { _option = SerializationOption.Default; }