Exemplo n.º 1
0
        internal static string GetXmlName(MemberInfo mi)
        {
            object[] vAttribs   = mi.GetCustomAttributes(true);
            string   strXmlName = mi.Name;

            XmlTypeAttribute xmlType = GetAttribute <XmlTypeAttribute>(vAttribs);

            if (xmlType != null)
            {
                strXmlName = xmlType.TypeName;
            }
            XmlRootAttribute xmlRoot = GetAttribute <XmlRootAttribute>(vAttribs);

            if (xmlRoot != null)
            {
                strXmlName = xmlRoot.ElementName;
            }
            XmlArrayAttribute xmlArray = GetAttribute <XmlArrayAttribute>(vAttribs);

            if (xmlArray != null)
            {
                strXmlName = xmlArray.ElementName;
            }
            XmlElementAttribute xmlElement = GetAttribute <XmlElementAttribute>(vAttribs);

            if (xmlElement != null)
            {
                strXmlName = xmlElement.ElementName;
            }

            return(strXmlName);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 判断成员信息pInfo是否被标记为XML相关属性
        /// </summary>
        /// <param name="pInfo">成员信息</param>
        /// <param name="attr">返回XML相关属性</param>
        /// <returns></returns>
        bool IsXmlAttribute(MemberInfo pInfo, out Attribute attr)
        {
            bool found = false;

            attr = null;

            var caList = pInfo.GetCustomAttributes(true);

            foreach (var ca in caList)
            {
                if (ca is XmlElementAttribute)
                {
                    attr  = new XmlElementAttribute((ca as XmlElementAttribute).ElementName);
                    found = true;
                    break;
                }
                else if (ca is XmlArrayAttribute)
                {
                    attr  = new XmlArrayAttribute((ca as XmlArrayAttribute).ElementName);
                    found = true;
                    break;
                }
                else
                {
                    // TODO: other type
                }
            }
            return(found);
        }
Exemplo n.º 3
0
 private static void WritePropToFile(string format, PropertyInfo prop, XmlArrayAttribute attribute, StreamWriter file)
 {
     file.WriteLine(format, prop.Name, attribute.ElementName.Replace("[]", ""), prop.PropertyType.Name());
     if (prop.Name.EndsWith("DateAsString"))
     {
         file.WriteLine(format, prop.Name.Replace("DateAsString", ""), attribute.ElementName, typeof(DateTime).Name());
     }
 }
        public void ElementNameDefault()
        {
            XmlArrayAttribute attr = new XmlArrayAttribute();

            Assert.AreEqual(string.Empty, attr.ElementName, "#1");

            attr.ElementName = null;
            Assert.AreEqual(string.Empty, attr.ElementName, "#2");
        }
Exemplo n.º 5
0
        private XName GetCollectionName(PropertyInfo propertyInfo)
        {
            XmlArrayAttribute attribute = propertyInfo.GetCustomAttribute <XmlArrayAttribute>();

            if (attribute == null)
            {
                return(_ns + propertyInfo.Name);
            }
            return(_ns + attribute.ElementName);
        }
Exemplo n.º 6
0
        public LiteralAttributes(MemberInfo memberInfo, XmlAttributes xmlAtts) :
            this(memberInfo)
        {
            if (xmlAtts == null)
            {
                return;
            }

            Ignore = xmlAtts.XmlIgnore;
            if (!Ignore)
            {
                XmlChoiceIdentifier = xmlAtts.XmlChoiceIdentifier;
                XmlAttribute        = xmlAtts.XmlAttribute;
                XmlArray            = xmlAtts.XmlArray;
                XmlText             = xmlAtts.XmlText;
                XmlEnum             = xmlAtts.XmlEnum;
                DefaultValue        = (xmlAtts.XmlDefaultValue == null) ?
                                      null :
                                      new DefaultValueAttribute(xmlAtts.XmlDefaultValue);

                Xmlns = xmlAtts.Xmlns;
                if (Xmlns)
                {
                    object[] attrs = memberInfo.GetCustomAttributes(s_nsDeclType, false).ToArray();
                    XmlNamespaceDeclaration = (XmlNamespaceDeclarationsAttribute)(attrs.Length > 0 ? attrs[0] : null);
                }
                else
                {
                    XmlNamespaceDeclaration = null;
                }

                // Use if statements here so that the XmlElements collection populated by reflection
                // is eliminated only if the app developer has provided substitute XmlElementAttribute's.
                // Ditto for the XmlArrayItems and XmlAnyElements.
                if (xmlAtts.XmlElements.Count > 0)
                {
                    XmlElements = xmlAtts.XmlElements;
                }

                if (xmlAtts.XmlArrayItems.Count > 0)
                {
                    XmlArrayItems = xmlAtts.XmlArrayItems;
                }

                XmlAnyAttribute = xmlAtts.XmlAnyAttribute;

                if (xmlAtts.XmlAnyElements.Count > 0)
                {
                    XmlAnyElements = xmlAtts.XmlAnyElements;
                }
            }
        }
Exemplo n.º 7
0
        public void XmlArrayDifferentNames()
        {
            XmlArrayAttribute array1 = new XmlArrayAttribute("myname");
            XmlArrayAttribute array2 = new XmlArrayAttribute("myothername");

            atts1.XmlArray = array1;
            atts2.XmlArray = array2;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMe), atts2);

            ThumbprintHelpers.DifferentThumbprint(ov1, ov2);
        }
Exemplo n.º 8
0
        public void XmlArraySameName()
        {
            XmlArrayAttribute array1 = new XmlArrayAttribute("myname");
            XmlArrayAttribute array2 = new XmlArrayAttribute("myname");

            atts1.XmlArray = array1;
            atts2.XmlArray = array2;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMe), atts2);

            ThumbprintHelpers.SameThumbprint(ov1, ov2);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the serialized name for the member.
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public override IEnumerable <DataName> GetName(MemberInfo member)
        {
            if (member is Type)
            {
                XmlRootAttribute rootAttr = TypeCoercionUtility.GetAttribute <XmlRootAttribute>(member);
                if (rootAttr != null && !String.IsNullOrEmpty(rootAttr.ElementName))
                {
                    yield return(new DataName(rootAttr.ElementName, null, rootAttr.Namespace));
                }

                XmlTypeAttribute typeAttr = TypeCoercionUtility.GetAttribute <XmlTypeAttribute>(member);
                if (typeAttr != null && !String.IsNullOrEmpty(typeAttr.TypeName))
                {
                    yield return(new DataName(typeAttr.TypeName, null, typeAttr.Namespace));
                }

                yield break;
            }

            XmlElementAttribute elemAttr = TypeCoercionUtility.GetAttribute <XmlElementAttribute>(member);

            if (elemAttr != null && !String.IsNullOrEmpty(elemAttr.ElementName))
            {
                yield return(new DataName(elemAttr.ElementName, null, elemAttr.Namespace));
            }

            XmlAttributeAttribute attrAttr = TypeCoercionUtility.GetAttribute <XmlAttributeAttribute>(member);

            if (attrAttr != null && !String.IsNullOrEmpty(attrAttr.AttributeName))
            {
                yield return(new DataName(attrAttr.AttributeName, null, attrAttr.Namespace, true));
            }

            XmlArrayAttribute arrayAttr = TypeCoercionUtility.GetAttribute <XmlArrayAttribute>(member);

            if (arrayAttr != null && !String.IsNullOrEmpty(arrayAttr.ElementName))
            {
                // TODO: figure out a way to surface XmlArrayItemAttribute name too

                yield return(new DataName(arrayAttr.ElementName, null, arrayAttr.Namespace));
            }

            if (member is FieldInfo && ((FieldInfo)member).DeclaringType.IsEnum)
            {
                XmlEnumAttribute enumAttr = TypeCoercionUtility.GetAttribute <XmlEnumAttribute>(member);
                if (enumAttr != null && !String.IsNullOrEmpty(enumAttr.Name))
                {
                    yield return(new DataName(enumAttr.Name));
                }
            }
        }
Exemplo n.º 10
0
 private static void AddXmlArrayPrint(XmlArrayAttribute att, StringBuilder printBuilder)
 {
     if (null != att)
     {
         printBuilder.Append(att.ElementName);
         printBuilder.Append("/");
         printBuilder.Append(att.Form);
         printBuilder.Append("/");
         printBuilder.Append(att.IsNullable);
         printBuilder.Append("/");
         printBuilder.Append(att.Namespace);
     }
     printBuilder.Append("%%");
 }
Exemplo n.º 11
0
 protected virtual Serializer <TContext> CreateArraySerializer(PropertyInfo property,
                                                               XmlArrayAttribute arrayAttribute,
                                                               XmlArrayItemAttribute arrayItemAttribute)
 {
     return(CreateSerializer(
                CreateArraySerializer(
                    property,
                    string.IsNullOrEmpty(arrayAttribute.Name) ? property.Name : arrayAttribute.Name,
                    arrayAttribute.Namespace,
                    arrayAttribute.Prefix,
                    arrayAttribute.OmitIfEmpty,
                    arrayItemAttribute),
                arrayAttribute.OmitIfNull));
 }
Exemplo n.º 12
0
    // Return an XmlSerializer used for overriding.
    public XmlSerializer CreateOverrider()
    {
        // Creating XmlAttributeOverrides and XmlAttributes objects.
        XmlAttributeOverrides xOver  = new XmlAttributeOverrides();
        XmlAttributes         xAttrs = new XmlAttributes();

        // Add an override for the XmlArray.
        XmlArrayAttribute xArray = new XmlArrayAttribute("Staff");

        xArray.Namespace = "http://www.cpandl.com";
        xAttrs.XmlArray  = xArray;
        xOver.Add(typeof(Group), "Members", xAttrs);

        // Create the XmlSerializer and return it.
        return(new XmlSerializer(typeof(Group), xOver));
    }
        public void DocumentLiteralWithNamedOutArrayParameter()
        {
            WebServiceProxyFactory wspf = new WebServiceProxyFactory();

            wspf.ServiceUri       = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl");
            wspf.ServiceInterface = typeof(IHelloWorld);
            wspf.AfterPropertiesSet();

            object proxy = wspf.GetObject();

            Assert.IsNotNull(proxy);

            Type proxyType = proxy.GetType();

            Assert.IsTrue(proxy is IHelloWorld);
            Assert.IsTrue(proxy is SoapHttpClientProtocol);

            MethodInfo sayHelloArrayMethod = proxyType.GetMethod("SayHelloArray");

            Assert.IsNotNull(sayHelloArrayMethod);

            object[] sdmaAttrs = sayHelloArrayMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false);
            Assert.IsTrue(sdmaAttrs.Length > 0);

            SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)sdmaAttrs[0];

            Assert.AreEqual("http://www.springframwework.net/SayHelloArray", sdma.Action);
            Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle);
            Assert.AreEqual(string.Empty, sdma.Binding);
            Assert.AreEqual(false, sdma.OneWay);
            Assert.AreEqual(string.Empty, sdma.RequestElementName);
            Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace);
            Assert.AreEqual(string.Empty, sdma.ResponseElementName);
            Assert.AreEqual("http://www.springframwework.net", sdma.ResponseNamespace);
            Assert.AreEqual(SoapBindingUse.Literal, sdma.Use);

            object[] xaAttrs = sayHelloArrayMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(XmlArrayAttribute), false);
            Assert.IsTrue(xaAttrs.Length > 0);

            XmlArrayAttribute xaa = (XmlArrayAttribute)xaAttrs[0];

            Assert.AreEqual("out", xaa.ElementName);

            // Try to instantiate the proxy type
            ObjectUtils.InstantiateType(proxyType);
        }
Exemplo n.º 14
0
        public void XmlArrayDifferentForm()
        {
            XmlArrayAttribute array1 = new XmlArrayAttribute("myname");

            array1.Form = System.Xml.Schema.XmlSchemaForm.Qualified;
            XmlArrayAttribute array2 = new XmlArrayAttribute("myname");

            array2.Form = System.Xml.Schema.XmlSchemaForm.Unqualified;

            atts1.XmlArray = array1;
            atts2.XmlArray = array2;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMe), atts2);

            ThumbprintHelpers.DifferentThumbprint(ov1, ov2);
        }
Exemplo n.º 15
0
        public void XmlArrayDifferentNullable()
        {
            XmlArrayAttribute array1 = new XmlArrayAttribute("myname");

            array1.IsNullable = true;
            XmlArrayAttribute array2 = new XmlArrayAttribute("myname");

            array2.IsNullable = false;

            atts1.XmlArray = array1;
            atts2.XmlArray = array2;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMe), atts2);

            ThumbprintHelpers.DifferentThumbprint(ov1, ov2);
        }
Exemplo n.º 16
0
        public void DefaultConstructor_ReturnsDefaultValues()
        {
            // Call
            var assembly = new SerializableAssembly();

            // Assert
            Assert.IsNull(assembly.Id);
            Assert.IsNull(assembly.Boundary);
            Assert.IsNull(assembly.FeatureMembers);

            object[] serializableAttributes = typeof(SerializableAssembly).GetCustomAttributes(typeof(SerializableAttribute), false);
            Assert.AreEqual(1, serializableAttributes.Length);

            var xmlRootAttribute = (XmlRootAttribute)typeof(SerializableAssembly).GetCustomAttributes(typeof(XmlRootAttribute), false).Single();

            Assert.AreEqual("Assemblage", xmlRootAttribute.ElementName);
            Assert.AreEqual("http://localhost/standaarden/assemblage", xmlRootAttribute.Namespace);

            const string gmlNamespace = "http://www.opengis.net/gml/3.2";

            SerializableAttributeTestHelper.AssertXmlAttributeAttribute <SerializableAssembly>(
                nameof(SerializableAssembly.Id), "id", gmlNamespace);
            SerializableAttributeTestHelper.AssertXmlElementAttribute <SerializableAssembly>(
                nameof(SerializableAssembly.Boundary), "boundedBy", gmlNamespace);

            XmlArrayAttribute xmlArrayAttribute = TypeUtils.GetPropertyAttributes <SerializableAssembly, XmlArrayAttribute>(nameof(SerializableAssembly.FeatureMembers)).Single();

            Assert.AreEqual("featureMember", xmlArrayAttribute.ElementName);

            IEnumerable <XmlArrayItemAttribute> xmlArrayItemAttributes = TypeUtils.GetPropertyAttributes <SerializableAssembly, XmlArrayItemAttribute>(nameof(SerializableAssembly.FeatureMembers));

            Assert.AreEqual(8, xmlArrayItemAttributes.Count());
            Assert.AreEqual(typeof(SerializableAssessmentSection), xmlArrayItemAttributes.ElementAt(0).Type);
            Assert.AreEqual(typeof(SerializableAssessmentProcess), xmlArrayItemAttributes.ElementAt(1).Type);
            Assert.AreEqual(typeof(SerializableTotalAssemblyResult), xmlArrayItemAttributes.ElementAt(2).Type);
            Assert.AreEqual(typeof(SerializableFailureMechanism), xmlArrayItemAttributes.ElementAt(3).Type);
            Assert.AreEqual(typeof(SerializableFailureMechanismSectionAssembly), xmlArrayItemAttributes.ElementAt(4).Type);
            Assert.AreEqual(typeof(SerializableCombinedFailureMechanismSectionAssembly), xmlArrayItemAttributes.ElementAt(5).Type);
            Assert.AreEqual(typeof(SerializableFailureMechanismSectionCollection), xmlArrayItemAttributes.ElementAt(6).Type);
            Assert.AreEqual(typeof(SerializableFailureMechanismSection), xmlArrayItemAttributes.ElementAt(7).Type);
        }
Exemplo n.º 17
0
        // this method is for loading vanilla valid xml. It has a <List> tag inside the root tag, so we have to wrap it around something.
        public static List <T> LoadXmlEx <T>(string localpath, string root, string item, string modpath = null, string pattern = "*.xml")
        {
            var defs_type = typeof(DefsEx <T>);
            // we only create a new serializer if we can't find one for the type DefsEx<T>.
            var id = Path.Combine(localpath, defs_type.ToString());

            if (!serializers.ContainsKey(id))
            {
                var type_attrs = new XmlAttributes();
                var root_attr  = new XmlRootAttribute(root);
                type_attrs.XmlRoot = root_attr;
                var member_attrs = new XmlAttributes();
                var array_attr   = new XmlArrayAttribute("List");
                var item_attr    = new XmlArrayItemAttribute(item);
                member_attrs.XmlArray = array_attr;
                member_attrs.XmlArrayItems.Add(item_attr);
                var overrides = new XmlAttributeOverrides();
                overrides.Add(defs_type, type_attrs);
                overrides.Add(defs_type, "Defs", member_attrs);
                var serializer = new XmlSerializer(defs_type, overrides);
                serializers.Add(id, serializer);
            }
            return(LoadXmlFile <DefsEx <T> >(localpath, modpath, pattern).SelectMany(i => i.Defs).ToList());
        }
        public void NamespaceDefault()
        {
            XmlArrayAttribute attr = new XmlArrayAttribute();

            Assert.IsNull(attr.Namespace);
        }
Exemplo n.º 19
0
        private void writeObjectFolder(string filePath, object obj)
        {
            _ObjectStore.UnMarkSerialized(obj);
            Type objectType = obj.GetType(), stringType = typeof(String);

            string           folderPath       = Path.GetDirectoryName(filePath);
            HashSet <string> nestedProperties = new HashSet <string>();

            List <Tuple <string, object, bool> > queued = new List <Tuple <string, object, bool> >();
            IList <PropertyInfo> fields = this.GetFieldsOrdered(objectType);

            foreach (PropertyInfo propertyInfo in fields)
            {
                if (propertyInfo == null)
                {
                    continue;
                }
                Type propertyType = propertyInfo.PropertyType;
                XmlArrayAttribute     xmlArrayAttribute     = propertyInfo.GetCustomAttribute <XmlArrayAttribute>();
                XmlArrayItemAttribute xmlArrayItemAttribute = propertyInfo.GetCustomAttribute <XmlArrayItemAttribute>();

                if (xmlArrayAttribute != null && xmlArrayItemAttribute != null)
                {
                    bool isLeaf = xmlArrayItemAttribute != null && string.Compare(xmlArrayItemAttribute.DataType, "_leaf_", true) == 0;
                    if (string.IsNullOrEmpty(xmlArrayItemAttribute.ElementName) && xmlArrayItemAttribute.NestingLevel > 0 && propertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(propertyType.GetGenericTypeDefinition()))
                    {
                        Type         genericType        = propertyType.GetGenericArguments()[0];
                        PropertyInfo uniqueIdProperty   = genericType.GetProperty("id", typeof(string));
                        PropertyInfo folderNameProperty = genericType.GetProperty("_folderName", typeof(string));
                        if (folderNameProperty == null)
                        {
                            folderNameProperty = uniqueIdProperty;
                        }

                        PropertyInfo nameProp = objectType.GetProperty("Name", typeof(string));
                        if (uniqueIdProperty != null)
                        {
                            IEnumerable enumerable = propertyInfo.GetValue(obj) as IEnumerable;
                            if (enumerable != null)
                            {
                                bool allSaved = true, nestingValid = true;;
                                int  count = 0;
                                foreach (object nested in enumerable)
                                {
                                    if (nested == null)
                                    {
                                        continue;
                                    }
                                    count++;
                                    if (!_ObjectStore.isSerialized(nested))
                                    {
                                        allSaved = false;
                                    }
                                    object objId = uniqueIdProperty.GetValue(nested);
                                    if (objId == null || string.IsNullOrEmpty(objId.ToString()))
                                    {
                                        nestingValid = false;
                                        break;
                                    }
                                }
                                if (nestingValid && !allSaved)
                                {
                                    string nestedPath = Path.Combine(folderPath, removeInvalidFile(propertyInfo.Name));
                                    Directory.CreateDirectory(nestedPath);
                                    nestedProperties.Add(propertyInfo.Name);
                                    if (xmlArrayItemAttribute.NestingLevel > 1)
                                    {
                                        string prefix = m_NominatedTypeFilePrefix.Count > 0 ? hasFilePrefix(genericType) : "";
                                        IEnumerable <IGrouping <char, object> > groups = null;
                                        if (string.IsNullOrEmpty(prefix))
                                        {
                                            groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(uniqueIdProperty.GetValue(x).ToString()[0]));
                                        }
                                        else
                                        {
                                            int prefixLength = prefix.Length;
                                            groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(initialChar(uniqueIdProperty.GetValue(x).ToString(), prefix, prefixLength)));
                                        }
                                        foreach (IGrouping <char, object> group in groups)
                                        {
                                            string alphaPath = Path.Combine(nestedPath, group.Key.ToString());
                                            Directory.CreateDirectory(alphaPath);
                                            foreach (object nested in group)
                                            {
                                                _ObjectStore.MarkSerialized(nested);
                                                string nestedObjectPath = isLeaf ? alphaPath : Path.Combine(alphaPath, removeInvalidFile(folderNameProperty.GetValue(nested).ToString()));
                                                Directory.CreateDirectory(nestedObjectPath);
                                                string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml");
                                                queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf));
                                            }
                                        }
                                        continue;
                                    }
                                    foreach (object nested in enumerable)
                                    {
                                        if (nested == null)
                                        {
                                            continue;
                                        }
                                        _ObjectStore.MarkSerialized(nested);
                                        string nestedObjectPath = isLeaf ? nestedPath : Path.Combine(nestedPath, removeInvalidFile(isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : folderNameProperty.GetValue(nested).ToString()));
                                        Directory.CreateDirectory(nestedObjectPath);
                                        string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml");
                                        queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf));
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    object propertyObject = propertyInfo.GetValue(obj);
                    if (propertyObject == null)
                    {
                        nestedProperties.Add(propertyInfo.Name);
                    }
                    else
                    {
                        DataType dataType = DataType.Custom;
                        string   fileExtension = ".txt", txt = "";
                        foreach (DataTypeAttribute dataTypeAttribute in propertyInfo.GetCustomAttributes <DataTypeAttribute>())
                        {
                            FileExtensionsAttribute fileExtensionsAttribute = dataTypeAttribute as FileExtensionsAttribute;
                            if (fileExtensionsAttribute != null && !string.IsNullOrEmpty(fileExtensionsAttribute.Extensions))
                            {
                                fileExtension = fileExtensionsAttribute.Extensions;
                            }
                            if (dataTypeAttribute.DataType != DataType.Custom)
                            {
                                dataType = dataTypeAttribute.DataType;
                            }
                        }
                        if (dataType == DataType.Html)
                        {
                            string html = propertyObject.ToString();
                            if (!string.IsNullOrEmpty(html))
                            {
                                nestedProperties.Add(propertyInfo.Name);
                                string htmlPath = Path.Combine(folderPath, propertyInfo.Name + ".html");
                                File.WriteAllText(htmlPath, html.TrimEnd() + Environment.NewLine, Encoding.UTF8);
                                continue;
                            }
                        }
                        else if (dataType == DataType.MultilineText)
                        {
                            byte[] byteArray = propertyObject as byte[];
                            if (byteArray != null)
                            {
                                nestedProperties.Add(propertyInfo.Name);
                                txt = Encoding.ASCII.GetString(byteArray);
                            }
                            else
                            {
                                txt = propertyObject.ToString();
                            }
                            if (!string.IsNullOrEmpty(txt))
                            {
                                nestedProperties.Add(propertyInfo.Name);
                                string txtPath = Path.Combine(folderPath, propertyInfo.Name + fileExtension);
                                File.WriteAllText(txtPath, txt.TrimEnd() + Environment.NewLine, Encoding.UTF8);
                                continue;
                            }
                        }
                    }
                }
            }
            if (nestedProperties.Count < fields.Count)
            {
                _ObjectStore.UnMarkSerialized(obj);
                using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    writeObject(fileStream, obj, nestedProperties);
                }
            }
            foreach (Tuple <string, object, bool> o in queued)
            {
                if (o.Item3)
                {
                    _ObjectStore.UnMarkSerialized(o.Item2);
                    using (FileStream fileStream = new FileStream(o.Item1, FileMode.Create, FileAccess.Write))
                    {
                        writeObject(fileStream, o.Item2, new HashSet <string>());
                    }
                }
                else
                {
                    writeObjectFolder(o.Item1, o.Item2);
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <param name="list"></param>
        /// <param name="inherit"></param>
        /// <param name="inverse"></param>
        /// <param name="platform">Specific version, or UNSET to use default (latest)</param>
        private void BuildFieldList(Type type, IList <PropertyInfo> list, bool inherit, bool inverse)
        {
            if (inherit && type.BaseType != typeof(object) && type.BaseType != typeof(Serializer))
            {
                BuildFieldList(type.BaseType, list, inherit, inverse);

                // zero-out any fields that are overridden as derived at subtype (e.g. IfcSIUnit.Dimensions)
                for (int iField = 0; iField < list.Count; iField++)
                {
                    PropertyInfo field = list[iField];
                    if (field != null)
                    {
                        PropertyInfo prop = type.GetProperty(field.Name.Substring(1), BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                        if (prop != null)
                        {
                            list[iField] = null;                             // hide derived fields
                        }
                    }
                }
            }

            PropertyInfo[]                 fields = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            PropertyInfo[]                 sorted = new PropertyInfo[fields.Length];
            List <PropertyInfo>            unorderedAttributes = new List <PropertyInfo>();
            SortedList <int, PropertyInfo> orderedAttributes   = new SortedList <int, PropertyInfo>();

            foreach (PropertyInfo field in fields)
            {
                DataMemberAttribute dataMemberAttribute = field.GetCustomAttribute <DataMemberAttribute>();
                if (_XmlAttributePriority)
                {
                    XmlIgnoreAttribute xmlIgnoreAttribute = field.GetCustomAttribute <XmlIgnoreAttribute>();
                    if (xmlIgnoreAttribute != null)
                    {
                        continue;
                    }
                    XmlElementAttribute xmlElementAttribute = field.GetCustomAttribute <XmlElementAttribute>();
                    if (xmlElementAttribute != null)
                    {
                        if (xmlElementAttribute.Order > -1 && xmlElementAttribute.Order < fields.Length)
                        {
                            sorted[xmlElementAttribute.Order] = field;
                            continue;
                        }
                        if (dataMemberAttribute == null)
                        {
                            unorderedAttributes.Add(field);
                            continue;
                        }
                    }
                    XmlAttributeAttribute xmlAttributeAttribute = field.GetCustomAttribute <XmlAttributeAttribute>();
                    if (xmlAttributeAttribute != null)
                    {
                        if (dataMemberAttribute != null && dataMemberAttribute.Order >= 0)
                        {
                            orderedAttributes.Add(dataMemberAttribute.Order, field);
                            continue;
                        }
                        if (dataMemberAttribute == null)
                        {
                            unorderedAttributes.Add(field);
                            continue;
                        }
                    }
                    XmlArrayAttribute xmlArrayAttribute = field.GetCustomAttribute <XmlArrayAttribute>();
                    if (xmlArrayAttribute != null)
                    {
                        if (xmlArrayAttribute.Order > -1 && xmlArrayAttribute.Order < fields.Length)
                        {
                            sorted[xmlArrayAttribute.Order] = field;
                            continue;
                        }
                        if (dataMemberAttribute == null)
                        {
                            unorderedAttributes.Add(field);
                            continue;
                        }
                    }
                }
                if (dataMemberAttribute != null)
                {
                    if (dataMemberAttribute.Order < fields.Length)
                    {
                        sorted[dataMemberAttribute.Order] = field;
                    }
                    else
                    {
                        unorderedAttributes.Add(field);
                    }
                }
            }

            foreach (PropertyInfo sort in sorted)
            {
                if (sort != null)
                {
                    list.Add(sort);
                }
            }
            foreach (PropertyInfo propertyInfo in orderedAttributes.Values)
            {
                list.Add(propertyInfo);
            }
            foreach (PropertyInfo propertyInfo in unorderedAttributes)
            {
                list.Add(propertyInfo);
            }
            // now inverse -- need particular order???
            if (inverse)
            {
                //fields = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                foreach (PropertyInfo field in fields)
                {
                    if (field.IsDefined(typeof(InversePropertyAttribute), false))
                    {
                        list.Add(field);
                    }
                }
            }
        }
Exemplo n.º 21
0
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlAttributes(ICustomAttributeProvider provider)
        {
            object[] attrs = provider.GetCustomAttributes(false);

            // most generic <any/> matches everything
            XmlAnyElementAttribute wildcard = null;

            for (int i = 0; i < attrs.Length; i++)
            {
                if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute)
                {
                    _xmlIgnore = true;
                    break;
                }
                else if (attrs[i] is XmlElementAttribute)
                {
                    _xmlElements.Add((XmlElementAttribute)attrs[i]);
                }
                else if (attrs[i] is XmlArrayItemAttribute)
                {
                    _xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]);
                }
                else if (attrs[i] is XmlAnyElementAttribute)
                {
                    XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i];
                    if ((any.Name == null || any.Name.Length == 0) && any.NamespaceSpecified && any.Namespace == null)
                    {
                        // ignore duplicate wildcards
                        wildcard = any;
                    }
                    else
                    {
                        _xmlAnyElements.Add((XmlAnyElementAttribute)attrs[i]);
                    }
                }
                else if (attrs[i] is DefaultValueAttribute)
                {
                    _xmlDefaultValue = ((DefaultValueAttribute)attrs[i]).Value;
                }
                else if (attrs[i] is XmlAttributeAttribute)
                {
                    _xmlAttribute = (XmlAttributeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlArrayAttribute)
                {
                    _xmlArray = (XmlArrayAttribute)attrs[i];
                }
                else if (attrs[i] is XmlTextAttribute)
                {
                    _xmlText = (XmlTextAttribute)attrs[i];
                }
                else if (attrs[i] is XmlEnumAttribute)
                {
                    _xmlEnum = (XmlEnumAttribute)attrs[i];
                }
                else if (attrs[i] is XmlRootAttribute)
                {
                    _xmlRoot = (XmlRootAttribute)attrs[i];
                }
                else if (attrs[i] is XmlTypeAttribute)
                {
                    _xmlType = (XmlTypeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlAnyAttributeAttribute)
                {
                    _xmlAnyAttribute = (XmlAnyAttributeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlChoiceIdentifierAttribute)
                {
                    _xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attrs[i];
                }
                else if (attrs[i] is XmlNamespaceDeclarationsAttribute)
                {
                    _xmlns = true;
                }
            }
            if (_xmlIgnore)
            {
                _xmlElements.Clear();
                _xmlArrayItems.Clear();
                _xmlAnyElements.Clear();
                _xmlDefaultValue     = null;
                _xmlAttribute        = null;
                _xmlArray            = null;
                _xmlText             = null;
                _xmlEnum             = null;
                _xmlType             = null;
                _xmlAnyAttribute     = null;
                _xmlChoiceIdentifier = null;
                _xmlns = false;
            }
            else
            {
                if (wildcard != null)
                {
                    _xmlAnyElements.Add(wildcard);
                }
            }
        }
Exemplo n.º 22
0
        internal static bool TryGetTag(MemberInfo member, out int tag, out string name, bool callerIsTagInference, out DataFormat format, out MemberSerializationOptions options)
        {
            name    = member.Name;
            format  = DataFormat.Default;
            tag     = -1;
            options = MemberSerializationOptions.None;

            // check for delegates (don't even try!)
            Type valueType;

            switch (member.MemberType)
            {
            case MemberTypes.Property:
                valueType = ((PropertyInfo)member).PropertyType;
                break;

            case MemberTypes.Field:
                valueType = ((FieldInfo)member).FieldType;
                break;

            default:     // not sure what this is!
                return(false);
            }
            if (valueType.IsSubclassOf(typeof(Delegate)))
            {
                return(false);
            }

            // check for exclusion
            if (AttributeUtils.GetAttribute <ProtoIgnoreAttribute>(member) != null ||
                AttributeUtils.GetAttribute <ProtoPartialIgnoreAttribute>(member.ReflectedType,
                                                                          delegate(ProtoPartialIgnoreAttribute ppia)
                                                                          { return(ppia.MemberName == member.Name); }) != null)
            {
                return(false);
            }

            // check against the property
            ProtoMemberAttribute pm = AttributeUtils.GetAttribute <ProtoMemberAttribute>(member);

            if (pm == null)
            { // check also against the type
                pm = AttributeUtils.GetAttribute <ProtoPartialMemberAttribute>(member.ReflectedType,
                                                                               delegate(ProtoPartialMemberAttribute ppma) { return(ppma.MemberName == member.Name); });
            }
            if (pm != null)
            {
                format = pm.DataFormat;
                if (!string.IsNullOrEmpty(pm.Name))
                {
                    name = pm.Name;
                }
                tag     = pm.Tag;
                options = pm.Options;
                return(tag > 0);
            }

            ProtoContractAttribute pca = AttributeUtils.GetAttribute <ProtoContractAttribute>(member.DeclaringType);

            if (pca != null && pca.ImplicitFields != ImplicitFields.None)
            {
                if (callerIsTagInference)
                {
                    return(true);                     // short-circuit
                }
                List <MemberInfo> members = new List <MemberInfo>();
                switch (pca.ImplicitFields)
                {
                case ImplicitFields.AllFields:
                    AddImplicitByDeclaringType(member.DeclaringType, members,
                                               member.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
                    break;

                case ImplicitFields.AllPublic:
                    AddImplicitByDeclaringType(member.DeclaringType, members,
                                               member.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public));
                    AddImplicitByDeclaringType(member.DeclaringType, members,
                                               member.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public));
                    break;

                default:
                    throw new NotSupportedException("Unknown ImplicitFields option: " + pca.ImplicitFields);
                }
                members.Sort(delegate(MemberInfo x, MemberInfo y)
                {
                    return(string.CompareOrdinal(x.Name, y.Name));
                });
                int index = members.IndexOf(member);
                if (index >= 0)
                {
                    tag = index + pca.ImplicitFirstTag;
                    return(true);
                }
                return(false);
            }


            XmlElementAttribute xe = AttributeUtils.GetAttribute <XmlElementAttribute>(member);

            if (xe != null)
            {
                if (!string.IsNullOrEmpty(xe.ElementName))
                {
                    name = xe.ElementName;
                }
                tag = xe.Order;
                return(tag > 0);
            }

            XmlArrayAttribute xa = AttributeUtils.GetAttribute <XmlArrayAttribute>(member);

            if (xa != null)
            {
                if (!string.IsNullOrEmpty(xa.ElementName))
                {
                    name = xa.ElementName;
                }
                tag = xa.Order;
                return(tag > 0);
            }

            return(false);
        }
Exemplo n.º 23
0
        private static void WriteElement(XmlElement node, object config)
        {
            IEnumerable <PropertyInformation <XmlAttributeAttribute> > attributes = GetProperties <XmlAttributeAttribute>(config);

            foreach (PropertyInformation <XmlAttributeAttribute> pi in attributes)
            {
                object defaultAttr = pi.Property.GetCustomAttributes(typeof(System.ComponentModel.DefaultValueAttribute), true).SingleOrDefault();
                object value       = pi.Property.GetValue(config, null);

                if (defaultAttr != null)
                {
                    object defValue = ((System.ComponentModel.DefaultValueAttribute)defaultAttr).Value;
                    if (defValue == null && value == null)
                    {
                        node.RemoveAttribute(pi.Property.Name);
                        continue;
                    }
                    if (defValue != null && defValue.Equals(value))
                    {
                        node.RemoveAttribute(pi.Property.Name);
                        continue;
                    }
                }
                if (value == null)
                {
                    XmlAttribute attr = node.Attributes[pi.Property.Name];
                    if (attr != null)
                    {
                        node.Attributes.Remove(attr);
                    }
                }
                else
                {
                    string attrValue = String.Format(CultureInfo.InvariantCulture, "{0}", value);

                    if (value is bool)
                    {
                        attrValue = attrValue.ToLower();
                    }

                    node.SetAttribute(pi.Property.Name, attrValue);
                }
            }

            IEnumerable <PropertyInformation <XmlArrayItemAttribute> > boundedCollections = GetProperties <XmlArrayItemAttribute>(config); //there are "unbounded" too. see below

            foreach (var pi in boundedCollections)
            {
                string            containerName = pi.Property.Name;
                XmlArrayAttribute xmlArray      = (XmlArrayAttribute)pi.Property.GetCustomAttributes(typeof(XmlArrayAttribute), true).SingleOrDefault();
                if (xmlArray != null)
                {
                    containerName = xmlArray.ElementName;
                }

                XmlNode container = node.SelectSingleNode(containerName);
                if (container == null)
                {
                    container = node.OwnerDocument.CreateElement(containerName);
                    node.AppendChild(container);
                }

                IEnumerable collection = pi.Property.GetValue(config, null) as IEnumerable;
                WriteCollection(collection, pi.Attribute.ElementName, container);
            }

            IEnumerable <PropertyInformation <XmlElementAttribute> > selfCollection = GetProperties <XmlElementAttribute>(config);//config element contains collection of elements.

            foreach (PropertyInformation <XmlElementAttribute> pi in selfCollection)
            {
                string elementName = pi.Property.Name;
                if (!string.IsNullOrEmpty(pi.Attribute.ElementName))
                {
                    elementName = pi.Attribute.ElementName;
                }

                object      value      = pi.Property.GetValue(config, null);
                IEnumerable collection = value as IEnumerable;
                if (value is string)
                {
                    collection = null;
                }

                if (collection != null)
                {
                    WriteCollection(collection, elementName, node);
                }
                else
                {
                    XmlElement elementXml = (XmlElement)node.SelectSingleNode(elementName);
                    if (elementXml == null)
                    {
                        elementXml = node.OwnerDocument.CreateElement(elementName);
                        node.AppendChild(elementXml);
                    }

                    if (elementXml.Name == "Timeout" && value == null)
                    {
                        XmlNode parent = elementXml.ParentNode;
                        parent.RemoveChild(elementXml);
                    }

                    try
                    {
                        if (value == null)
                        {
                            elementXml.InnerText = string.Empty;
                            continue;
                        }
                        if (value is string || value is int || value is double || value is long)
                        {
                            elementXml.InnerText = value.ToString();
                            continue;
                        }
                        if (value is bool)
                        {
                            bool v = (bool)value;
                            elementXml.InnerText = v ? "true" : "false";
                            continue;
                        }
                    }
                    catch { }

                    WriteElement(elementXml, value);
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// 以pNode为根节点,反序列化pXmlObj中XML属性为pAttr的成员
        /// </summary>
        /// <param name="pNode">源节点元素</param>
        /// <param name="pXmlObj">反序列化对象</param>
        /// <param name="pInfo">当前处理的pXmlObj的成员信息</param>
        /// <param name="pAttr">XmlArray属性</param>
        void ParseMemberXmlArray(XmlNode pNode, ref object pXmlObj, MemberInfo pInfo, XmlArrayAttribute pAttr)
        {
            if (null == pNode)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数XmlNode", MethodBase.GetCurrentMethod().Name);
            }
            if (null == pXmlObj)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数ref object", MethodBase.GetCurrentMethod().Name);
            }
            if (null == pInfo)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数MemberInfo", MethodBase.GetCurrentMethod().Name);
            }
            if (null == pAttr)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数XmlElementAttribute", MethodBase.GetCurrentMethod().Name);
            }

            if (!NodeNameMatch(pNode, pAttr.ElementName))
            {
                return;
            } // 当前MemberInfo不是pNode期望的成员

            switch (GetEnumerableCatagory(pInfo))
            {
            case TEnumerableCatagory.EArray:
            {
                ParseArrayMemberXmlArray(pNode, ref pXmlObj, pInfo, pAttr);
                break;
            }

            case TEnumerableCatagory.EList:
            {
                ParseListMemberXmlArray(pNode, ref pXmlObj, pInfo);
                break;
            }

            case TEnumerableCatagory.EUnknown:
            {
                MyLog.Instance.Warning("在{0}中,{1}可能是未知的可Enumerable反序列化的成员", MethodBase.GetCurrentMethod().Name, pInfo);
                break;
            }

            default:
                throw new NotSupportedException(string.Format("在{0}中,{1}不可被作为可Enumerable反序列化的成员", MethodBase.GetCurrentMethod().Name, pInfo));
            }
        }
 /// <summary>
 /// Sets the <see cref="XmlArrayAttribute"/> for the property.
 /// </summary>
 public OverrideMemberXml <T> Attr(XmlArrayAttribute attribute)
 {
     Attributes.XmlArray = attribute;
     return(this);
 }
Exemplo n.º 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pNode"></param>
        /// <param name="pXmlObj"></param>
        /// <param name="pInfo"></param>
        /// <param name="pAttr"></param>
        void ParseArrayMemberXmlArray(XmlNode pNode, ref object pXmlObj, MemberInfo pInfo, XmlArrayAttribute pAttr)
        {
            if (null == pNode)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数XmlNode", MethodBase.GetCurrentMethod().Name);
            }
            if (null == pXmlObj)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数ref object", MethodBase.GetCurrentMethod().Name);
            }
            if (null == pInfo)
            {
                throw new ArgumentNullException("在{0}中,非法输入参数MemberInfo", MethodBase.GetCurrentMethod().Name);
            }

            // get generic arguments of pInfo
            Type memberType = null;

            switch (pInfo.MemberType)
            {
            case MemberTypes.Field: { memberType = (pInfo as FieldInfo).FieldType; break; }

            case MemberTypes.Property: { memberType = (pInfo as PropertyInfo).PropertyType; break; }

            default: throw new NotSupportedException(string.Format("在{0}中,{1}不可被作为反序列化的成员(MemberType={2})", MethodBase.GetCurrentMethod().Name, pInfo, pInfo.MemberType));
            }

            // create instance of List<T> by T[]
            var typeFullName = memberType.FullName.Remove(memberType.FullName.IndexOf("[]"), 2);
            var genericType  = Assembly.GetAssembly(memberType)?.GetType(typeFullName, true);

            if (null == genericType)
            {
                throw new NullReferenceException(string.Format("在{0}中,无法根据{1}获取Type", MethodBase.GetCurrentMethod().Name, typeFullName));
            }
            Type[] typeArgs       = { genericType };
            var    makeme         = typeof(List <>).MakeGenericType(typeArgs);
            var    arrayMemberObj = Activator.CreateInstance(makeme); // the new created instance

            // get members of T
            List <MemberInfo> miList = new List <MemberInfo>(1);

            miList.AddRange(genericType.GetFields());
            miList.AddRange(genericType.GetProperties());

            // envaluated members of arrayMemberObj from pNode and its children
            foreach (XmlNode child in pNode.ChildNodes)
            {
                var memberObj = genericType.Assembly.CreateInstance(genericType.FullName);
                ParseNodes(child.ChildNodes, ref memberObj, miList);
                MethodInfo methodInfo = arrayMemberObj.GetType().GetMethod("Add", BindingFlags.Instance | BindingFlags.Public);
                methodInfo.Invoke(arrayMemberObj, new object[] { memberObj });
            }

            // convert List<T> to T[]
            MethodInfo methodInfo_ToList = arrayMemberObj.GetType().GetMethod("ToArray", BindingFlags.Instance | BindingFlags.Public);
            var        array             = methodInfo_ToList.Invoke(arrayMemberObj, new object[] { });

            //(pInfo as PropertyInfo).SetValue(pXmlObj, array, null);

            if (pInfo is FieldInfo)
            {
                (pInfo as FieldInfo).SetValue(pXmlObj, Convert.ChangeType(array, (pInfo as FieldInfo).FieldType));
            } // 当前MemberInfo是成员变量
            else if (pInfo is PropertyInfo)
            {
                (pInfo as PropertyInfo).SetValue(pXmlObj, Convert.ChangeType(array, (pInfo as PropertyInfo).PropertyType), null);
            } // 当前MemberInfo是属性
            else
            {
                throw new InvalidCastException(string.Format("{0}不是期望的MemberInfo, 不应被指定XmlElement属性", pInfo));
            } // 当前MemberInfo是不支持的
        }
Exemplo n.º 27
0
        void ProcessType()
        {
            attribute_deserializers = new Dictionary <string, ObjectDeserializer> ();
            element_deserializers   = new Dictionary <string, ObjectDeserializer> ();

            foreach (var property in Properties)
            {
                XmlElementAttribute   element_attribute    = null;
                XmlFlagAttribute      flag_attribute       = null;
                XmlArrayAttribute     array_attribute      = null;
                XmlArrayItemAttribute array_item_attribute = null;
                XmlAttributeAttribute attribute_attribute  = null;

                foreach (var custom_attribute in property.GetCustomAttributes(false))
                {
                    if (custom_attribute is DoNotDeserializeAttribute)
                    {
                        element_attribute   = null;
                        flag_attribute      = null;
                        array_attribute     = null;
                        attribute_attribute = null;
                        value_property      = null;
                        break;
                    }

                    var element = custom_attribute as XmlElementAttribute;
                    if (element != null)
                    {
                        element_attribute = element;
                        continue;
                    }

                    var flag = custom_attribute as XmlFlagAttribute;
                    if (flag != null)
                    {
                        flag_attribute = flag;
                        continue;
                    }

                    var array = custom_attribute as XmlArrayAttribute;
                    if (array != null)
                    {
                        array_attribute = array;
                        continue;
                    }

                    var array_item = custom_attribute as XmlArrayItemAttribute;
                    if (array_item != null)
                    {
                        array_item_attribute = array_item;
                        continue;
                    }

                    var attribute = custom_attribute as XmlAttributeAttribute;
                    if (attribute != null)
                    {
                        attribute_attribute = attribute;
                        continue;
                    }

                    if (custom_attribute is XmlValueAttribute)
                    {
                        // TODO check if this isn't null and throw
                        value_property = property;
                        continue;
                    }
                }

                if (element_attribute != null)
                {
                    var deserializer =
                        CreateCustomDeserializer(property) ??
                        CreateElementDeserializer(property);
                    AddDeserializer(element_deserializers,
                                    CreateName(property.Name, element_attribute.Name, element_attribute.Namespace),
                                    deserializer);
                    continue;
                }

                if (flag_attribute != null)
                {
                    AddDeserializer(element_deserializers,
                                    CreateName(property.Name, flag_attribute.Name, flag_attribute.Namespace),
                                    CreateFlagDeserializer(property));
                    continue;
                }

                if (array_attribute != null)
                {
                    AddDeserializer(element_deserializers,
                                    CreateName(property.Name, array_attribute.Name, array_attribute.Namespace),
                                    CreateArrayElementDeserializer(property));
                    continue;
                }
                else if (array_item_attribute != null)
                {
                    var name       = array_item_attribute.Name;
                    var @namespace = array_item_attribute.Namespace;
                    if (string.IsNullOrEmpty(name))
                    {
                        var item_type      = GetICollection(property.PropertyType).GetGenericArguments()[0];
                        var type_attribute = item_type.GetCustomAttributes(typeof(XmlTypeAttribute), false);
                        if (type_attribute.Length == 0)
                        {
                            name = item_type.Name;
                        }
                        else
                        {
                            var xml_type = (XmlTypeAttribute)type_attribute[0];
                            name       = string.IsNullOrEmpty(xml_type.Name) ? item_type.Name : xml_type.Name;
                            @namespace = xml_type.Namespace;
                        }
                    }
                    AddDeserializer(element_deserializers,
                                    CreateName(name, @namespace),
                                    CreateArrayItemElementDeserializer(property));
                }

                if (attribute_attribute != null)
                {
                    var deserializer =
                        CreateCustomDeserializer(property) ??
                        CreateAttributeDeserializer(property);
                    AddDeserializer(attribute_deserializers,
                                    CreateName(property.Name, attribute_attribute.Name, attribute_attribute.Namespace),
                                    deserializer);
                    continue;
                }
            }
        }
        private void SerializeElement <T>(T obj, List <Attribute> customAttributes, string xmlNodeName = null, XmlTagAttribute classTagAttribute = null)
        {
            if (customAttributes.Any(x => x.GetType() == typeof(XmlIgnoreAttribute)))
            {
                return;
            }

            Type objType = obj.GetType();

            if (validTypes.Any(x => x == objType)) // If the type is one of the basics
            {
                XmlFormatAttribute formatAttribute = GetAttribute <XmlFormatAttribute>(customAttributes);

                string objToString = string.Format("{0" + (formatAttribute == null ? "" : ":" + formatAttribute.Format) + "}", obj);
                bool   xmlEncode   = GetAttribute <XmlCDataAttribute>(customAttributes) == null;
                objToString = EscapeXMLValue(objToString, xmlEncode);

                XmlElementAttribute elementAttribute = GetAttribute <XmlElementAttribute>(customAttributes);
                XmlTagAttribute     tagAttribute     = GetAttribute <XmlTagAttribute>(customAttributes);
                string xmlNodeRestylized             = tagAttribute?.Format(xmlNodeName);
                string xmlNodeClassRestylized        = classTagAttribute?.Format(xmlNodeName);
                xmlNodeName = elementAttribute?.ElementName ?? xmlNodeRestylized ?? xmlNodeClassRestylized ?? xmlNodeName;

                string formattedNode = xmlNodeName != null
                    ? string.Format("<{0}>{1}</{0}>\n", xmlNodeName, objToString)
                    : objToString;

                Append(formattedNode);
            }
            else if (typeof(IEnumerable).IsAssignableFrom(objType)) // If the type is IEnumerable
            {
                Type underlyingType = objType.GetGenericArguments().FirstOrDefault() ?? objType.GetElementType();

                XmlArrayAttribute     arrayAttribute        = GetAttribute <XmlArrayAttribute>(customAttributes);
                XmlArrayItemAttribute arrayItemAttribute    = GetAttribute <XmlArrayItemAttribute>(customAttributes);
                XmlElementAttribute   arrayElementAttribute = GetAttribute <XmlElementAttribute>(customAttributes);

                string collectionNodeName;
                string itemNodeName;
                bool   indent;

                if (arrayElementAttribute != null && (arrayAttribute != null || arrayItemAttribute != null))
                {
                    throw new XmlException("Cannot have both element attribute and array attribute/s");
                }
                else if (arrayElementAttribute != null)
                {
                    collectionNodeName = null;
                    itemNodeName       = arrayElementAttribute.ElementName;
                    indent             = false;
                }
                else
                {
                    collectionNodeName = arrayAttribute?.ElementName ?? xmlNodeName;
                    itemNodeName       = arrayItemAttribute?.ElementName ?? underlyingType.Name;
                    indent             = true;
                }

                if (indent)
                {
                    Append(string.Format("<{0}>\n", collectionNodeName));
                    nestCount++;
                }

                foreach (var item in obj as IEnumerable)
                {
                    SerializeElement(item, new List <Attribute>(), itemNodeName, classTagAttribute);
                }

                if (indent)
                {
                    nestCount--;
                    Append(string.Format("</{0}>\n", collectionNodeName));
                }
            }
            else // If the type is object
            {
                customAttributes.AddRange(GetXmlAttributes(objType));

                XmlRootAttribute    rootAttribute    = GetAttribute <XmlRootAttribute>(customAttributes);
                XmlElementAttribute elementAttribute = GetAttribute <XmlElementAttribute>(customAttributes);
                XmlTagAttribute     tagAttribute     = GetAttribute <XmlTagAttribute>(customAttributes);

                xmlNodeName = elementAttribute?.ElementName ?? rootAttribute?.ElementName ?? xmlNodeName ?? objType.Name;

                var properties = objType.GetProperties();
                var fields     = objType.GetFields();

                int xmlRootIndex = Append("");
                nestCount++;

                Dictionary <string, string> xmlAttributes = new Dictionary <string, string>();

                foreach (var property in properties)
                {
                    List <Attribute> propertyAttributes = GetXmlAttributes(property);

                    XmlAttributeAttribute xmlAttribute = GetAttribute <XmlAttributeAttribute>(propertyAttributes);

                    if (xmlAttribute != null)
                    {
                        string name = xmlAttribute.AttributeName.Length != 0 ? xmlAttribute.AttributeName : property.Name;
                        xmlAttributes.Add(name, property.GetValue(obj, null).ToString());
                    }
                    else
                    {
                        SerializeElement(property.GetValue(obj, null), propertyAttributes, property.Name, tagAttribute ?? classTagAttribute);
                    }
                }

                foreach (var field in fields)
                {
                    List <Attribute> fieldAttributes = GetXmlAttributes(field);

                    XmlAttributeAttribute xmlAttribute = GetAttribute <XmlAttributeAttribute>(fieldAttributes);

                    if (xmlAttribute != null)
                    {
                        string name = xmlAttribute.AttributeName.Length != 0 ? xmlAttribute.AttributeName : field.Name;
                        xmlAttributes.Add(name, field.GetValue(obj).ToString());
                    }
                    else
                    {
                        SerializeElement(field.GetValue(obj), fieldAttributes, field.Name, tagAttribute ?? classTagAttribute);
                    }
                }

                nestCount--;
                Append(string.Format("</{0}>\n", xmlNodeName));

                IEnumerable <string> wholeAttributes = xmlAttributes.Select(x => x.Key + "=\"" + x.Value + "\"");

                string xmlRoot = string.Format("<{0}{1}{2}>\n", xmlNodeName, (wholeAttributes.Any() ? " " : ""), string.Join(" ", wholeAttributes));

                stringList[xmlRootIndex] = xmlRoot;
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Adds specified instance of XmlArrayAttribute to current type or member
 /// </summary>
 public OverrideXml Attr(XmlArrayAttribute attribute)
 {
     Open();
     _attributes.XmlArray = attribute;
     return(this);
 }
Exemplo n.º 30
0
        protected virtual void ProcessProperty(PropertyInfo property,
                                               ICollection <Serializer <TContext> > attributeSerializers,
                                               ICollection <Serializer <TContext> > elementSerializers)
        {
            XmlAttributeAttribute attribute_attribute  = null;
            XmlElementAttribute   element_attribute    = null;
            XmlFlagAttribute      flag_attribute       = null;
            XmlArrayAttribute     array_attribute      = null;
            XmlArrayItemAttribute array_item_attribute = null;
            XmlValueAttribute     value_attribute      = null;

            foreach (var custom_attribute in property.GetCustomAttributes(false))
            {
                if (custom_attribute is DoNotSerializeAttribute)
                {
                    attribute_attribute = null;
                    element_attribute   = null;
                    flag_attribute      = null;
                    array_attribute     = null;
                    value_attribute     = null;
                    break;
                }

                var attribute = custom_attribute as XmlAttributeAttribute;
                if (attribute != null)
                {
                    attribute_attribute = attribute;
                    continue;
                }

                var element = custom_attribute as XmlElementAttribute;
                if (element != null)
                {
                    element_attribute = element;
                    continue;
                }

                var flag = custom_attribute as XmlFlagAttribute;
                if (flag != null)
                {
                    flag_attribute = flag;
                    continue;
                }

                var array = custom_attribute as XmlArrayAttribute;
                if (array != null)
                {
                    array_attribute = array;
                    continue;
                }

                var array_item = custom_attribute as XmlArrayItemAttribute;
                if (array_item != null)
                {
                    array_item_attribute = array_item;
                    continue;
                }

                var value = custom_attribute as XmlValueAttribute;
                if (value != null)
                {
                    value_attribute = value;
                    continue;
                }
            }

            if (attribute_attribute != null)
            {
                attributeSerializers.Add(
                    CreateSerializer(property, CreateAttributeSerializer(property, attribute_attribute)));
            }
            else if (element_attribute != null)
            {
                elementSerializers.Add(
                    CreateSerializer(property, CreateElementSerializer(property, element_attribute)));
            }
            else if (flag_attribute != null)
            {
                elementSerializers.Add(
                    CreateSerializer(property, CreateFlagSerializer(property, flag_attribute)));
            }
            else if (array_attribute != null)
            {
                elementSerializers.Add(
                    CreateSerializer(property,
                                     CreateArraySerializer(property, array_attribute, array_item_attribute)));
            }
            else if (array_item_attribute != null)
            {
                elementSerializers.Add(
                    CreateSerializer(property, CreateArrayItemSerializer(property, array_item_attribute)));
            }
            else if (value_attribute != null)
            {
                elementSerializers.Add(
                    CreateSerializer(property, CreateValueSerializer(property)));
            }
        }