Ejemplo n.º 1
0
        public static object Deserialize(PropertyInfo prop, XElement parent, object parentItem, SerializerOptions options)
        {
            Guard.Against <VipException>(!prop.HasAttribute <DFeDictionaryAttribute>(),
                                         $"Atributo necessário não encontrado [{nameof(DFeDictionaryAttribute)}]");
            Guard.Against <VipException>(!prop.HasAttribute <DFeDictionaryKeyAttribute>(),
                                         $"Atributo necessário não encontrado [{nameof(DFeDictionaryKeyAttribute)}]");
            Guard.Against <VipException>(!prop.HasAttribute <DFeDictionaryValueAttribute>(),
                                         $"Atributo necessário não encontrado [{nameof(DFeDictionaryValueAttribute)}]");

            var tag      = prop.GetAttribute <DFeDictionaryAttribute>();
            var keyAtt   = prop.GetAttribute <DFeDictionaryKeyAttribute>();
            var valueAtt = prop.GetAttribute <DFeDictionaryValueAttribute>();

            var dictionary = (IDictionary)Activator.CreateInstance(prop.PropertyType);
            var args       = prop.PropertyType.GetGenericArguments();

            var keyType   = ObjectType.From(args[0]);
            var valueType = ObjectType.From(args[1]);

            var elements = parent.ElementsAnyNs(keyAtt.AsAttribute ? valueAtt.Name : tag.ItemName);

            foreach (var element in elements)
            {
                object key;
                object value;
                if (keyAtt.AsAttribute)
                {
                    var keyElement = (XObject)element.Attributes(keyAtt.Name).FirstOrDefault();
                    key   = PrimitiveSerializer.Deserialize(keyAtt, keyElement, null, prop, options);
                    value = valueType == ObjectType.PrimitiveType
                        ? PrimitiveSerializer.Deserialize(valueAtt, element, parentItem, prop, options)
                        : ObjectSerializer.Deserialize(args[1], element, options);
                }
                else
                {
                    key = keyType == ObjectType.PrimitiveType
                        ? PrimitiveSerializer.Deserialize(keyAtt, element.ElementAnyNs(keyAtt.Name), parentItem, prop, options)
                        : ObjectSerializer.Deserialize(args[0], element.ElementAnyNs(keyAtt.Name), options);

                    value = valueType == ObjectType.PrimitiveType
                        ? PrimitiveSerializer.Deserialize(valueAtt, element.ElementAnyNs(valueAtt.Name), parentItem, prop, options)
                        : ObjectSerializer.Deserialize(args[1], element.ElementAnyNs(valueAtt.Name), options);
                }

                dictionary.Add(key, value);
            }

            return(dictionary);
        }
Ejemplo n.º 2
0
        public static object Deserialize(PropertyInfo prop, XElement parentElement, object item, SerializerOptions options)
        {
            try
            {
                var tag = prop.HasAttribute <DFeElementAttribute>()
                    ? (DFeBaseAttribute)prop.GetAttribute <DFeElementAttribute>()
                    : prop.GetAttribute <DFeAttributeAttribute>();

                var objectType = ObjectType.From(prop.PropertyType);
                if (objectType == ObjectType.DictionaryType)
                {
                    var dicTag            = prop.GetAttribute <DFeDictionaryAttribute>();
                    var dictionaryElement = parentElement.ElementAnyNs(dicTag.Name);
                    return(DictionarySerializer.Deserialize(prop, dictionaryElement, item, options));
                }

                if (objectType.IsIn(ObjectType.ArrayType, ObjectType.EnumerableType))
                {
                    var listElement = parentElement.ElementsAnyNs(tag.Name);
                    var list        = (ArrayList)CollectionSerializer.Deserialize(typeof(ArrayList), listElement.ToArray(), prop, item, options);
                    var type        = prop.PropertyType.IsArray ? prop.PropertyType.GetElementType() : prop.PropertyType.GetGenericArguments()[0];
                    return(objectType == ObjectType.ArrayType ? list.ToArray(type) : list.Cast(type));
                }

                if (objectType == ObjectType.ListType)
                {
                    var listElement = parentElement.ElementsAnyNs(tag.Name);
                    return(CollectionSerializer.Deserialize(prop.PropertyType, listElement.ToArray(), prop, item, options));
                }

                if (objectType.IsIn(ObjectType.InterfaceType, ObjectType.AbstractType))
                {
                    return(InterfaceSerializer.Deserialize(prop, parentElement, item, options));
                }

                if (objectType == ObjectType.RootType)
                {
                    if (tag != null)
                    {
                        var xElement = parentElement.ElementsAnyNs(tag.Name).FirstOrDefault();
                        return(Deserialize(prop.PropertyType, xElement, options));
                    }

                    var rootTag   = prop.PropertyType.GetAttribute <DFeRootAttribute>();
                    var rootNames = new List <string>();
                    if (!rootTag.Name.IsNullOrEmpty())
                    {
                        rootNames.Add(rootTag.Name);
                        rootNames.Add(prop.PropertyType.Name);
                    }
                    else
                    {
                        rootNames.AddRange(prop.PropertyType.GetRootNames());
                        rootNames.Add(prop.PropertyType.Name);
                    }

                    var xmlNode = (from node in parentElement.Elements()
                                   where node.Name.LocalName.IsIn(rootNames)
                                   select node).FirstOrDefault();

                    return(Deserialize(prop.PropertyType, xmlNode, options));
                }

                if (objectType == ObjectType.ClassType)
                {
                    var xElement = parentElement.ElementsAnyNs(tag.Name).FirstOrDefault();
                    return(Deserialize(prop.PropertyType, xElement, options));
                }

                var element = parentElement.ElementsAnyNs(tag.Name).FirstOrDefault() ??
                              (XObject)parentElement.Attributes(tag.Name).FirstOrDefault();

                return(PrimitiveSerializer.Deserialize(tag, element, item, prop, options));
            }
            catch (System.Exception e)
            {
                var msg = $"Erro ao deserializar a propriedade:{Environment.NewLine}{prop.DeclaringType?.Name ?? prop.PropertyType.Name} - {prop.Name}";
                throw new VipException(msg, e);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Deserializes the specified type.
        /// </summary>
        /// <param name="type">The type of the list to deserialize.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="prop">The property.</param>
        /// <param name="parentItem"></param>
        /// <param name="options">Indicates how the output is deserialized.</param>
        /// <returns>The deserialized list from the XElement.</returns>
        /// <exception cref="System.InvalidOperationException">
        ///     Could not deserialize this non generic dictionary without more type
        ///     information.
        /// </exception>
        /// Deserializes the XElement to the list (e.g. List
        /// <T />
        /// , Array of a specified type using options.
        public static object Deserialize(Type type, XElement[] parent, PropertyInfo prop, object parentItem, SerializerOptions options)
        {
            var listItemType = GetListType(type);
            var objectType   = ObjectType.From(GetItemType(prop.PropertyType));

            var list       = (IList)Activator.CreateInstance(type);
            var elementAtt = prop.GetAttribute <DFeCollectionAttribute>();

            if (prop.HasAttribute <DFeItemAttribute>())
            {
                var itemTags = prop.GetAttributes <DFeItemAttribute>();
                var elements = parent.All(x => x.Name.LocalName == elementAtt.Name) && parent.Length > 1 ? parent : parent.Elements();

                foreach (var element in elements)
                {
                    var itemTag = itemTags.SingleOrDefault(x => x.Name == element.Name.LocalName);
                    Guard.Against <VipException>(itemTag == null, $"Nenhum atributo [{nameof(DFeItemAttribute)}] encontrado " +
                                                 $"para o elemento: {element.Name.LocalName}");

                    object obj;
                    if (itemTag != null && itemTag.IsValue)
                    {
                        obj = itemTag.Tipo.HasCreate() ? itemTag.Tipo.GetCreate().Invoke() : Activator.CreateInstance(itemTag.Tipo);

                        var properties = itemTag.Tipo.GetProperties()
                                         .Where(x => !x.ShouldIgnoreProperty() && x.ShouldSerializeProperty(obj))
                                         .OrderBy(x => x.GetAttribute <DFeBaseAttribute>()?.Ordem ?? 0).ToArray();

                        Guard.Against <VipException>(!properties.All(x => x.HasAttribute <DFeItemValueAttribute>() || x.HasAttribute <DFeAttributeAttribute>()),
                                                     $"Item {itemTag.Tipo.Name} é do tipo [ItemValue] e so pode ter atributo do tipo [DFeAttributeAttribute] ou [DFeItemValueAttribute].");

                        Guard.Against <VipException>(properties.Count(x => x.HasAttribute <DFeItemValueAttribute>()) != 1,
                                                     $"Item {itemTag.Tipo.Name} é do tipo [ItemValue] e não tem presente o atributo [DFeItemValueAttribute] ou possui mais de um atributo.");

                        var valueProp = properties.SingleOrDefault(x => x.HasAttribute <DFeItemValueAttribute>());
                        var valueAtt  = valueProp.GetAttribute <DFeItemValueAttribute>();

                        var value = PrimitiveSerializer.GetValue(valueAtt.Tipo, element.Value, obj, prop);
                        valueProp?.SetValue(obj, value);

                        foreach (var property in properties.Where(x => x.HasAttribute <DFeAttributeAttribute>()))
                        {
                            var attTag = property.GetAttribute <DFeAttributeAttribute>();
                            value = PrimitiveSerializer.Deserialize(attTag, element, obj, property, options);
                            property.SetValue(obj, value);
                        }
                    }
                    else
                    {
                        obj = ObjectSerializer.Deserialize(itemTag?.Tipo, element, options);
                    }

                    list.Add(obj);
                }
            }
            else
            {
                if (objectType == ObjectType.PrimitiveType)
                {
                    foreach (var element in parent)
                    {
                        var obj = PrimitiveSerializer.Deserialize(elementAtt, element, parentItem, prop, options);
                        list.Add(obj);
                    }
                }
                else
                {
                    if (ObjectType.From(prop.PropertyType).IsIn(ObjectType.ArrayType, ObjectType.EnumerableType))
                    {
                        listItemType = GetItemType(prop.PropertyType);
                    }

                    foreach (var element in parent)
                    {
                        var obj = ObjectSerializer.Deserialize(listItemType, element, options);
                        list.Add(obj);
                    }
                }
            }

            return(list);
        }