Summary description for XmlAttributes.
Example #1
0
        public byte[] getRequestContent( string doctype, string root, Type type, object obj)
        {
            XmlSerializer serializer = null;
            if (root == null)
            {
                //... root element will be the object type name
                serializer = new XmlSerializer(type);
            }
            else
            {
                //... root element set explicitely
                var xattribs = new XmlAttributes();
                var xroot = new XmlRootAttribute(root);
                xattribs.XmlRoot = xroot;
                var xoverrides = new XmlAttributeOverrides();
                xoverrides.Add(type, xattribs);
                serializer = new XmlSerializer(type, xoverrides);
            }
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;
            settings.Encoding = new UTF8Encoding(false/*no BOM*/, true/*throw if input illegal*/);

            XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
            xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlNameSpace.Add("noNamespaceSchemaLocation", m_schemadir + "/" + doctype + "." + m_schemaext);

            StringWriter sw = new StringWriter();
            XmlWriter xw = XmlWriter.Create( sw, settings);
            xw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");

            serializer.Serialize(xw, obj, xmlNameSpace);

            return settings.Encoding.GetBytes( sw.ToString());
        }
        /// <summary>
        /// Serializes an object into an XML document
        /// </summary>
        /// <param name="obj">object to serialize</param>
        /// <param name="rootAttribute">root attribute to use</param>
        /// <param name="namespacePrefixes">namespace prefixes</param>
        /// <returns>a string that contains the XML document</returns>
        public static string Serialize(object obj, XmlRootAttribute rootAttribute, params XmlQualifiedName[] namespacePrefixes)
        {
            if (obj == null)
            {
                return null;
            }

            using (var textWriter = new StringWriterUTF8())
            {
                var type = obj.GetType();
                var xmlAttributeOverrides = new XmlAttributeOverrides();
                if (rootAttribute != null)
                {
                    var xmlAttributes = new XmlAttributes();
                    xmlAttributes.XmlRoot = rootAttribute;
                    xmlAttributeOverrides.Add(type, xmlAttributes);
                }
                using (var xmWriter = XmlWriter.Create(textWriter, new XmlWriterSettings() { OmitXmlDeclaration = true }))
                {
                    var namespaces = new XmlSerializerNamespaces();
                    if (namespacePrefixes != null)
                    {
                        foreach (var ns in namespacePrefixes)
                        {
                            namespaces.Add(ns.Name, ns.Namespace);
                        }
                    }
                    new XmlSerializer(type, xmlAttributeOverrides).Serialize(xmWriter, obj, namespaces);
                }
                return textWriter.ToString();
            }
        }
        private async void ButtonSendErrorReport_Click(object sender, RoutedEventArgs e)
        {
            var ex = Error.ToExceptionless();
            ex.SetUserDescription(string.Empty, NoteTextBox.Text);
            ex.AddObject(HurricaneSettings.Instance.Config, "HurricaneSettings", null, null, true);

            if (HurricaneSettings.Instance.IsLoaded)
            {
                using (var sw = new StringWriter())
                {
                    XmlAttributeOverrides overrides = new XmlAttributeOverrides(); //DONT serialize the passwords and send them to me!
                    XmlAttributes attribs = new XmlAttributes {XmlIgnore = true};
                    attribs.XmlElements.Add(new XmlElementAttribute("Passwords"));
                    overrides.Add(typeof(ConfigSettings), "Passwords", attribs);

                    var xmls = new XmlSerializer(typeof(ConfigSettings), overrides);
                    xmls.Serialize(sw, HurricaneSettings.Instance.Config);

                    var doc = new XmlDocument();
                    doc.LoadXml(sw.ToString());
                    ex.SetProperty("HurricaneSettings", JsonConvert.SerializeXmlNode(doc));
                }
            }

            ex.Submit();
            ((Button)sender).IsEnabled = false;
            StatusProgressBar.IsIndeterminate = true;
            await ExceptionlessClient.Default.ProcessQueueAsync();
            StatusProgressBar.IsIndeterminate = false;
            Application.Current.Shutdown();
        }
Example #4
0
		public static PersistentVM LoadStateFromFile(string filePath)
		{
			PersistentVM persistentVM;
			if (File.Exists(filePath))
			{
				XmlAttributeOverrides xmlAttributeOverride = new XmlAttributeOverrides();
				XmlAttributes xmlAttribute = new XmlAttributes();
				xmlAttribute.XmlIgnore = true;
				xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "MediaLink", xmlAttribute);
				xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", xmlAttribute);
				xmlAttributeOverride.Add(typeof(OSVirtualHardDisk), "MediaLink", xmlAttribute);
				xmlAttributeOverride.Add(typeof(OSVirtualHardDisk), "SourceImageName", xmlAttribute);
				Type[] typeArray = new Type[1];
				typeArray[0] = typeof(NetworkConfigurationSet);
				XmlSerializer xmlSerializer = new XmlSerializer(typeof(PersistentVM), xmlAttributeOverride, typeArray, null, null);
				using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
				{
					persistentVM = xmlSerializer.Deserialize(fileStream) as PersistentVM;
				}
				return persistentVM;
			}
			else
			{
				throw new ArgumentException("The file to load the role does not exist", "filePath");
			}
		}
Example #5
0
		public void Add (Type type, string member, XmlAttributes attributes) 
		{
			if(overrides[GetKey(type, member)] != null)
				throw new Exception("The attributes for the given type and Member already exist in the collection");
			
			overrides.Add(GetKey(type,member), attributes);
		}
        public static PersistentVM LoadStateFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentException(Resources.MissingPersistentVMFile, "filePath");
            }

            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            XmlAttributes ignoreAttrib = new XmlAttributes();
            ignoreAttrib.XmlIgnore = true;
            overrides.Add(typeof(DataVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "SourceImageName", ignoreAttrib);

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(PersistentVM), overrides, new Type[] { typeof(NetworkConfigurationSet) }, null, null);

            PersistentVM role = null;
            
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                role = serializer.Deserialize(stream) as PersistentVM;
            }

            return role;
        }
        public static XmlAttributeOverrides Create(Type objectType)
        {
            XmlAttributeOverrides xOver = null;

            if (!table.TryGetValue(objectType, out xOver))
            {
                // Create XmlAttributeOverrides object.
                xOver = new XmlAttributeOverrides();

                /* Create an XmlTypeAttribute and change the name of the XML type. */
                XmlTypeAttribute xType = new XmlTypeAttribute();
                xType.TypeName = objectType.Name;

                // Set the XmlTypeAttribute to the XmlType property.
                XmlAttributes attrs = new XmlAttributes();
                attrs.XmlType = xType;

                /* Add the XmlAttributes to the XmlAttributeOverrides,
                   specifying the member to override. */
                xOver.Add(objectType, attrs);

                table.MergeSafe(objectType, xOver);
            }

            return xOver;
        }
        public static T ParseXML <T>(this string @this) where T : class
        {
            if (string.IsNullOrWhiteSpace(@this))
            {
                return((T)Activator.CreateInstance(typeof(T)));
            }

            if ([email protected]("<?xml version=\"1.0\" encoding=\"utf-16\"?>"))
            {
                @this = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + @this;
            }

            string kUtf8BOM = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetPreamble());

            if (@this.StartsWith(kUtf8BOM))
            {
                @this = @this.Remove(0, kUtf8BOM.Length);
            }
            if (@this.StartsWith("?xm"))
            {
                @this = "<" + @this;
            }

            StringReader  Stream = null;
            XmlTextReader Reader = null;

            try
            {
                System.Xml.Serialization.XmlAttributeOverrides xOver = new System.Xml.Serialization.XmlAttributeOverrides();
                System.Xml.Serialization.XmlAttributes         attrs = new System.Xml.Serialization.XmlAttributes();
                foreach (var Ig in typeof(T).GetProperties().Where(c => !c.PropertyType.IsSerializable || c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.BusinessLogic") || c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.Engine")).Select(c => c.Name))
                {
                    attrs           = new System.Xml.Serialization.XmlAttributes();
                    attrs.XmlIgnore = true;
                    xOver.Add(typeof(T), Ig, attrs);
                }

                XmlSerializer Serializer = new XmlSerializer(typeof(T), xOver);
                Stream = new StringReader(@this);
                Reader = new XmlTextReader(Stream);

                // covert reader to object
                return((T)Serializer.Deserialize(Reader));
            }
            catch (Exception ex)
            {
                return(default(T));
            }
            finally
            {
                if (Stream != null)
                {
                    Stream.Close();
                }
                if (Reader != null)
                {
                    Reader.Close();
                }
            }
        }
Example #9
0
        public static XmlAttributeOverrides GetExportedDefinitionsOverrides(XmlAttributeOverrides DefinitionsOverrides)
        {
            var _container = PluginContainer.GetOvalCompositionContainer();

            var testTypes = _container.GetExports<TestType>().Select(exp => exp.Value.GetType());
            var objectTypes = _container.GetExports<ObjectType>().Select(exp => exp.Value.GetType());
            var stateTypes = _container.GetExports<StateType>().Select(exp => exp.Value.GetType());

            XmlAttributes testAttributes = new XmlAttributes();
            foreach (var testType in testTypes)
            {
                var xmlAttrs = (testType.GetCustomAttributes(typeof(XmlRootAttribute), false) as XmlRootAttribute[]).SingleOrDefault();
                testAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute(xmlAttrs.ElementName, testType) { Namespace = xmlAttrs.Namespace });
            }
            DefinitionsOverrides.Add(typeof(oval_definitions), "tests", testAttributes);
            XmlAttributes objectAttributes = new XmlAttributes();
            foreach (var objectType in objectTypes)
            {
                var xmlAttrs = (objectType.GetCustomAttributes(typeof(XmlRootAttribute), false) as XmlRootAttribute[]).SingleOrDefault();
                objectAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute(xmlAttrs.ElementName, objectType) { Namespace = xmlAttrs.Namespace });
            }
            DefinitionsOverrides.Add(typeof(oval_definitions), "objects", objectAttributes);

            XmlAttributes stateAttributes = new XmlAttributes();
            foreach (var stateType in stateTypes)
            {
                var xmlAttrs = (stateType.GetCustomAttributes(typeof(XmlRootAttribute), false) as XmlRootAttribute[]).SingleOrDefault();
                stateAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute(xmlAttrs.ElementName, stateType) { Namespace = xmlAttrs.Namespace });
            }
            DefinitionsOverrides.Add(typeof(oval_definitions), "states", stateAttributes);

            return DefinitionsOverrides;
        }
        internal override bool ReflectReturn() {
            MessagePart part = new MessagePart();
            part.Name = "Body";
            ReflectionContext.OutputMessage.Parts.Add(part);

            if (typeof(XmlNode).IsAssignableFrom(ReflectionContext.Method.ReturnType)) {
                MimeContentBinding mimeContentBinding = new MimeContentBinding();
                mimeContentBinding.Type = "text/xml";
                mimeContentBinding.Part = part.Name;
                ReflectionContext.OperationBinding.Output.Extensions.Add(mimeContentBinding);
            }
            else {
                MimeXmlBinding mimeXmlBinding = new MimeXmlBinding();
                mimeXmlBinding.Part = part.Name;

                LogicalMethodInfo methodInfo = ReflectionContext.Method;
                XmlAttributes a = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider);
                XmlTypeMapping xmlTypeMapping = ReflectionContext.ReflectionImporter.ImportTypeMapping(methodInfo.ReturnType, a.XmlRoot);
                xmlTypeMapping.SetKey(methodInfo.GetKey() + ":Return");
                ReflectionContext.SchemaExporter.ExportTypeMapping(xmlTypeMapping);
                part.Element = new XmlQualifiedName(xmlTypeMapping.XsdElementName, xmlTypeMapping.Namespace);
                ReflectionContext.OperationBinding.Output.Extensions.Add(mimeXmlBinding);
            }

            return true;
        }
Example #11
0
        public static byte[] getRequestContent(string doctype, string root, Type type, object obj)
        {
            var xattribs = new XmlAttributes();
            var xroot = new XmlRootAttribute(root);
            xattribs.XmlRoot = xroot;
            var xoverrides = new XmlAttributeOverrides();
            //... have to use XmlAttributeOverrides because .NET insists on the object name as root element name otherwise ([XmlRoot(..)] has no effect)
            xoverrides.Add(type, xattribs);

            XmlSerializer serializer = new XmlSerializer(type, xoverrides);
            StringWriter sw = new StringWriter();
            XmlWriterSettings wsettings = new XmlWriterSettings();
            wsettings.OmitXmlDeclaration = false;
            wsettings.Encoding = new UTF8Encoding();
            XmlWriter xw = XmlWriter.Create(sw, wsettings);
            xw.WriteProcessingInstruction("xml", "version='1.0' standalone='no'");
            //... have to write header by hand (OmitXmlDeclaration=false has no effect)
            xw.WriteDocType(root, null, doctype + ".sfrm", null);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            //... trick to avoid printing of xmlns:xsi xmlns:xsd attributes of the root element

            serializer.Serialize(xw, obj, ns);
            return sw.ToArray();
        }
		public void NewXmlAttributes ()
		{
			// seems not different from Type specified ctor().
			XmlAttributes atts = new XmlAttributes ();
			AssertNull (atts.XmlAnyAttribute);
			AssertNotNull (atts.XmlAnyElements);
			AssertEquals (0, atts.XmlAnyElements.Count);
			AssertNull (atts.XmlArray);
			AssertNotNull (atts.XmlArrayItems);
			AssertEquals (0, atts.XmlArrayItems.Count);
			AssertNull (atts.XmlAttribute);
			AssertNull (atts.XmlChoiceIdentifier);
			AssertNotNull (atts.XmlDefaultValue);
			// DBNull??
			AssertEquals (DBNull.Value, atts.XmlDefaultValue);
			AssertNotNull (atts.XmlElements);
			AssertEquals (0, atts.XmlElements.Count);
			AssertNull (atts.XmlEnum);
			AssertNotNull (atts.XmlIgnore);
			AssertEquals (TypeCode.Boolean, atts.XmlIgnore.GetTypeCode ());
			AssertEquals (false, atts.Xmlns);
			AssertNull (atts.XmlRoot);
			AssertNull (atts.XmlText);
			AssertNull (atts.XmlType);
		}
		public void NewXmlAttributes ()
		{
			// seems not different from Type specified ctor().
			XmlAttributes atts = new XmlAttributes ();
			Assert.IsNull (atts.XmlAnyAttribute, "#1");
			Assert.IsNotNull (atts.XmlAnyElements, "#2");
			Assert.AreEqual (0, atts.XmlAnyElements.Count, "#3");
			Assert.IsNull (atts.XmlArray, "#4");
			Assert.IsNotNull (atts.XmlArrayItems, "#5");
			Assert.AreEqual (0, atts.XmlArrayItems.Count, "#6");
			Assert.IsNull (atts.XmlAttribute, "#7");
			Assert.IsNull (atts.XmlChoiceIdentifier, "#8");
			Assert.IsNotNull (atts.XmlDefaultValue, "#9");
			// DBNull??
			Assert.AreEqual (DBNull.Value, atts.XmlDefaultValue, "#10");
			Assert.IsNotNull (atts.XmlElements, "#11");
			Assert.AreEqual (0, atts.XmlElements.Count, "#12");
			Assert.IsNull (atts.XmlEnum, "#13");
			Assert.IsNotNull (atts.XmlIgnore, "#14");
			Assert.AreEqual (TypeCode.Boolean, atts.XmlIgnore.GetTypeCode (), "#15");
			Assert.AreEqual (false, atts.Xmlns, "#16");
			Assert.IsNull (atts.XmlRoot, "#17");
			Assert.IsNull (atts.XmlText, "#18");
			Assert.IsNull (atts.XmlType, "#19");
		}
 internal static object[] GetInitializers(LogicalMethodInfo[] methodInfos)
 {
     if (methodInfos.Length == 0)
     {
         return new object[0];
     }
     WebServiceAttribute attribute = WebServiceReflector.GetAttribute(methodInfos);
     bool serviceDefaultIsEncoded = SoapReflector.ServiceDefaultIsEncoded(WebServiceReflector.GetMostDerivedType(methodInfos));
     XmlReflectionImporter importer = SoapReflector.CreateXmlImporter(attribute.Namespace, serviceDefaultIsEncoded);
     WebMethodReflector.IncludeTypes(methodInfos, importer);
     ArrayList list = new ArrayList();
     bool[] flagArray = new bool[methodInfos.Length];
     for (int i = 0; i < methodInfos.Length; i++)
     {
         LogicalMethodInfo methodInfo = methodInfos[i];
         Type returnType = methodInfo.ReturnType;
         if (IsSupported(returnType) && HttpServerProtocol.AreUrlParametersSupported(methodInfo))
         {
             XmlAttributes attributes = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider);
             XmlTypeMapping mapping = importer.ImportTypeMapping(returnType, attributes.XmlRoot);
             mapping.SetKey(methodInfo.GetKey() + ":Return");
             list.Add(mapping);
             flagArray[i] = true;
         }
     }
     if (list.Count == 0)
     {
         return new object[0];
     }
     XmlMapping[] mappings = (XmlMapping[]) list.ToArray(typeof(XmlMapping));
     Evidence evidenceForType = GetEvidenceForType(methodInfos[0].DeclaringType);
     TraceMethod caller = Tracing.On ? new TraceMethod(typeof(XmlReturn), "GetInitializers", methodInfos) : null;
     if (Tracing.On)
     {
         Tracing.Enter(Tracing.TraceId("TraceCreateSerializer"), caller, new TraceMethod(typeof(XmlSerializer), "FromMappings", new object[] { mappings, evidenceForType }));
     }
     XmlSerializer[] serializerArray = null;
     if (AppDomain.CurrentDomain.IsHomogenous)
     {
         serializerArray = XmlSerializer.FromMappings(mappings);
     }
     else
     {
         serializerArray = XmlSerializer.FromMappings(mappings, evidenceForType);
     }
     if (Tracing.On)
     {
         Tracing.Exit(Tracing.TraceId("TraceCreateSerializer"), caller);
     }
     object[] objArray = new object[methodInfos.Length];
     int num2 = 0;
     for (int j = 0; j < objArray.Length; j++)
     {
         if (flagArray[j])
         {
             objArray[j] = serializerArray[num2++];
         }
     }
     return objArray;
 }
Example #15
0
        //SerialSample4\form1.cs
        private void button1_Click(object sender, System.EventArgs e)
        {
            //create the XmlAttributes boject
              XmlAttributes attrs=new XmlAttributes();
              //add the types of the objects that will be serialized
              attrs.XmlElements.Add(new XmlElementAttribute("Book",typeof(BookProduct)));
              attrs.XmlElements.Add(new XmlElementAttribute("Product",typeof(Product)));
              XmlAttributeOverrides attrOver=new XmlAttributeOverrides();
              //add to the attributes collection
              attrOver.Add(typeof(Inventory),"InventoryItems",attrs);
              //create the Product and Book objects
              Product newProd=new Product();
              BookProduct newBook=new BookProduct();

              newProd.ProductID=100;
              newProd.ProductName="Product Thing";
              newProd.SupplierID=10;

              newBook.ProductID=101;
              newBook.ProductName="How to Use Your New Product Thing";
              newBook.SupplierID=10;
              newBook.ISBN="123456789";

              Product[] addProd={newProd,newBook};

              Inventory inv=new Inventory();
              inv.InventoryItems=addProd;
              TextWriter tr=new StreamWriter("..\\..\\..\\inventory.xml");
              XmlSerializer sr=new XmlSerializer(typeof(Inventory),attrOver);

              sr.Serialize(tr,inv);
              tr.Close();
            MessageBox.Show("Serialized!");
        }
 internal override bool ReflectReturn()
 {
     MessagePart messagePart = new MessagePart {
         Name = "Body"
     };
     base.ReflectionContext.OutputMessage.Parts.Add(messagePart);
     if (typeof(XmlNode).IsAssignableFrom(base.ReflectionContext.Method.ReturnType))
     {
         MimeContentBinding extension = new MimeContentBinding {
             Type = "text/xml",
             Part = messagePart.Name
         };
         base.ReflectionContext.OperationBinding.Output.Extensions.Add(extension);
     }
     else
     {
         MimeXmlBinding binding2 = new MimeXmlBinding {
             Part = messagePart.Name
         };
         LogicalMethodInfo method = base.ReflectionContext.Method;
         XmlAttributes attributes = new XmlAttributes(method.ReturnTypeCustomAttributeProvider);
         XmlTypeMapping xmlTypeMapping = base.ReflectionContext.ReflectionImporter.ImportTypeMapping(method.ReturnType, attributes.XmlRoot);
         xmlTypeMapping.SetKey(method.GetKey() + ":Return");
         base.ReflectionContext.SchemaExporter.ExportTypeMapping(xmlTypeMapping);
         messagePart.Element = new XmlQualifiedName(xmlTypeMapping.XsdElementName, xmlTypeMapping.Namespace);
         base.ReflectionContext.OperationBinding.Output.Extensions.Add(binding2);
     }
     return true;
 }
		public void SetUp()
		{
			ov1 = new XmlAttributeOverrides();
			ov2 = new XmlAttributeOverrides();

			atts1 = new XmlAttributes();
			atts2 = new XmlAttributes();
		}
		public void SameObjectWithRootAttribute()
		{
			XmlAttributeOverrides ov = new XmlAttributeOverrides();
			XmlAttributes atts = new XmlAttributes();
			atts.XmlRoot = new XmlRootAttribute("myRoot");
			ov.Add(typeof(SerializeMe), atts);

			ThumbprintHelpers.SameThumbprint(ov, ov);
		}
		public TypeTableEntry (Hashtable memberTable,
			XmlAttributes xmlAttributes,
			ArrayList elementMembers,
			ArrayList attributeMembers)
		{
			this.memberTable = memberTable;
			this.xmlAttributes = xmlAttributes;
			this.elementMembers = elementMembers;
			this.attributeMembers = attributeMembers;
		}
		public void SameMemberName()
		{
			atts1 = new XmlAttributes(new ChoiceIdentifierAttributeProvider("myname"));
			atts2 = new XmlAttributes(new ChoiceIdentifierAttributeProvider("myname"));

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

			ThumbprintHelpers.SameThumbprint(ov1, ov2);
		}
        public static ModuleConfiguration Load(string fileName, List<Type> displayList, List<Type> deviceList,
                                               List<Type> sourceList, List<Type> mappingList)
        {
            string configurationSchemaFile = Path.ChangeExtension(fileName, "xsd");
            try
            {
                XmlAttributeOverrides ovr = new XmlAttributeOverrides();

                XmlAttributes attrsDevice = new XmlAttributes();
                XmlAttributes attrsSource = new XmlAttributes();
                XmlAttributes attrsDisplay = new XmlAttributes();
                XmlAttributes attrsMapping = new XmlAttributes();

                attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(typeof (Mapping)));

                foreach (Type type in sourceList)
                    attrsSource.XmlArrayItems.Add(new XmlArrayItemAttribute(type));
                foreach (Type type in deviceList)
                    attrsDevice.XmlArrayItems.Add(new XmlArrayItemAttribute(type));
                foreach (Type type in displayList)
                    attrsDisplay.XmlArrayItems.Add(new XmlArrayItemAttribute(type));
                foreach (Type type in mappingList)
                    attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(type));

                ovr.Add(typeof (ModuleConfiguration), "DeviceList", attrsDevice);
                ovr.Add(typeof (ModuleConfiguration), "SourceList", attrsSource);
                ovr.Add(typeof (ModuleConfiguration), "DisplayList", attrsDisplay);
                ovr.Add(typeof (DisplayType), "MappingList", attrsMapping);

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas.Add("urn:configuration-schema", configurationSchemaFile);
                // Проводим валидацию, отдельно от десереализации, потому-что если вместе то валится
                using (XmlReader reader = XmlReader.Create(fileName, settings))
                    while (reader.Read())
                    {
                    }
                // Проводим десереализации без валидации, потому-что если вместе то валится
                XmlSerializer serializer = new XmlSerializer(typeof (ModuleConfiguration), ovr);
                using (XmlReader reader = XmlReader.Create(fileName))
                    return (ModuleConfiguration) serializer.Deserialize(reader);
            }
            catch (FileNotFoundException ex)
            {
                throw new ModuleConfigurationException(ex.FileName);
            }
            catch (XmlSchemaException ex)
            {
                throw new ModuleConfigurationException(new Uri(ex.SourceUri).AbsolutePath, ex);    //configurationSchemaFile
            }
            catch (XmlException ex)
            {
                throw new ModuleConfigurationException(new Uri(ex.SourceUri).AbsolutePath, ex);
            }
        }
Example #22
0
 /// <include file='doc\XmlAttributeOverrides.uex' path='docs/doc[@for="XmlAttributeOverrides.Add1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Add(Type type, string member, XmlAttributes attributes) {
     Hashtable members = (Hashtable)types[type];
     if (members == null) {
         members = new Hashtable();
         types.Add(type, members);
     }
     else if (members[member] != null) {
         throw new InvalidOperationException(Res.GetString(Res.XmlAttributeSetAgain, type.FullName, member));
     }
     members.Add(member, attributes);
 }
Example #23
0
        public void WriteTo(TextWriter tw)
        {
            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            XmlAttributes attrs = new XmlAttributes {XmlIgnore = true};

            overrides.Add(Object.GetType(), "Id", attributes: attrs);

            XmlSerializer xs = new XmlSerializer(Object.GetType(), overrides);

            xs.Serialize(tw, Object);
        }
Example #24
0
        private void InitializeSerializer()
        {
            XmlAttributes attrs = new XmlAttributes();
            XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
            attrOverrides.Add(typeof(string), "File", attrs);
            attrOverrides.Add(typeof(List<string>), "Columns", attrs);
            attrOverrides.Add(typeof(List<List<string>>), "Rows", attrs);

            m_compositionXmlSerializer = new XmlSerializer(typeof(List<List<string>>), attrOverrides);

            m_mapSerializer = new TmxMapSerializer.Serializer.TmxMapSerializer();
        }
        public static string BuildXml <T>(this T BusinessObject) where T : class
        {
            MemoryStream Stream = null;
            TextWriter   Writer = null;

            try
            {
                System.Xml.Serialization.XmlAttributeOverrides xOver = new System.Xml.Serialization.XmlAttributeOverrides();
                System.Xml.Serialization.XmlAttributes         attrs = new System.Xml.Serialization.XmlAttributes();

                foreach (var Ig in typeof(T).GetProperties().Where(c =>
                                                                   !c.PropertyType.IsSerializable ||
                                                                   c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.BusinessLogic")).Select(c => c.Name))
                {
                    attrs           = new System.Xml.Serialization.XmlAttributes();
                    attrs.XmlIgnore = true;
                    xOver.Add(typeof(T), Ig, attrs);
                }

                Stream = new MemoryStream();
                Writer = new StreamWriter(Stream, Encoding.Unicode);

                XmlSerializer Serializer = new XmlSerializer(typeof(T), xOver);
                Serializer.Serialize(Writer, BusinessObject);

                int    Count    = (int)Stream.Length;
                byte[] BytesArr = new byte[Count];

                Stream.Seek(0, SeekOrigin.Begin);
                Stream.Read(BytesArr, 0, Count);

                UnicodeEncoding utf = new UnicodeEncoding();
                return(System.Web.HttpUtility.HtmlDecode(utf.GetString(BytesArr).Trim()));

                //return utf.GetString(BytesArr).Trim();
            }
            catch (Exception exc)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
                return(string.Empty);
            }
            finally
            {
                if (Stream != null)
                {
                    Stream.Close();
                }
                if (Writer != null)
                {
                    Writer.Close();
                }
            }
        }
Example #26
0
		public void SaveToFile(string path)
		{
			XmlSerializer serializer = new XmlSerializer(typeof (OptionsList));
			XmlAttributeOverrides overrides = new XmlAttributeOverrides();
			XmlAttributes ignoreAttr = new XmlAttributes();
			ignoreAttr.XmlIgnore = true;
			overrides.Add(typeof (Annotatable), "IsStarred", ignoreAttr);

			using (StreamWriter writer = File.CreateText(path))
			{
				serializer.Serialize(writer, this);
				writer.Close();
			}
		}
        internal XmlAttributeOverrides GetSerializerOverrides()
        {
            var overrides = new XmlAttributeOverrides();
            var attributes = new XmlAttributes();

            foreach (XmlElementAttribute attribute in SerializerAttributes)
            {
                attributes.XmlElements.Add(attribute);
            }

            overrides.Add(typeof(ItemData), "Typed", attributes);

            return overrides;
        }
		public void TwoObjectsWithSameRootAttributeDifferentTypes()
		{
			XmlAttributeOverrides ov1 = new XmlAttributeOverrides();
			XmlAttributeOverrides ov2 = new XmlAttributeOverrides();
			XmlAttributes atts1 = new XmlAttributes();
			atts1.XmlRoot = new XmlRootAttribute("myRoot");
			ov1.Add(typeof(SerializeMe), atts1);

			XmlAttributes atts2 = new XmlAttributes();
			atts2.XmlRoot = new XmlRootAttribute("myRoot");
			ov2.Add(typeof(SerializeMeToo), atts2);

			ThumbprintHelpers.DifferentThumbprint(ov1, ov2);
		}
 public static void AddArrayItemMemberMapping(XmlAttributes at, Type type, string elementName, bool isNullable, string elementNamespace, bool isQualified, int nestingLevel)
 {
     XmlArrayItemAttribute arrayItem = AddArrayItemMemberMappingInternal(type, elementName, isNullable);
     if ( isQualified )
     {
         arrayItem.Form = XmlSchemaForm.Qualified;
     }
     else
     {
         arrayItem.Form = XmlSchemaForm.Unqualified;
     }
     arrayItem.NestingLevel = nestingLevel;
     at.XmlArrayItems.Add(arrayItem);
 }
        internal static object[] GetInitializers(LogicalMethodInfo[] methodInfos) {
            if (methodInfos.Length == 0) return new object[0];
            WebServiceAttribute serviceAttribute = WebServiceReflector.GetAttribute(methodInfos);
            bool serviceDefaultIsEncoded = SoapReflector.ServiceDefaultIsEncoded(WebServiceReflector.GetMostDerivedType(methodInfos));
            XmlReflectionImporter importer = SoapReflector.CreateXmlImporter(serviceAttribute.Namespace, serviceDefaultIsEncoded);
            WebMethodReflector.IncludeTypes(methodInfos, importer);
            ArrayList mappings = new ArrayList();
            bool[] supported = new bool[methodInfos.Length];
            for (int i = 0; i < methodInfos.Length; i++) {
                LogicalMethodInfo methodInfo = methodInfos[i];
                Type type = methodInfo.ReturnType;
                if (IsSupported(type) && HttpServerProtocol.AreUrlParametersSupported(methodInfo)) {
                    XmlAttributes a = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider);
                    XmlTypeMapping mapping = importer.ImportTypeMapping(type, a.XmlRoot);
                    mapping.SetKey(methodInfo.GetKey() + ":Return");
                    mappings.Add(mapping);
                    supported[i] = true;
                }
            }
            if (mappings.Count == 0)
                return new object[0];

            XmlMapping[] xmlMappings = (XmlMapping[])mappings.ToArray(typeof(XmlMapping));
            Evidence evidence = GetEvidenceForType(methodInfos[0].DeclaringType);

            TraceMethod caller = Tracing.On ? new TraceMethod(typeof(XmlReturn), "GetInitializers", methodInfos) : null;
            if (Tracing.On) Tracing.Enter(Tracing.TraceId(Res.TraceCreateSerializer), caller, new TraceMethod(typeof(XmlSerializer), "FromMappings", xmlMappings, evidence));
            XmlSerializer[] serializers = null;
            if (AppDomain.CurrentDomain.IsHomogenous)
            {
                serializers = XmlSerializer.FromMappings(xmlMappings);
            }
            else
            {
#pragma warning disable 618 // If we're in a non-homogenous domain, legacy CAS mode is enabled, so passing through evidence will not fail
                serializers = XmlSerializer.FromMappings(xmlMappings, evidence);
#pragma warning restore 618
            }

            if (Tracing.On) Tracing.Exit(Tracing.TraceId(Res.TraceCreateSerializer), caller);

            object[] initializers = new object[methodInfos.Length];
            int count = 0;
            for (int i = 0; i < initializers.Length; i++) {
                if (supported[i]) {
                    initializers[i] = serializers[count++];
                }
            }
            return initializers;
        }
 public void Add(Type type, string member, XmlAttributes attributes)
 {
     Hashtable hashtable = (Hashtable) this.types[type];
     if (hashtable == null)
     {
         hashtable = new Hashtable();
         this.types.Add(type, hashtable);
     }
     else if (hashtable[member] != null)
     {
         throw new InvalidOperationException(Res.GetString("XmlAttributeSetAgain", new object[] { type.FullName, member }));
     }
     hashtable.Add(member, attributes);
 }
 /// <include file='doc\XmlAttributeOverrides.uex' path='docs/doc[@for="XmlAttributeOverrides.Add1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Add(Type type, string member, XmlAttributes attributes)
 {
     Dictionary<string, XmlAttributes> members;
     if (!_types.TryGetValue(type, out members))
     {
         members = new Dictionary<string, XmlAttributes>();
         _types.Add(type, members);
     }
     else if (members.ContainsKey(member))
     {
         throw new InvalidOperationException(SR.Format(SR.XmlAttributeSetAgain, type.FullName, member));
     }
     members.Add(member, attributes);
 }
Example #33
0
        private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags)
        {
            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                MethodInfo enumerator = type.GetMethod("GetEnumerator", new Type[0]);

                if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
                {
                    // try generic implementation
                    enumerator = null;
                    foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
                    {
                        enumerator = member as MethodInfo;
                        if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
                        {
                            // use the first one we find
                            flags |= TypeFlags.GenericInterface;
                            break;
                        }
                        else
                        {
                            enumerator = null;
                        }
                    }
                    if (enumerator == null)
                    {
                        // and finally private interface implementation
                        flags     |= TypeFlags.UsePrivateImplementation;
                        enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, new Type[0]);
                    }
                }
                if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
                {
                    return(null);
                }
                XmlAttributes methodAttrs = new XmlAttributes(enumerator);
                if (methodAttrs.XmlIgnore)
                {
                    return(null);
                }

                PropertyInfo p           = enumerator.ReturnType.GetProperty("Current");
                Type         currentType = (p == null ? typeof(object) : p.PropertyType);

                MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType });

                if (addMethod == null && currentType != typeof(object))
                {
                    currentType = typeof(object);
                    addMethod   = type.GetMethod("Add", new Type[] { currentType });
                }
                if (addMethod == null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable"));
                }
                return(currentType);
            }
            else
            {
                return(null);
            }
        }
Example #34
0
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Add(Type type, XmlAttributes attributes)
 {
     Add(type, string.Empty, attributes);
 }
Example #35
0
 internal static string GenerateKey(Type type, XmlRootAttribute?root, string?ns)
 {
     root ??= (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute));
     return($"{type.FullName}:{(root == null ? string.Empty : root.GetKey())}:{ns ?? string.Empty}");
 }
 public void Add(System.Type type, System.Xml.Serialization.XmlAttributes attributes)
 {
 }