Reflection functions now working on all loaded assemblies.
2 using System.Collections.Generic;
3 using System.ComponentModel;
7 using System.Threading.Tasks;
8 using System.Runtime.Serialization;
9 using System.Runtime.Serialization.Json;
10 using System.Globalization;
12 namespace SharpLib.Utils
15 /// Allow serialization into JSON.
16 /// Most useful to be able to save complex settings for instance.
19 /// [TypeConverter(typeof(TypeConverterJson<PersistantObject>))]
21 /// public class PersistantObject
24 /// <typeparam name="T"></typeparam>
25 public class TypeConverterJson<T> : TypeConverter where T : class
27 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
29 if (sourceType == typeof(string))
32 return base.CanConvertFrom(context, sourceType);
38 /// <param name="context"></param>
39 /// <param name="culture"></param>
40 /// <param name="value"></param>
41 /// <returns></returns>
42 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
44 string stringValue = value as string;
45 if (stringValue != null)
47 //Load object form JSON string
48 byte[] byteArray = Encoding.UTF8.GetBytes(stringValue);
49 MemoryStream stream = new MemoryStream(byteArray);
50 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings()
52 UseSimpleDictionaryFormat = true
54 T settings = (T)ser.ReadObject(stream);
58 return base.ConvertFrom(context, culture, value);
64 /// <param name="context"></param>
65 /// <param name="culture"></param>
66 /// <param name="value"></param>
67 /// <param name="destinationType"></param>
68 /// <returns></returns>
69 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
71 if (destinationType == typeof(string))
73 //Save settings into JSON string
74 MemoryStream stream = new MemoryStream();
75 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings()
77 UseSimpleDictionaryFormat = true
79 ser.WriteObject(stream, value);
80 // convert stream to string
82 StreamReader reader = new StreamReader(stream);
83 string text = reader.ReadToEnd();
88 return base.ConvertTo(context,culture,value,destinationType);