예제 #1
0
        protected string TypeSerializeName(Type type)
        {
            string name = "";

            if (_typeSerializeNames.TryGetValue(type, out name))
            {
                return(name);
            }
            name = type.Name;
            XmlTypeAttribute typeAttribute = type.GetCustomAttribute(typeof(XmlTypeAttribute), false) as XmlTypeAttribute;

            if (typeAttribute != null && !string.IsNullOrEmpty(typeAttribute.TypeName))
            {
                name = typeAttribute.TypeName;
            }
            return(_typeSerializeNames[type] = name);
        }
예제 #2
0
        /// <summary>
        /// Get element attribute
        /// Collect custom XmlType name if available, otherwise use class Name
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static XmlElementAttribute getElementOverride(Type type)
        {
            string elementName = type.Name;

            object[] attributes = type.GetCustomAttributes(typeof(XmlTypeAttribute), false);
            if (attributes.Length > 0)
            {
                XmlTypeAttribute typeAttribute = type.GetCustomAttributes(typeof(XmlTypeAttribute), false)[0] as XmlTypeAttribute;
                if (typeAttribute != null)
                {
                    elementName = typeAttribute.TypeName;
                }
            }
            XmlElementAttribute element = new XmlElementAttribute(elementName, type);

            return(element);
        }
예제 #3
0
        public void SameXmlTypeDifferentObjects()
        {
            XmlAttributeOverrides ov1 = new XmlAttributeOverrides();
            XmlAttributeOverrides ov2 = new XmlAttributeOverrides();

            XmlTypeAttribute att = new XmlTypeAttribute("myType");

            XmlAttributes atts1 = new XmlAttributes();

            atts1.XmlType = att;
            XmlAttributes atts2 = new XmlAttributes();

            atts2.XmlType = att;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMe), atts2);
            ThumbprintHelpers.SameThumbprint(ov1, ov2);
        }
예제 #4
0
        private static Entity Load(Type type)
        {
            Attribute[] attribs  = Attribute.GetCustomAttributes(type);
            bool        isEntity = false;
            string      name     = null;

            for (int i = 0; i < attribs.Length; i++)
            {
                if (attribs[i] is ProtoContractAttribute)
                {
                    ProtoContractAttribute pca = (ProtoContractAttribute)attribs[i];
                    name     = pca.Name;
                    isEntity = true;
                    break;
                }
            }
            if (!isEntity)
            {
                for (int i = 0; i < attribs.Length; i++)
                {
                    if (attribs[i].GetType().FullName == Serializer.DataContractAttributeFullName)
                    {
                        Serializer.ParseDataContractAttribute(attribs[i], out name);
                        isEntity = true;
                        break;
                    }
                }
            }
            if (!isEntity)
            {
                for (int i = 0; i < attribs.Length; i++)
                {
                    if (attribs[i] is XmlTypeAttribute)
                    {
                        XmlTypeAttribute xta = (XmlTypeAttribute)attribs[i];
                        name     = xta.TypeName;
                        isEntity = true;
                        break;
                    }
                }
            }
            return(isEntity ? new Entity(type, name, null) : null);
        }
예제 #5
0
        public void TestHeaderGeneration()
        {
            ProjectMappingManagerSetup.InitializeManager(ServiceProvider, "ProjectMapping.DataContractDsl.Tests.xml");

            DataContractEnum rootElement = CreateDefaultDataContractEnum();
            string           content     = RunTemplate(rootElement);

            Type generatedType = CompileAndGetType(content);

            Assert.IsTrue(generatedType.IsEnum);
            Assert.AreEqual <string>(ElementName, generatedType.Name);
            XmlRootAttribute xmlRootAttr = TypeAsserter.AssertAttribute <XmlRootAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlRootAttr.Namespace);
            Assert.IsFalse(xmlRootAttr.IsNullable);
            XmlTypeAttribute xmlTypeAttr = TypeAsserter.AssertAttribute <XmlTypeAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlTypeAttr.Namespace);
        }
예제 #6
0
        public void DifferentTypesSameXmlTypes()
        {
            XmlAttributeOverrides ov1 = new XmlAttributeOverrides();
            XmlAttributeOverrides ov2 = new XmlAttributeOverrides();

            XmlTypeAttribute att1 = new XmlTypeAttribute("myType");
            XmlTypeAttribute att2 = new XmlTypeAttribute("myType");

            XmlAttributes atts1 = new XmlAttributes();

            atts1.XmlType = att1;
            XmlAttributes atts2 = new XmlAttributes();

            atts2.XmlType = att2;

            ov1.Add(typeof(SerializeMe), atts1);
            ov2.Add(typeof(SerializeMeToo), atts2);
            ThumbprintHelpers.DifferentThumbprint(ov1, ov2);
        }
        public void TestPrimitiveHeaderGeneration()
        {
            ProjectMappingManagerSetup.InitializeManager(ServiceProvider, "ProjectMapping.DataContractDsl.Tests.xml");

            PrimitiveDataTypeCollection collectionElement =
                CreateDefaultPrimitiveDataTypeCollection(typeof(Collection <>), PrimitiveDataElementType1);
            string content = RunTemplate(collectionElement);

            Type generatedType = CompileAndGetType(content);

            Assert.IsTrue(generatedType.IsClass);
            Assert.AreEqual <Type>(typeof(Collection <int>), generatedType.BaseType);
            XmlRootAttribute xmlRootAttr = TypeAsserter.AssertAttribute <XmlRootAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlRootAttr.Namespace);
            Assert.IsFalse(xmlRootAttr.IsNullable);
            XmlTypeAttribute xmlTypeAttr = TypeAsserter.AssertAttribute <XmlTypeAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlTypeAttr.Namespace);
        }
예제 #8
0
        /// <summary>
        /// Serializa um objeto para Xml
        /// </summary>
        /// <typeparam name="T">Tipo do objeto</typeparam>
        /// <param name="obj">Objeto</param>
        /// <returns>Xml serializado</returns>
        public static XmlNode SerializeToXml <T>(T obj)
        {
            var doc = new XmlDocument();
            var nav = doc.CreateNavigator();

            XmlSerializerNamespaces ns      = new XmlSerializerNamespaces();
            XmlTypeAttribute        xmlType = (XmlTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(XmlTypeAttribute));

            if (xmlType != null)
            {
                ns.Add("", xmlType.Namespace);
            }

            using (var writer = nav.AppendChild())
            {
                var ser = new XmlSerializer(typeof(T));
                ser.Serialize(writer, obj, ns);
            }

            return(doc);
        }
예제 #9
0
        protected override Serializer <TContext> CreateTypeStartAutoSerializer()
        {
            var    name       = Type.Name;
            string @namespace = null;
            string prefix     = null;

            XmlTypeAttribute type_attribute = null;
            var namespaces = new List <XmlNamespaceAttribute> ();

            foreach (var custom_attribute in Type.GetCustomAttributes(false))
            {
                var xml_type = custom_attribute as XmlTypeAttribute;
                if (xml_type != null)
                {
                    type_attribute = xml_type;
                    continue;
                }
                else
                {
                    var xml_namespace = custom_attribute as XmlNamespaceAttribute;
                    if (xml_namespace != null)
                    {
                        namespaces.Add(xml_namespace);
                    }
                }
            }

            if (type_attribute != null)
            {
                if (!string.IsNullOrEmpty(type_attribute.Name))
                {
                    name = type_attribute.Name;
                }
                @namespace = type_attribute.Namespace;
                prefix     = type_attribute.Prefix;
            }

            return(CreateTypeStartAutoSerializer(
                       name, @namespace, prefix, namespaces.Count == 0 ? null : namespaces.ToArray()));
        }
예제 #10
0
        /// <summary>
        /// Serializes any object to XML.
        /// </summary>
        /// <param name="report">The object to serialize.</param>
        /// <returns>Xml of the serialized object.</returns>
        public static XmlDocument SerializeToXml(this Object report)
        {
            // Get XmlTypeAttribute
            XmlTypeAttribute xta = Attribute.GetCustomAttribute(report.GetType(), typeof(XmlTypeAttribute)) as XmlTypeAttribute;

            if (xta == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidDocumentAttribute);
            }

            // Get XmlRootAttribute
            XmlRootAttribute xra = Attribute.GetCustomAttribute(report.GetType(), typeof(XmlRootAttribute)) as XmlRootAttribute;

            if (xra == null)
            {
                xra = new XmlRootAttribute();
            }
            xra.Namespace = xta.Namespace;

            XmlDocument output = new XmlDocument();

            output.PreserveWhitespace = true;

            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();

            xsn.Add(string.Empty, string.Empty);

            StringBuilder sb   = new StringBuilder();
            XmlWriter     xmlw = XmlWriter.Create(sb);

            //XmlSerializer xmlSerializer = new XmlSerializer(report.GetType(), xra); -- Use new CachingXmlSerializerFactory class
            var xmlSerializer = CachingXmlSerializerFactory.Create(report.GetType(), xra);

            xmlSerializer.Serialize(xmlw, report, xsn);
            xmlw.Close();

            output.LoadXml(sb.ToString());

            return(output);
        }
예제 #11
0
        public static List <T> all <T>()
        {
            Type type = typeof(T);
            Type list = typeof(List <T>);

            Type[] extraTypes = new Type[1];
            extraTypes[0] = typeof(T);

            string defaultNamespace      = "";
            string xmlroot               = type.Name.ToString().Pluralize().ToLower();
            string ResourceCollectionURL = RESTfulResourceBase.baseurl + type.Name.ToString().ToLower().Pluralize() + ".xml";

            XmlAttributes         xmlAttributes         = new XmlAttributes();
            XmlTypeAttribute      xmlTypeAttribute      = new XmlTypeAttribute(type.ToString().ToLower());
            XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();

            xmlAttributes.XmlType = xmlTypeAttribute;
            xmlAttributeOverrides.Add(type, xmlAttributes);

            HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(ResourceCollectionURL);
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                Console.WriteLine(e.Message);
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream        stream     = response.GetResponseStream();
                XmlSerializer serializer = new XmlSerializer(list, xmlAttributeOverrides, extraTypes, new XmlRootAttribute(xmlroot), defaultNamespace);
                return((List <T>)serializer.Deserialize(stream));
            }
            //else if (response.StatusCode == HttpStatusCode.NotFound)
            throw new System.Exception("404 Resource does not exist");
        }
예제 #12
0
        private void CreateClass(Type t)
        {
            ClassDeclaration c = this.ns.AddClass(this.conformer.ToCapitalized(t.Name));

            // check if XmlType present
            if (TypeHelper.HasCustomAttribute(t, typeof(XmlTypeAttribute)))
            {
                XmlTypeAttribute typeAttr =
                    (XmlTypeAttribute)TypeHelper.GetFirstCustomAttribute(t, typeof(XmlTypeAttribute));
                AttributeDeclaration type = c.CustomAttributes.Add(typeof(XmlTypeAttribute));
                type.Arguments.Add("IncludeInSchema", Expr.Prim(typeAttr.IncludeInSchema));
                if (this.Config.KeepNamespaces)
                {
                    type.Arguments.Add("Namespace", Expr.Prim(typeAttr.Namespace));
                }
                type.Arguments.Add("TypeName", Expr.Prim(typeAttr.TypeName));
            }

            // check if XmlRoot present
            if (TypeHelper.HasCustomAttribute(t, typeof(XmlRootAttribute)))
            {
                XmlRootAttribute rootAttr =
                    (XmlRootAttribute)TypeHelper.GetFirstCustomAttribute(t, typeof(XmlRootAttribute));
                AttributeDeclaration root = c.CustomAttributes.Add(typeof(XmlRootAttribute));

                root.Arguments.Add("ElementName", Expr.Prim(rootAttr.ElementName));
                root.Arguments.Add("IsNullable", Expr.Prim(rootAttr.IsNullable));
                if (this.Config.KeepNamespaces)
                {
                    root.Arguments.Add("Namespace", Expr.Prim(rootAttr.Namespace));
                }
                root.Arguments.Add("DataType", Expr.Prim(rootAttr.DataType));
            }
            else
            {
                AttributeDeclaration root = c.CustomAttributes.Add(typeof(XmlRootAttribute));
                root.Arguments.Add("ElementName", Expr.Prim(t.Name));
            }
            this.types.Add(t, c);
        }
예제 #13
0
        private bool IsAnonymousType(Type t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }

            //check for the presence of an XmlTypeAttribute(AnonymousType = true) flag.
            object[] xmlTypeAttributes = t.GetCustomAttributes(typeof(XmlTypeAttribute), false);
            if (xmlTypeAttributes != null && xmlTypeAttributes.Length > 0)
            {
                XmlTypeAttribute xmlTypeAtt = xmlTypeAttributes[0] as XmlTypeAttribute;
                if (xmlTypeAtt != null && xmlTypeAtt.AnonymousType)
                {
                    return(true);
                }
            }
            return(false);
            //else it may be an aggregate type.//UNDONE
            //PropertyInfo cTypeProp = t.GetProperty("cType");//HACK assuming all types with a cType property are wrappers for arrays!
            //return cTypeProp != null;
        }
        /// <summary>
        /// Get the Namespace from a type's <see cref="XmlRootAttribute"/> (preferred) or <see cref="XmlTypeAttribute"/>.
        /// </summary>
        /// <exception cref="ArgumentException"> Thrown if no namespace is specified through at least one of the possible attributes. </exception>
        public static string GetNamespace(Type type)
        {
            ArgumentUtility.CheckNotNull("type", type);

            XmlTypeAttribute xmlType    = (XmlTypeAttribute)Attribute.GetCustomAttribute(type, typeof(XmlTypeAttribute), true);
            XmlRootAttribute xmlRoot    = (XmlRootAttribute)Attribute.GetCustomAttribute(type, typeof(XmlRootAttribute), true);
            bool             hasXmlType = xmlType != null;
            bool             hasXmlRoot = xmlRoot != null;

            if (!hasXmlType && !hasXmlRoot)
            {
                throw new ArgumentException(
                          string.Format(
                              "Cannot determine the xml namespace of type '{0}' because no neither an XmlTypeAttribute nor an XmlRootAttribute has been provided.",
                              type.FullName),
                          "type");
            }

            bool hasXmlTypeNamespace = hasXmlType ? (!String.IsNullOrEmpty(xmlType.Namespace)) : false;
            bool hasXmlRootNamespace = hasXmlRoot ? (!String.IsNullOrEmpty(xmlRoot.Namespace)) : false;

            if (!hasXmlTypeNamespace && !hasXmlRootNamespace)
            {
                throw new ArgumentException(
                          string.Format(
                              "Cannot determine the xml namespace of type '{0}' because neither an XmlTypeAttribute nor an XmlRootAttribute is used to define a namespace for the type.",
                              type.FullName),
                          "type");
            }

            if (hasXmlRootNamespace)
            {
                return(xmlRoot.Namespace);
            }
            else
            {
                return(xmlType.Namespace);
            }
        }
예제 #15
0
        /// <summary>
        /// Gets the XML namespace associated with a serializable object type.
        /// </summary>
        /// <param name="serializableObjectType">The object type for which the XML namespace is being requested.</param>
        /// <returns>The XML namespace.</returns>
        public static string GetXmlNamespace(Type serializableObjectType)
        {
            string xmlNamespace = null;

            try
            {
                object[] attributes = serializableObjectType.GetCustomAttributes(typeof(System.Xml.Serialization.XmlTypeAttribute), false);
                if (attributes.Length == 0)
                {
                    throw new Exception("Missing XmlType attribute on class " + serializableObjectType.Name + ".");
                }
                else
                {
                    XmlTypeAttribute xmlType = (XmlTypeAttribute)attributes[0];
                    xmlNamespace = xmlType.Namespace;
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Unable to get XML namespace for type " + serializableObjectType.Name + ".", exception);
            }
            return(xmlNamespace);
        }
예제 #16
0
        public void GetAllAnonymousSchemaClasses()
        {
            IList <Type> filteredTypes = new List <Type>(allTypes.Length);

            foreach (Type t in allTypes)
            {
                if (!t.IsClass)
                {
                    continue;
                }
                if (t.Namespace == null)
                {
                    continue;
                }
                if (!t.Namespace.Equals("IfcDotNet.Schema"))
                {
                    continue;
                }
                object[] attributes = t.GetCustomAttributes(typeof(XmlTypeAttribute), true);
                if (attributes == null || attributes.Length < 1)
                {
                    continue;
                }
                foreach (object o in attributes)
                {
                    XmlTypeAttribute att = o as XmlTypeAttribute;
                    if (att != null)
                    {
                        if (att.AnonymousType)
                        {
                            logger.Debug(t.FullName);
                            break;
                        }
                    }
                }
            }
        }
        public void TestHeaderGeneration()
        {
            ProjectMappingManagerSetup.InitializeManager(ServiceProvider, "ProjectMapping.DataContractDsl.Tests.xml");

            DataContractCollection collectionElement =
                CreateDefaultDataContractCollectionElement(typeof(Collection <>));
            string content = RunTemplate(collectionElement);

            this.EnsureType(ref content, PrimitiveDataElementName1);
            Type generatedType = CompileAndGetType(content);

            Assert.IsTrue(generatedType.IsClass);
            Assert.AreEqual <string>(ElementName, generatedType.Name);
            XmlRootAttribute xmlRootAttr = TypeAsserter.AssertAttribute <XmlRootAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlRootAttr.Namespace);
            Assert.IsFalse(xmlRootAttr.IsNullable);
            XmlTypeAttribute xmlTypeAttr = TypeAsserter.AssertAttribute <XmlTypeAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlTypeAttr.Namespace);

            Assert.AreEqual <string>(((AsmxDataContractCollection)collectionElement.ObjectExtender).CollectionType.Name, generatedType.BaseType.Name);
            Assert.IsTrue(generatedType.BaseType.FullName.Contains(PrimitiveDataElementName1));
        }
예제 #18
0
 /// <summary>
 /// Adds specified instance of XmlTypeAttribute to current type or member
 /// </summary>
 public OverrideXml Attr(XmlTypeAttribute attribute)
 {
     Open();
     _attributes.XmlType = attribute;
     return(this);
 }
예제 #19
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);
                }
            }
        }
예제 #20
0
        private static MemberInfo[] GetStructFormat(Type t)
        {
            if (false)
            {
                lock (FunctorToLayout)
                {
                    PrologTermLayout layout;
                    if (TypeToLayout.TryGetValue(t, out layout))
                    {
                        return(layout.FieldInfos);
                    }
                }
            }
            bool specialXMLType = false;

            if (!t.IsEnum)
            {
                var ta = t.GetCustomAttributes(typeof(XmlTypeAttribute), false);
                if (ta != null && ta.Length > 0)
                {
                    XmlTypeAttribute xta = (XmlTypeAttribute)ta[0];
                    specialXMLType = true;
                }
            }
            MemberInfo[] tGetFields = null;
            if (specialXMLType)
            {
                List <MemberInfo> fis = new List <MemberInfo>();
                foreach (var e in t.GetFields(InstanceFields))
                {
                    var use = e.GetCustomAttributes(typeof(XmlArrayItemAttribute), false);
                    if (use == null || use.Length < 1)
                    {
                        continue;
                    }
                    fis.Add(e);
                }
                foreach (var e in t.GetProperties(InstanceFields))
                {
                    var use = e.GetCustomAttributes(typeof(XmlArrayItemAttribute), false);
                    if (use == null || use.Length < 1)
                    {
                        continue;
                    }
                    fis.Add(e);
                }
                tGetFields = fis.ToArray();
            }
            else
            {
                // look for [StructLayout(LayoutKind.Sequential)]

                var ta = t.GetCustomAttributes(typeof(StructLayoutAttribute), false);
                if (ta != null && ta.Length > 0)
                {
                    StructLayoutAttribute xta = (StructLayoutAttribute)ta[0];
                    // ReSharper disable ConditionIsAlwaysTrueOrFalse
                    if (xta.Value == LayoutKind.Sequential || true /* all sequential layouts*/)
                    // ReSharper restore ConditionIsAlwaysTrueOrFalse
                    {
                        tGetFields = t.GetFields(InstanceFields);
                    }
                }
                if (tGetFields == null)
                {
                    tGetFields = t.GetFields(InstanceFields);
                }
            }
            if (tGetFields.Length == 0)
            {
                Warn("No fields in {0}", t);
            }
            return(tGetFields);
        }
예제 #21
0
        private void LinkReferences(IDictionary <int, Entity> entities)
        {
            foreach (StepEntityReference orl in this._objectLinks)
            {
                //HACK need some error catching
                if (orl.ReferencingObject < 1)
                {
                    throw new StepBindingException("Attempting to link STEP objects, but the referencing object number is not within bounds (Id is less than 1)");
                }
                if (orl.ReferencedObject < 1)
                {
                    throw new StepBindingException("Attempting to link STEP objects, but the referenced object number is not within bounds (Id is less than 1)");
                }

                Entity referencing;
                try{
                    referencing = entities[orl.ReferencingObject];
                }catch (Exception e) {
                    throw new StepBindingException(String.Format(CultureInfo.InvariantCulture,
                                                                 "Could not locate referencing Entity #{0}",
                                                                 orl.ReferencingObject), e);
                }
                if (referencing == null)
                {
                    throw new StepBindingException(String.Format(CultureInfo.InvariantCulture,
                                                                 "Attempting to link STEP objects but the referencing object, #{0}, is null",
                                                                 orl.ReferencingObject));
                }

                Entity referenced;
                try{
                    referenced = entities[orl.ReferencedObject];
                }catch (Exception e) {
                    throw new StepBindingException(String.Format(CultureInfo.InvariantCulture,
                                                                 "Could not locate referenced Entity #{0}",
                                                                 orl.ReferencedObject), e);
                }
                if (referenced == null)
                {
                    throw new StepBindingException(String.Format(CultureInfo.InvariantCulture,
                                                                 "Attempting to link STEP objects but the referenced object, #{0}, is null",
                                                                 orl.ReferencedObject));
                }

                logger.Debug(String.Format(CultureInfo.InvariantCulture,
                                           "Attempting to link object #{0} of type {1} into {2}property {3}, expecting a type of {4}, of object #{5}, a type of {6}",
                                           orl.ReferencedObject,
                                           referenced.GetType().Name,
                                           orl.IsIndexed ? "index " + orl.Index + " of " : String.Empty,
                                           orl.Property.Name,
                                           orl.Property.PropertyType.Name,
                                           orl.ReferencingObject,
                                           referencing.GetType().Name));

                Object objToInsert = referenced;

                //a quirk of the automatically generated schema is that there are occasionaly intermediate
                //objects which wrap the value we wish to insert
                object[] xmlTypeAttributes = orl.Property.PropertyType.GetCustomAttributes(typeof(XmlTypeAttribute), true);
                logger.Debug("found xmlTypeAttributes : " + xmlTypeAttributes.Length);
                if (xmlTypeAttributes.Length > 0)
                {
                    foreach (object xmlTypeAttribute in xmlTypeAttributes)
                    {
                        XmlTypeAttribute xta = xmlTypeAttribute as XmlTypeAttribute;
                        if (xta == null)
                        {
                            continue;
                        }
                        if (!xta.AnonymousType)
                        {
                            continue;
                        }

                        //search for the actual property within the wrapping object to insert the data into
                        Type   typeToSearchWithin = orl.Property.PropertyType;
                        Object wrappingObj        = orl.Property.GetValue(referencing, null);
                        if (wrappingObj == null)
                        {
                            wrappingObj = Activator.CreateInstance(typeToSearchWithin);
                        }
                        PropertyInfo wrappingProperty = findWrappingProperty(typeToSearchWithin, referenced.GetType());

                        if (wrappingProperty == null)
                        {
                            continue;
                        }

                        logger.Debug(String.Format(CultureInfo.InvariantCulture,
                                                   "Found an intermediate wrapping object of type {0}.  Found a property {1} within the wrapping object, this property expects a type of {2}",
                                                   typeToSearchWithin.Name,
                                                   wrappingProperty.Name,
                                                   wrappingProperty.PropertyType.Name));

                        //insert the referenced into the wrapping object
                        if (orl.IsIndexed)
                        {
                            //it's an array, or similar indexed type
                            Object arr = wrappingProperty.GetValue(wrappingObj, null);
                            if (arr == null)
                            {
                                int length = orl.Index > 0 ? orl.Index + 1 : 1;                                 //FIXME we may require larger arrays
                                logger.Debug("Creating a new array of type " + referenced.GetType().Name + " with length " + length + " to hold data to be inserted into index " + orl.Index);
                                Array array = Array.CreateInstance(referenced.GetType(), length);
                                array.SetValue(referenced, orl.Index);                                    //FIXME array may be out of index
                                wrappingProperty.SetValue(wrappingObj, array, null);
                            }
                            else
                            {
                                Array array = arr as Array;
                                if (array == null)
                                {
                                    throw new StepBindingException("Object could not be cast as an Array");
                                }
                                array.SetValue(referenced, orl.Index);
                                //wrappingProperty.SetValue( wrappingObj, referenced, new object[]{orl.Index});
                            }
                        }
                        else
                        {
                            wrappingProperty.SetValue(wrappingObj, referenced, null);
                        }

                        objToInsert = wrappingObj;
                        break;
                    }
                }

                orl.Property.SetValue(referencing,
                                      objToInsert,
                                      null);                 //unlikely to be indexed if there is no wrapping type (case handled above)
            }
        }
예제 #22
0
        public virtual void AfterPropertiesSet()
        {
            if (ClasspathScanner == null)
            {
                if (Log.InfoEnabled)
                {
                    Log.Info("Skipped scanning for XML transfer types. Reason: No instance of " + typeof(IClasspathScanner).FullName + " resolved");
                }
                return;
            }
            IList <Type> rootElementClasses = ClasspathScanner.ScanClassesAnnotatedWith(typeof(DataContractAttribute), typeof(System.Xml.Serialization.XmlTypeAttribute), typeof(XmlTypeAttribute));

            if (Log.InfoEnabled)
            {
                Log.Info("Found " + rootElementClasses.Count + " classes annotated as XML transfer types");
            }
            if (Log.DebugEnabled)
            {
                List <Type> sorted = new List <Type>(rootElementClasses);
                sorted.Sort(delegate(Type left, Type right)
                {
                    return(left.FullName.CompareTo(right.FullName));
                });
                for (int a = 0, size = sorted.Count; a < size; a++)
                {
                    Log.Debug("Xml entity found: " + sorted[a].Namespace + "." + sorted[a].Name);
                }
            }
            for (int a = rootElementClasses.Count; a-- > 0;)
            {
                Type   rootElementClass = rootElementClasses[a];
                String name;
                String namespaceString;

                XmlTypeAttribute genericXmlType = AnnotationUtil.GetAnnotation <XmlTypeAttribute>(rootElementClass, false);
                if (genericXmlType != null)
                {
                    name            = genericXmlType.Name;
                    namespaceString = genericXmlType.Namespace;
                }
                else
                {
                    DataContractAttribute dataContract = AnnotationUtil.GetAnnotation <DataContractAttribute>(rootElementClass, false);
                    if (dataContract != null)
                    {
                        name            = dataContract.Name;
                        namespaceString = dataContract.Namespace;
                    }
                    else
                    {
                        System.Xml.Serialization.XmlTypeAttribute xmlTypeAttribute = AnnotationUtil.GetAnnotation <System.Xml.Serialization.XmlTypeAttribute>(rootElementClass, false);
                        name            = xmlTypeAttribute.TypeName;
                        namespaceString = xmlTypeAttribute.Namespace;
                    }
                }
                if (DefaultNamespace.Equals(namespaceString))
                {
                    namespaceString = null;
                }
                if (name == null)
                {
                    name = rootElementClass.Name;
                }
                XmlTypeExtendable.RegisterXmlType(rootElementClass, name, namespaceString);
                unregisterRunnables.Add(delegate()
                {
                    XmlTypeExtendable.UnregisterXmlType(rootElementClass, name, namespaceString);
                });
            }
            this.rootElementClasses = rootElementClasses;
        }
예제 #23
0
 /// <summary>
 /// Creates a new xml structure from xml attribute
 /// </summary>
 public SwaggerXmlInfo(XmlTypeAttribute typeInfo)
 {
     this.Namespace = typeInfo.Namespace;
 }
예제 #24
0
        public void IncludeInSchemaDefault()
        {
            XmlTypeAttribute attr = new XmlTypeAttribute();

            Assert.AreEqual(true, attr.IncludeInSchema);
        }
예제 #25
0
        public void NamespaceDefault()
        {
            XmlTypeAttribute attr = new XmlTypeAttribute();

            Assert.IsNull(attr.Namespace);
        }
예제 #26
0
        private static KeyValuePair <List <PropertyInfo>, List <FieldInfo> > GetPropsForTypes(Type t)
        {
            KeyValuePair <List <PropertyInfo>, List <FieldInfo> > kv;

            if (PropForTypes.TryGetValue(t, out kv))
            {
                return(kv);
            }

            lock (PropForTypes)
            {
                if (!PropForTypes.TryGetValue(t, out kv))
                {
                    kv = new KeyValuePair <List <PropertyInfo>, List <FieldInfo> >(new List <PropertyInfo>(),
                                                                                   new List <FieldInfo>());
                    var  ta             = t.GetCustomAttributes(typeof(XmlTypeAttribute), false);
                    bool specialXMLType = false;
                    if (ta != null && ta.Length > 0)
                    {
                        XmlTypeAttribute xta = (XmlTypeAttribute)ta[0];
                        specialXMLType = true;
                    }
                    HashSet <string> lowerProps = new HashSet <string>();
                    BindingFlags     flags      = BindingFlags.Instance | BindingFlags.Public; //BindingFlags.NonPublic
                    foreach (
                        PropertyInfo o in t.GetProperties(flags))
                    {
                        if (o.CanRead)
                        {
                            if (o.Name.StartsWith("_"))
                            {
                                continue;
                            }
                            if (o.DeclaringType == typeof(Object))
                            {
                                continue;
                            }
                            if (!lowerProps.Add(o.Name.ToLower()))
                            {
                                continue;
                            }
                            if (o.GetIndexParameters().Length > 0)
                            {
                                continue;
                            }
                            if (specialXMLType)
                            {
                                var use = o.GetCustomAttributes(typeof(XmlArrayItemAttribute), false);
                                if (use == null || use.Length < 1)
                                {
                                    continue;
                                }
                            }
                            kv.Key.Add(o);
                        }
                    }
                    foreach (FieldInfo o in t.GetFields(flags))
                    {
                        if (o.Name.StartsWith("_"))
                        {
                            continue;
                        }
                        if (o.DeclaringType == typeof(Object))
                        {
                            continue;
                        }
                        if (!lowerProps.Add(o.Name.ToLower()))
                        {
                            continue;
                        }
                        if (specialXMLType)
                        {
                            var use = o.GetCustomAttributes(typeof(XmlArrayItemAttribute), false);
                            if (use == null || use.Length < 1)
                            {
                                continue;
                            }
                        }
                        kv.Value.Add(o);
                    }
                }
                return(kv);
            }
        }
예제 #27
0
 /// <summary>
 /// Adds new attribute to the node decorations.
 /// </summary>
 /// <param name="attr">An attriubute.</param>
 protected void Add(object attr)
 {
     if (attr is NodePolicyAttribute)
     {
         if (_nodePolicy == null)
         {
             _nodePolicy = (NodePolicyAttribute)attr;
         }
     }
     else if (attr is ConverterAttribute)
     {
         if (_converter == null)
         {
             _converter = (ConverterAttribute)attr;
         }
     }
     else if (attr is TransparentAttribute)
     {
         _transparent = (TransparentAttribute)attr;
     }
     else if (attr is SkipNavigableRootAttribute)
     {
         _skipNavigableRoot = (SkipNavigableRootAttribute)attr;
     }
     else if (attr is ChildXmlElementAttribute)
     {
         _childXmlElementName = (ChildXmlElementAttribute)attr;
     }
     else if (attr is XmlRootAttribute)
     {
         if (_xmlRoot == null)
         {
             _xmlRoot = (XmlRootAttribute)attr;
         }
     }
     else if (attr is XmlAttributeAttribute)
     {
         if (NodeTypeUndefined())
         {
             _xmlAttribute = (XmlAttributeAttribute)attr;
         }
     }
     else if (attr is XmlElementAttribute)
     {
         if (NodeTypeUndefined())
         {
             _xmlElement = (XmlElementAttribute)attr;
             _isNullable = _xmlElement.IsNullable;
         }
     }
     else if (attr is XmlAnyElementAttribute)
     {
         if (NodeTypeUndefined())
         {
             _xmlAnyElement = (XmlAnyElementAttribute)attr;
         }
     }
     else if (attr is XmlTextAttribute)
     {
         if (NodeTypeUndefined())
         {
             _xmlText = (XmlTextAttribute)attr;
         }
     }
     else if (attr is XmlIgnoreAttribute)
     {
         _xmlIgnore = (XmlIgnoreAttribute)attr;
     }
     else if (attr is XmlTypeAttribute)
     {
         _xmlType = (XmlTypeAttribute)attr;
     }
 }
 /// <summary>
 /// Sets the <see cref="XmlTypeAttribute"/> for the class.
 /// </summary>
 public OverrideRootXml <T> Attr(XmlTypeAttribute attribute)
 {
     Attributes.XmlType = attribute;
     return(this);
 }
예제 #29
0
        /// <summary>
        /// Create a value set from an enumeration
        /// </summary>
        public ValueSet CreateValueSetFromEnum(Type enumType)
        {
            // Does this have Everest attributes?
            if (enumType.GetCustomAttribute <StructureAttribute>() != null)
            {
                return(CreateValueFromEverestEnum(enumType));
            }
            else
            {
                ValueSet retVal  = new ValueSet();
                var      baseUri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString();

                // XmlType?
                XmlTypeAttribute     xTypeAtt       = enumType.GetCustomAttribute <XmlTypeAttribute>();
                DescriptionAttribute descriptionAtt = enumType.GetCustomAttribute <DescriptionAttribute>();

                retVal.Name       = enumType.Name;
                retVal.Identifier = String.Format("{0}/ValueSet/@{1}", baseUri, enumType.Name);
                retVal.Version    = enumType.Assembly.GetName().Version.ToString();
                retVal.Id         = retVal.Identifier;
                retVal.VersionId  = retVal.Version;

                // Description
                if (descriptionAtt != null)
                {
                    retVal.Description = descriptionAtt.Description;
                }

                // Use the company attribute
                var companyAtt = enumType.Assembly.GetCustomAttribute <AssemblyCompanyAttribute>();
                if (companyAtt != null)
                {
                    retVal.Publisher = companyAtt.Company;
                }

                // Date of the assembly file
                if (!String.IsNullOrEmpty(enumType.Assembly.Location) && File.Exists(enumType.Assembly.Location))
                {
                    retVal.Date = new SVC.Messaging.FHIR.DataTypes.DateOnly()
                    {
                        DateValue = new FileInfo(enumType.Assembly.Location).LastWriteTime
                    }
                }
                ;
                retVal.Timestamp = retVal.Date.DateValue.Value;
                retVal.Status    = new SVC.Messaging.FHIR.DataTypes.PrimitiveCode <string>("testing");

                // Definition
                retVal.Define = new ValueSetDefinition();
                if (xTypeAtt != null)
                {
                    retVal.Define.System = new Uri(String.Format("{0}#{1}", xTypeAtt.Namespace, xTypeAtt.TypeName));
                }
                else
                {
                    retVal.Define.System = new Uri(String.Format("{0}/ValueSet/@{1}", baseUri, enumType.Name));
                }

                // Now populate
                foreach (var value in enumType.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    var definition = new ConceptDefinition();
                    definition.Code     = new SVC.Messaging.FHIR.DataTypes.PrimitiveCode <string>(MARC.Everest.Connectors.Util.ToWireFormat(value.GetValue(null)));
                    definition.Abstract = false;

                    descriptionAtt = value.GetCustomAttribute <DescriptionAttribute>();
                    if (descriptionAtt != null)
                    {
                        definition.Display = descriptionAtt.Description;
                    }

                    retVal.Define.Concept.Add(definition);
                }

                return(retVal);
            }
        }
        private static XmlAttributeOverrides GenerateMzIdentMlOverrides(string namespaceUrl)
        {
            // root override: affects only MzIdentMLType
            //[System.Xml.Serialization.XmlRootAttribute("MzIdentML", Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1", IsNullable = false)]
            // all:
            //[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1")]
            var xmlOverrides      = new XmlAttributeOverrides();
            var xmlTypeNsOverride = new XmlAttributes();
            var xmlTypeNs         = new XmlTypeAttribute {
                Namespace = namespaceUrl
            };

            xmlTypeNsOverride.XmlType = xmlTypeNs;

            var xmlRootOverrides = new XmlAttributes {
                XmlType = xmlTypeNs
            };

            var xmlRootOverride = new XmlRootAttribute
            {
                ElementName = "MzIdentML",
                Namespace   = namespaceUrl,
                IsNullable  = false
            };

            xmlRootOverrides.XmlRoot = xmlRootOverride;

            xmlOverrides.Add(typeof(MzIdentMLType), xmlRootOverrides);
            xmlOverrides.Add(typeof(cvType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationItemRefType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(PeptideHypothesisType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(FragmentArrayType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(IonTypeType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(CVParamType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(UserParamType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ParamType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ParamListType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(PeptideEvidenceRefType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AnalysisDataType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationListType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(MeasureType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(IdentifiableType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(BibliographicReferenceType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProteinDetectionHypothesisType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProteinAmbiguityGroupType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProteinDetectionListType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationItemType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationResultType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ExternalDataType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(FileFormatType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectraDataType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIDFormatType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SourceFileType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SearchDatabaseType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProteinDetectionProtocolType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(TranslationTableType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(MassTableType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ResidueType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AmbiguousResidueType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(EnzymeType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationProtocolType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpecificityRulesType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SearchModificationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(EnzymesType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(FilterType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(DatabaseTranslationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProtocolApplicationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProteinDetectionType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(InputSpectrumIdentificationsType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SpectrumIdentificationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(InputSpectraType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SearchDatabaseRefType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(PeptideEvidenceType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(PeptideType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ModificationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SubstitutionModificationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(DBSequenceType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SampleType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ContactRoleType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(RoleType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SubSampleType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AbstractContactType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(OrganizationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ParentOrganizationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(PersonType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AffiliationType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(ProviderType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AnalysisSoftwareType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(InputsType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(DataCollectionType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AnalysisProtocolCollectionType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(AnalysisCollectionType), xmlTypeNsOverride);
            xmlOverrides.Add(typeof(SequenceCollectionType), xmlTypeNsOverride);

            return(xmlOverrides);
        }