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.IsEmpty())
                    {
                        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));
                }

                XObject element;
                if (tag is DFeAttributeAttribute)
                {
                    element = parentElement.Attributes(tag.Name).FirstOrDefault();
                }
                else
                {
                    element = parentElement.ElementsAnyNs(tag.Name).FirstOrDefault();
                }

                return(PrimitiveSerializer.Deserialize(tag, element, item, prop));
            }
            catch (Exception e)
            {
                var msg = $"Erro ao deserializar a propriedade:{Environment.NewLine}{prop.DeclaringType?.Name ?? prop.PropertyType.Name} - {prop.Name}";
                logger.Error(msg, e);
                throw new ACBrDFeException(msg, e);
            }
        }
        public static XElement Serialize(object value, Type tipo, string name, string nameSpace, SerializerOptions options)
        {
            try
            {
                XNamespace aw            = nameSpace ?? string.Empty;
                var        objectElement = name.IsEmpty() ? new XElement(name) : new XElement(aw + name);

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

                foreach (var prop in properties.AsParallel())
                {
                    if (prop.ShouldIgnoreProperty() || !prop.ShouldSerializeProperty(value))
                    {
                        continue;
                    }

                    var elements = Serialize(prop, value, options);
                    if (elements == null)
                    {
                        continue;
                    }

                    foreach (var element in elements)
                    {
                        if (element is XElement child)
                        {
                            objectElement.AddChild(child);
                        }
                        else
                        {
                            objectElement.AddAttribute((XAttribute)element);
                        }
                    }
                }

                return(objectElement);
            }
            catch (Exception e)
            {
                var msg = $"Erro ao serializar o objeto:{Environment.NewLine}{value}";
                logger.Error(msg, e);
                throw new ACBrDFeException(msg, e);
            }
        }
Exemple #3
0
        public static object Deserialize(PropertyInfo prop, XElement parentElement, object item, SerializerOptions options)
        {
            var tags = prop.GetAttributes <DFeItemAttribute>();

            foreach (var att in tags)
            {
                var node = parentElement.ElementsAnyNs(att.Name).FirstOrDefault();
                if (node == null)
                {
                    continue;
                }

                var objectType = ObjectType.From(att.Tipo);
                if (objectType.IsIn(ObjectType.ArrayType, ObjectType.EnumerableType))
                {
                    var listElement = parentElement.ElementsAnyNs(att.Name);
                    var list        = (ArrayList)CollectionSerializer.Deserialize(typeof(ArrayList), listElement, options);
                    var type        = CollectionSerializer.GetItemType(att.Tipo);
                    return(objectType == ObjectType.ArrayType ? list.ToArray(type) : list.Cast(type));
                }

                if (objectType == ObjectType.ListType)
                {
                    var listElement = parentElement.ElementsAnyNs(att.Name);
                    return(CollectionSerializer.Deserialize(att.Tipo, listElement, options));
                }

                return(ObjectSerializer.Deserialize(att.Tipo, node, options));
            }

            return(null);
        }
        public static IEnumerable <XObject> Serialize(PropertyInfo prop, object parentObject, SerializerOptions options)
        {
            try
            {
                var objectType = ObjectType.From(prop.PropertyType);

                if (objectType == ObjectType.DictionaryType)
                {
                    return(DictionarySerializer.Serialize(prop, parentObject, options));
                }

                if (objectType.IsIn(ObjectType.ListType, ObjectType.ArrayType, ObjectType.EnumerableType))
                {
                    return(CollectionSerializer.Serialize(prop, parentObject, options));
                }

                var value = prop.GetValue(parentObject, null);

                if (objectType.IsIn(ObjectType.InterfaceType, ObjectType.AbstractType))
                {
                    return(value == null ? null : InterfaceSerializer.Serialize(prop, parentObject, options));
                }

                if (objectType == ObjectType.ClassType)
                {
                    var attribute = prop.GetAttribute <DFeElementAttribute>();
                    if (attribute.Ocorrencia == Ocorrencia.NaoObrigatoria && value == null)
                    {
                        return(null);
                    }
                    if (attribute.IsValue)
                    {
                        prop.PropertyType.ValidateValueType();
                    }

                    return(new XObject[] { Serialize(value, prop.PropertyType, attribute.Name, attribute.Namespace, options) });
                }

                if (objectType == ObjectType.RootType)
                {
                    if (prop.HasAttribute <DFeElementAttribute>())
                    {
                        var attribute = prop.GetAttribute <DFeElementAttribute>();
                        if (attribute.Ocorrencia == Ocorrencia.NaoObrigatoria && value == null)
                        {
                            return(null);
                        }
                        return(new XObject[] { Serialize(value, prop.PropertyType, attribute.Name, attribute.Namespace, options) });
                    }

                    if (value == null)
                    {
                        return(null);
                    }
                    var rooTag   = prop.PropertyType.GetAttribute <DFeRootAttribute>();
                    var rootName = rooTag.Name;

                    if (rootName.IsEmpty())
                    {
                        var root = prop.PropertyType.GetRootName(value);
                        rootName = root.IsEmpty() ? prop.PropertyType.Name : root;
                    }

                    var rootElement = Serialize(value, prop.PropertyType, rootName, rooTag.Namespace, options);
                    return(new XObject[] { rootElement });
                }

                var tag = prop.GetTag();
                return(new[] { PrimitiveSerializer.Serialize(tag, parentObject, prop, options) });
            }
            catch (Exception e)
            {
                var msg = $"Erro ao serializar a propriedade:{Environment.NewLine}{prop.DeclaringType?.Name ?? prop.PropertyType.Name} - {prop.Name}";
                logger.Error(msg, e);
                throw new ACBrDFeException(msg, e);
            }
        }
Exemple #5
0
        private static XObject ProcessContent(DFeBaseAttribute tag, string conteudoProcessado, bool estaVazio, SerializerOptions options)
        {
            string alerta;

            if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio && tag.Min > 0)
            {
                alerta = DFeSerializer.ErrMsgVazio;
            }
            else
            {
                alerta = string.Empty;
            }

            if (conteudoProcessado.IsEmpty() && conteudoProcessado.Length < tag.Min && alerta.IsEmpty() && conteudoProcessado.Length > 1)
            {
                alerta = DFeSerializer.ErrMsgMenor;
            }

            if (!string.IsNullOrEmpty(conteudoProcessado.Trim()) && conteudoProcessado.Length > tag.Max)
            {
                alerta = DFeSerializer.ErrMsgMaior;
            }

            if (!string.IsNullOrEmpty(alerta.Trim()) && DFeSerializer.ErrMsgVazio.Equals(alerta) && !estaVazio)
            {
                alerta += $" [{tag.Name}]";
            }

            options.AddAlerta(tag.Id, tag.Name, tag.Descricao, alerta);

            if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio)
            {
                return(tag is DFeElementAttribute eAttribute ? (XObject) new XElement((XNamespace)eAttribute.Namespace + eAttribute.Name, "") : new XAttribute(tag.Name, ""));
            }

            if (estaVazio)
            {
                return(null);
            }

            var elementValue = options.RemoverAcentos ? conteudoProcessado.RemoveAccent() : conteudoProcessado;

            elementValue = options.RemoverEspacos ? elementValue.Trim() : elementValue;

            switch (tag)
            {
            case DFeAttributeAttribute _: return(new XAttribute(tag.Name, elementValue));

            case DFeDictionaryKeyAttribute keyAtt when keyAtt.AsAttribute: return(new XAttribute(keyAtt.Name, elementValue));

            case DFeElementAttribute eAttribute:
                XNamespace aw = eAttribute.Namespace ?? string.Empty;

                if (elementValue.IsCData())
                {
                    elementValue = elementValue.RemoveCData();
                    return(new XElement(aw + eAttribute.Name, new XCData(elementValue)));
                }
                else
                {
                    return(eAttribute.UseCData ? new XElement(aw + eAttribute.Name, new XCData(elementValue)) :
                           new XElement(aw + eAttribute.Name, elementValue));
                }

            default:
                return(new XElement(tag.Name, elementValue));
            }
        }
Exemple #6
0
        /// <summary>
        /// Serializes a fundamental primitive object (e.g. string, int etc.) into a XElement using options.
        /// </summary>
        /// <param name="tag">The name of the primitive to serialize.</param>
        /// <param name="item">The item.</param>
        /// <param name="prop">The property.</param>
        /// <param name="options">Indicates how the output is formatted or serialized.</param>
        /// <param name="idx"></param>
        /// <returns>The XElement representation of the primitive.</returns>
        public static XObject Serialize(DFeBaseAttribute tag, object item, PropertyInfo prop, SerializerOptions options, int idx = -1)
        {
            try
            {
                var value              = prop.GetValueOrIndex(item, idx);
                var estaVazio          = value == null || value.ToString().IsEmpty();
                var conteudoProcessado = ProcessValue(ref estaVazio, tag.Tipo, value, tag.Ocorrencia, tag.Min, prop, item);

                return(ProcessContent(tag, conteudoProcessado, estaVazio, options));
            }
            catch (Exception ex)
            {
                options.AddAlerta(tag.Id, tag.Name, tag.Descricao, ex.ToString());
                return(null);
            }
        }
Exemple #7
0
        public static XElement[] SerializeElementValue(ICollection values, DFeCollectionAttribute tag, DFeItemAttribute[] itemTags, SerializerOptions options)
        {
            var retElements = new List <XElement>();

            foreach (var value in values)
            {
                var itemTag = itemTags.SingleOrDefault(x => x.Tipo == value.GetType());
                Guard.Against <ACBrDFeException>(itemTag == null, $"Item {value.GetType().Name} não presente na lista de itens.");

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

                var valueProp = properties.Single(x => x.HasAttribute <DFeItemValueAttribute>());

                var valueType = ObjectType.From(valueProp.PropertyType);
                Guard.Against <ACBrDFeException>(valueType != ObjectType.PrimitiveType,
                                                 $"Item {value.GetType().Name} é do tipo [ItemValue] e o [DFeItemValueAttribute] não é do tipo primitivo");

                var attProps = properties.Where(x => x.HasAttribute <DFeAttributeAttribute>()).ToArray();

                var element = ValueElementSerializer.Serialize(itemTag.Name, itemTag.Namespace, value, options, valueProp, attProps);
                retElements.Add(element);
            }

            return(retElements.ToArray());
        }
Exemple #8
0
        /// <summary>
        /// Deserializes the XElement to the fundamental primitive (e.g. string, int etc.) of a specified type using options.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <param name="parentElement">The parent XElement used to deserialize the fundamental primitive.</param>
        /// <param name="item">The item.</param>
        /// <param name="prop">The property.</param>
        /// <param name="options">The options.</param>
        /// <returns>The deserialized fundamental primitive from the XElement.</returns>
        public static object Deserialize(IDFeElement tag, XObject parentElement, object item, PropertyInfo prop, SerializerOptions options, int idx = -1)
        {
            if (parentElement == null)
            {
                return(null);
            }

            var element = parentElement as XElement;
            var value   = element?.Value ?? ((XAttribute)parentElement).Value;

            return(GetValue(tag.Tipo, value, item, prop));
        }
Exemple #9
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>();

            IEnumerable <XElement> elements = parent;

            if (prop.HasAttribute <DFeItemAttribute>())
            {
                var itemTags = prop.GetAttributes <DFeItemAttribute>();
                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) ?? itemTags[0];
                    var obj     = ObjectSerializer.Deserialize(itemTag.Tipo, element, options);
                    list.Add(obj);
                }
            }
            else
            {
                if (objectType == ObjectType.PrimitiveType)
                {
                    foreach (var element in elements)
                    {
                        var obj = PrimitiveSerializer.Deserialize(elementAtt, element, parentItem, prop, options);
                        list.Add(obj);
                    }
                }
                else
                {
                    foreach (var element in elements)
                    {
                        var obj = ObjectSerializer.Deserialize(listItemType, element, options);
                        list.Add(obj);
                    }
                }
            }

            return(list);
        }
Exemple #10
0
        public static XElement[] SerializeChild(ICollection values, DFeCollectionAttribute tag, DFeItemAttribute[] itemTags, SerializerOptions options)
        {
            var childElements = new List <XElement>();

            foreach (var value in values)
            {
                var itemTag = itemTags.SingleOrDefault(x => x.Tipo == value.GetType());
                Guard.Against <ACBrDFeException>(itemTag == null, $"Item {value.GetType().Name} não presente na lista de itens.");

                var childElement = ObjectSerializer.Serialize(value, value.GetType(), itemTag.Name, itemTag.Namespace, options);
                childElements.Add(childElement);
            }

            return(childElements.ToArray());
        }
        public static XObject[] Serialize(PropertyInfo prop, object parentObject, SerializerOptions options)
        {
            Guard.Against <ACBrDFeException>(!prop.HasAttribute <DFeDictionaryAttribute>(), $"Atributo necessário não encontrado [{nameof(DFeDictionaryAttribute)}]");
            Guard.Against <ACBrDFeException>(!prop.HasAttribute <DFeDictionaryKeyAttribute>(), $"Atributo necessário não encontrado [{nameof(DFeDictionaryKeyAttribute)}]");
            Guard.Against <ACBrDFeException>(!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>();

            Guard.Against <ArgumentNullException>(!keyAtt.AsAttribute && tag.ItemName.IsEmpty(), "Se a Key não é um atributo é necessario informar o [ItemName]");

            var dictionary = (IDictionary)prop.GetValue(parentObject, null);

            if (dictionary.Count < tag.MinSize || dictionary.Count > tag.MaxSize && tag.MaxSize > 0)
            {
                var msg = dictionary.Count > tag.MaxSize ? DFeSerializer.ErrMsgMaiorMaximo : DFeSerializer.ErrMsgMenorMinimo;
                options.AddAlerta(tag.Id, tag.Name, tag.Descricao, msg);
            }

            if (dictionary.Count == 0 && tag.MinSize == 0 && tag.Ocorrencia == Ocorrencia.NaoObrigatoria)
            {
                return(null);
            }

            var args = dictionary.GetType().GetGenericArguments();

            Guard.Against <ArgumentException>(args.Length != 2);

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

            Guard.Against <ACBrDFeException>(keyType != ObjectType.PrimitiveType && keyAtt.AsAttribute);

            var list = new List <XElement>();

            var dicENumerator = dictionary.GetEnumerator();

            while (dicENumerator.MoveNext())
            {
                var key   = dicENumerator.Entry.Key;
                var value = dicENumerator.Entry.Value;

                var keyElement = keyType == ObjectType.PrimitiveType
                    ? PrimitiveSerializer.Serialize(keyAtt, key, options)
                    : ObjectSerializer.Serialize(key, key.GetType(), keyAtt.Name, keyAtt.Namespace, options);

                var valueElement = valueType == ObjectType.PrimitiveType
                    ? (XElement)PrimitiveSerializer.Serialize(valueAtt, value, options)
                    : ObjectSerializer.Serialize(value, value.GetType(), valueAtt.Name, valueAtt.Namespace, options);

                if (keyAtt.AsAttribute)
                {
                    valueElement.AddAttribute((XAttribute)keyElement);
                    list.Add(valueElement);
                }
                else
                {
                    var itemElement = new XElement(tag.ItemName);
                    itemElement.AddChild((XElement)keyElement);
                    itemElement.AddChild(valueElement);

                    list.Add(itemElement);
                }
            }

            var element = new XElement(tag.Name, tag.Namespace);

            element.AddChild(list.ToArray());

            return(new XObject[] { element });
        }
        public static object Deserialize(PropertyInfo prop, XElement parent, object parentItem, SerializerOptions options)
        {
            Guard.Against <ACBrDFeException>(!prop.HasAttribute <DFeDictionaryAttribute>(), $"Atributo necessário não encontrado [{nameof(DFeDictionaryAttribute)}]");
            Guard.Against <ACBrDFeException>(!prop.HasAttribute <DFeDictionaryKeyAttribute>(), $"Atributo necessário não encontrado [{nameof(DFeDictionaryKeyAttribute)}]");
            Guard.Against <ACBrDFeException>(!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);
                    value = valueType == ObjectType.PrimitiveType ?
                            PrimitiveSerializer.Deserialize(valueAtt, element, parentItem, prop) :
                            ObjectSerializer.Deserialize(args[1], element, options);
                }
                else
                {
                    key = keyType == ObjectType.PrimitiveType ?
                          PrimitiveSerializer.Deserialize(keyAtt, element.ElementAnyNs(keyAtt.Name), parentItem, prop) :
                          ObjectSerializer.Deserialize(args[0], element.ElementAnyNs(keyAtt.Name), options);

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

                dictionary.Add(key, value);
            }

            return(dictionary);
        }
Exemple #13
0
        /// <summary>
        /// Serializes a fundamental primitive object (e.g. string, int etc.) into a XElement using options.
        /// </summary>
        /// <param name="tag">The name of the primitive to serialize.</param>
        /// <param name="item">The item.</param>
        /// <param name="prop">The property.</param>
        /// <param name="options">Indicates how the output is formatted or serialized.</param>
        /// <returns>The XElement representation of the primitive.</returns>
        public static XObject Serialize(IDFeElement tag, object item, PropertyInfo prop, SerializerOptions options, int idx = -1)
        {
            try
            {
                var value              = prop.GetValueOrIndex(item, idx);
                var estaVazio          = value == null || value.ToString().IsEmpty();
                var conteudoProcessado = ProcessValue(ref estaVazio, tag.Tipo, value, tag.Ocorrencia, tag.Min, prop, item);

                string alerta;
                if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio && tag.Min > 0)
                {
                    alerta = DFeSerializer.ErrMsgVazio;
                }
                else
                {
                    alerta = string.Empty;
                }

                if (conteudoProcessado.IsEmpty() && conteudoProcessado.Length < tag.Min && alerta.IsEmpty() &&
                    conteudoProcessado.Length > 1)
                {
                    alerta = DFeSerializer.ErrMsgMenor;
                }

                if (!string.IsNullOrEmpty(conteudoProcessado.Trim()) && conteudoProcessado.Length > tag.Max)
                {
                    alerta = DFeSerializer.ErrMsgMaior;
                }

                if (!string.IsNullOrEmpty(alerta.Trim()) && DFeSerializer.ErrMsgVazio.Equals(alerta) && !estaVazio)
                {
                    alerta += $" [{value}]";
                }

                options.AddAlerta(tag.Id, tag.Name, tag.Descricao, alerta);

                XObject xmlTag = null;
                if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio)
                {
                    xmlTag = tag is DFeElementAttribute ? (XObject) new XElement(tag.Name) : new XAttribute(tag.Name, "");
                }

                if (estaVazio)
                {
                    return(xmlTag);
                }

                var elementValue = options.RemoverAcentos ? conteudoProcessado.RemoveAccent() : conteudoProcessado;

                if (tag is DFeAttributeAttribute)
                {
                    return(new XAttribute(tag.Name, elementValue));
                }

                var cData = ((DFeElementAttribute)tag).UseCData;
                if (!elementValue.IsCData())
                {
                    return(cData ? new XElement(tag.Name, new XCData(elementValue)) :
                           new XElement(tag.Name, elementValue));
                }

                elementValue = elementValue.RemoveCData();
                return(new XElement(tag.Name, new XCData(elementValue)));
            }
            catch (Exception ex)
            {
                options.AddAlerta(tag.Id, tag.Name, tag.Descricao, ex.ToString());
                return(null);
            }
        }
 public static XObject[] SerializeObjects(ICollection values, DFeItemAttribute tag, SerializerOptions options)
 {
     return((from object value in values select ObjectSerializer.Serialize(value, value.GetType(), tag.Name, tag.Namespace, options)).Cast <XObject>().ToArray());
 }
Exemple #15
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 <ACBrDFeException>(itemTag == null, $"Nenhum atributo [{nameof(DFeItemAttribute)}] encontrado " +
                                                     $"para o elemento: {element.Name.LocalName}");

                    object item;
                    if (objectType == ObjectType.ValueElementType)
                    {
                        item = ValueElementSerializer.Deserialize(itemTag.Tipo, element, options);
                    }
                    else if (objectType == ObjectType.PrimitiveType)
                    {
                        item = PrimitiveSerializer.Deserialize(elementAtt, element, parentItem, prop);
                    }
                    else
                    {
                        item = ObjectSerializer.Deserialize(itemTag.Tipo, element, options);
                    }

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

                    foreach (var element in parent)
                    {
                        var item = objectType == ObjectType.ValueElementType ? ValueElementSerializer.Deserialize(listItemType, element, options) :
                                   ObjectSerializer.Deserialize(listItemType, element, options);
                        list.Add(item);
                    }
                }
            }

            return(list);
        }
        public static XObject[] SerializePrimitive(PropertyInfo prop, object parentObject, ICollection values, DFeCollectionAttribute tag, SerializerOptions options)
        {
            var retElements = new List <XObject>();

            for (var i = 0; i < values.Count; i++)
            {
                var ret = PrimitiveSerializer.Serialize(tag, parentObject, prop, options, i);
                retElements.Add(ret);
            }

            return(retElements.ToArray());
        }
        public static XElement Serialize(string name, string nameSpace, object parentObject, SerializerOptions options, PropertyInfo valueProp, PropertyInfo[] attProps)
        {
            XNamespace aw      = nameSpace;
            var        element = nameSpace.IsEmpty() ? new XElement(name) : new XElement(aw + name);

            var valueAtt = valueProp.GetAttribute <DFeItemValueAttribute>();

            var childValue = valueProp.GetValueOrIndex(parentObject);
            var estaVazio  = childValue == null || childValue.ToString().IsEmpty();

            element.Value = PrimitiveSerializer.ProcessValue(ref estaVazio, valueAtt.Tipo, childValue,
                                                             valueAtt.Ocorrencia, valueAtt.Min, valueProp, parentObject);

            foreach (var property in attProps)
            {
                var attTag = property.GetAttribute <DFeAttributeAttribute>();
                var att    = (XAttribute)PrimitiveSerializer.Serialize(attTag, parentObject, property, options);
                element.AddAttribute(att);
            }

            return(element);
        }