private static IMessageHandler CreateMessageHandler(string assemblyName, string type) { #if SSHARP if (!assemblyName.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)) { assemblyName += ".dll"; } return((IMessageHandler)Activator.CreateInstance(Assembly.LoadFrom(assemblyName).GetType(type))); #else #if NETSTANDARD foreach ( var assembly in from assembly in TypeResolver.GetAssemblies() let name = assembly.GetName().Name where string.Compare(name, assemblyName, StringComparison.OrdinalIgnoreCase) == 0 select assembly) { return((IMessageHandler)Activator.CreateInstance(assembly.GetType(type))); } return((IMessageHandler)Activator.CreateInstance(TypeResolver.Load(assemblyName, type))); #else foreach (var assembly in from assembly in AppDomain.CurrentDomain.GetAssemblies() let name = assembly.GetName().Name where string.Compare(name, assemblyName, StringComparison.OrdinalIgnoreCase) == 0 select assembly) { return((IMessageHandler)Activator.CreateInstance(assembly.GetType(type))); } return((IMessageHandler)Activator.CreateInstance(AppDomain.CurrentDomain.Load(assemblyName).GetType(type))); #endif #endif }
public virtual T Deserialize <T> (IRestResponse response) { if (string.IsNullOrEmpty(response.Content)) { return(default(T)); } var doc = XDocument.Parse(response.Content); var root = doc.Root; if (RootElement.HasValue() && doc.Root != null) { root = doc.Root.DescendantsAndSelf(RootElement.AsNamespaced(Namespace)).SingleOrDefault(); } // autodetect xml namespace if (!Namespace.HasValue()) { RemoveNamespace(doc); } var x = (T)Activator.CreateInstance(typeof(T)); var objType = x.GetType(); if (objType.IsSubclassOfRawGeneric(typeof(List <>))) { x = (T)HandleListDerivative(root, objType.Name, objType); } else { x = (T)Map(x, root); } return(x); }
private object CreateAndMap(Type type, object element) { object instance = Activator.CreateInstance(type); Map(instance, (IDictionary <string, object>)element); return(instance); }
private object HandleListDerivative(XElement root, string propName, Type type) { var t = type.IsGenericType ? type.GetGenericArguments()[0] : type.BaseType.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(type); IList <XElement> elements = root.Descendants(t.Name.AsNamespaced(Namespace)) .ToList(); var name = t.Name; var attribute = t.GetAttribute <DeserializeAsAttribute> (); if (attribute != null) { name = attribute.Name; } if (!elements.Any()) { var lowerName = name.ToLower().AsNamespaced(Namespace); elements = root.Descendants(lowerName).ToList(); } if (!elements.Any()) { var camelName = name.ToCamelCase(Culture).AsNamespaced(Namespace); elements = root.Descendants(camelName).ToList(); } if (!elements.Any()) { elements = root.Descendants() .Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == name) .ToList(); } if (!elements.Any()) { var lowerName = name.ToLower().AsNamespaced(Namespace); elements = root.Descendants() .Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == lowerName) .ToList(); } PopulateListFromElements(t, elements, list); // get properties too, not just list items // only if this isn't a generic type if (!type.IsGenericType) { Map(list, root.Element(propName.AsNamespaced(Namespace)) ?? root); } return(list); }
private IList BuildList(Type type, object parent) { var list = (IList)Activator.CreateInstance(type); var listType = type .GetTypeInfo() .GetInterfaces() .First(x => x.GetTypeInfo().IsGenericType&& x.GetGenericTypeDefinition() == typeof(IList <>)); var itemType = listType.GetTypeInfo().GetGenericArguments()[0]; var list1 = parent as IList; if (list1 != null) { foreach (var element in list1) { if (itemType.GetTypeInfo().IsPrimitive) { object item = ConvertValue(itemType.GetTypeInfo(), element); list.Add(item); } else if (itemType == typeof(string)) { if (element == null) { list.Add(null); continue; } list.Add(element.ToString()); } else { if (element == null) { list.Add(null); continue; } var item = ConvertValue(itemType.GetTypeInfo(), element); list.Add(item); } } } else { list.Add(ConvertValue(itemType.GetTypeInfo(), parent)); } return(list); }
protected virtual object CreateAndMap(Type t, XElement element) { object item; if (t == typeof(string)) { item = element.Value; } else if (t.GetTypeInfo().IsPrimitive) { item = element.Value.ChangeType(t, Culture); } else { item = Activator.CreateInstance(t); Map(item, element); } return(item); }
private IDictionary BuildDictionary(Type type, object parent) { var dict = (IDictionary)Activator.CreateInstance(type); var keyType = type.GetTypeInfo().GetGenericArguments()[0]; var valueType = type.GetTypeInfo().GetGenericArguments()[1]; foreach (var child in (IDictionary <string, object>)parent) { var key = keyType != typeof(string) ? Convert.ChangeType(child.Key, keyType, CultureInfo.InvariantCulture) : child.Key; var item = valueType.GetTypeInfo().IsGenericType&& valueType.GetTypeInfo().GetGenericTypeDefinition() == typeof(List <>) ? BuildList(valueType, child.Value) : ConvertValue(valueType.GetTypeInfo(), child.Value); dict.Add(key, item); } return(dict); }
protected virtual object Map(object x, XElement root) { var objType = x.GetType(); var props = objType.GetCType().GetProperties(); var deserializeFromContentAttributeAlreadyUsed = false; foreach (var prop in props) { var type = prop.PropertyType.GetTypeInfo(); var typeIsPublic = type.IsPublic || type.IsNestedPublic; if (!typeIsPublic || !prop.CanWrite) { continue; } var deserializeFromContent = false; var isNameDefinedInAttribute = false; XName name = null; var attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); if (attributes.Any()) { var attribute = (DeserializeAsAttribute)attributes.First(); name = attribute.Name.AsNamespaced(Namespace); isNameDefinedInAttribute = !string.IsNullOrEmpty(name == null ? null : name.LocalName); deserializeFromContent = attribute.Content; if (deserializeFromContentAttributeAlreadyUsed && deserializeFromContent) { throw new ArgumentException("Class cannot have two properties marked with " + "SerializeAs(Content = true) attribute."); } deserializeFromContentAttributeAlreadyUsed |= deserializeFromContent; } if (name == null) { name = prop.Name.AsNamespaced(Namespace); } var value = GetValueFromXml(root, name, prop, isNameDefinedInAttribute); if (value == null) { // special case for text content node if (deserializeFromContent) { var textNode = root.Nodes().FirstOrDefault(n => n is XText); if (textNode != null) { value = ((XText)textNode).Value; prop.SetValue(x, value, null); } continue; } // special case for inline list items if (type.IsGenericType) { var genericType = type.GetGenericArguments()[0]; var first = GetElementByName(root, genericType.Name); var list = (IList)Activator.CreateInstance(type.AsType()); if (first != null && root != null) { var elements = root.Elements(first.Name); PopulateListFromElements(genericType, elements, list); } prop.SetValue(x, list, null); } continue; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { // if the value is empty, set the property to null... if (string.IsNullOrEmpty(value.ToString())) { prop.SetValue(x, null, null); continue; } type = type.GetGenericArguments()[0].GetTypeInfo(); } var asType = type.AsType(); if (asType == typeof(bool)) { var toConvert = value.ToString() .ToLower(); prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null); } else if (type.IsPrimitive) { prop.SetValue(x, value.ChangeType(asType, Culture), null); } else if (type.IsEnum) { var converted = ((Type)type.AsType()).FindEnumValue(value.ToString(), Culture); prop.SetValue(x, converted, null); } else if (asType == typeof(Uri)) { var uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (asType == typeof(string)) { prop.SetValue(x, value, null); } else if (asType == typeof(DateTime)) { value = DateFormat.HasValue() ? DateTime.ParseExact(value.ToString(), DateFormat, Culture) : DateTime.Parse(value.ToString(), Culture); prop.SetValue(x, value, null); } else if (asType == typeof(DateTimeOffset)) { var toConvert = value.ToString(); if (string.IsNullOrEmpty(toConvert)) { continue; } DateTimeOffset deserialisedValue; try { deserialisedValue = XmlConvert.ToDateTimeOffset(toConvert); prop.SetValue(x, deserialisedValue, null); } catch (Exception) { object result; if (TryGetFromString(toConvert, out result, asType)) { prop.SetValue(x, result, null); } else { //fallback to parse deserialisedValue = DateTimeOffset.Parse(toConvert); prop.SetValue(x, deserialisedValue, null); } } } else if (asType == typeof(decimal)) { value = decimal.Parse(value.ToString(), Culture); prop.SetValue(x, value, null); } else if (asType == typeof(Guid)) { var raw = value.ToString(); value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()); prop.SetValue(x, value, null); } else if (asType == typeof(TimeSpan)) { var timeSpan = XmlConvert.ToTimeSpan(value.ToString()); prop.SetValue(x, timeSpan, null); } else if (type.IsGenericType) { var list = (IList)Activator.CreateInstance(asType); var container = this.GetElementByName(root, name); if (container.HasElements) { var first = container.Elements().FirstOrDefault(); if (first != null) { var t = type.GetGenericArguments()[0]; var elements = container.Elements(first.Name); PopulateListFromElements(t, elements, list); } } prop.SetValue(x, list, null); } else if (((Type)asType).IsSubclassOfRawGeneric(typeof(List <>))) { // handles classes that derive from List<T> // e.g. a collection that also has attributes var list = HandleListDerivative(root, prop.Name, asType); prop.SetValue(x, list, null); } else { //fallback to type converters if possible object result; if (TryGetFromString(value.ToString(), out result, asType)) { prop.SetValue(x, result, null); } else { // nested property classes if (root == null) { continue; } var element = GetElementByName(root, name); if (element == null) { continue; } var item = CreateAndMap(asType, element); prop.SetValue(x, item, null); } } } return(x); }
/// <summary> /// Replace the default serializer with a custom one /// </summary> /// <typeparam name="T">The type that implements IRestSerializer</typeparam> /// <returns></returns> public IRestClient UseSerializer <T> () where T : IRestSerializer, new () { return(UseSerializer(() => Activator.CreateInstance <T> ())); }