Summary description for XmlSerializerNamespaces.
        /// <summary>
        /// Metodo para serializar una Lista de objetos en un XML simple
        /// </summary>
        /// <param name="thelist"> la lista de tipo List<T> </param>
        /// <returns></returns>
        public static string List2XML(IList thelist)
        {
            string xml = "";

            try
            {


                XmlSerializer xmlSer = new XmlSerializer(thelist.GetType());
                StringWriterWithEncoding sWriter = new StringWriterWithEncoding(Encoding.UTF8);

                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                xsn.Add(String.Empty, "");

                xmlSer.Serialize(sWriter, thelist, xsn);

                xml = sWriter.ToString();

              



            }
            catch (Exception e)
            {
               
            }

            return xml;
        }
예제 #2
0
 public bool Save(MySettings settings)
 {
     StreamWriter sw = null;
     try
     {
         //now global: XmlSerializer xs = new XmlSerializer(typeof(MySettings));
         //omit xmlns:xsi from xml output
         //Create our own namespaces for the output
         XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
         //Add an empty namespace and empty value
         ns.Add("", "");
         sw = new StreamWriter(settingsFile);
         xs.Serialize(sw, settings, ns);
         return true;
     }
     catch (Exception ex)
     {
         utils.helpers.addExceptionLog(ex.Message);
         return false;
     }
     finally
     {
         if (sw != null)
             sw.Close();
     }
 }
예제 #3
0
        public async Task<HttpResponseMessage> Post() {
            TextMessage recievedMessage;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(TextMessage));
            
            Stream stream = await Request.Content.ReadAsStreamAsync();
            using (var reader = new StreamReader(stream)) {
                
                recievedMessage = (TextMessage)xmlSerializer.Deserialize(reader);
            }
            
            TextMessage sendingMessage = new TextMessage() { 
                ToUserName = recievedMessage.FromUserName,
                FromUserName = recievedMessage.ToUserName,
                CreateTime = ConvertToUnixTimestamp(DateTime.Now).ToString(),
                Content = recievedMessage.Content
            };

            Trace.TraceInformation(Request.Headers.Accept.ToString());

            string messageStr = string.Empty;
            using (StringWriter textWriter = new StringWriter()) {
                var xns = new XmlSerializerNamespaces();
                xns.Add(string.Empty, string.Empty);
                xmlSerializer.Serialize(textWriter, sendingMessage, xns);
                messageStr = textWriter.ToString();
            }

            return new HttpResponseMessage() {
                Content = new StringContent(
                    messageStr,
                    Encoding.UTF8,
                    "text/html"
                )
            };
        }
예제 #4
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());
        }
예제 #5
0
        static XmlConfigService()
        {
            _xmlSerializer = new XmlSerializer(typeof(JobSchedulingData));

            _xmlSerializerNamespaces = new XmlSerializerNamespaces();
            _xmlSerializerNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        }
예제 #6
0
        public void ExportDefinition(Project project)
        {
            TextWriter resultsWriter = new StringWriter();
            XmlTextWriter xslResultsWriter = new XmlTextWriter(resultsWriter);
            MemoryStream outStrm = new MemoryStream();

            XmlSerializer xs = new XmlSerializer(typeof(Project));
            TextWriter stringWriter = new StringWriter();
            XmlTextWriter xtr = new XmlTextWriter(stringWriter);

            string xmlnamespace = _Settings.XmlNameSpace;
            XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
            xns.Add("tt", xmlnamespace);
            try
            {
                //xs.Serialize(xtr, model, xns);
                xs.Serialize(outStrm, project, xns);
            }
            catch (Exception ee)
            {
                string m = ee.Message;
            }
            outStrm.Position = 0;

            FileStream fs = new FileStream(Settings.FileName, FileMode.OpenOrCreate, FileAccess.Write);
            outStrm.WriteTo(fs);
            fs.Flush();
            fs.Close();
            //string str = stringWriter.ToString();
            outStrm.Position = 0;
        }
 public static void SerializeToFile(object obj, string file, FileMode fileMode, XmlSerializerNamespaces namespaces, bool omitXmlDeclaration)
 {
     using (FileStream fileStream = new FileStream(file, fileMode))
     {
         SerializeToStream(obj, fileStream, namespaces, omitXmlDeclaration);
     }
 }
예제 #8
0
 static XmlSerializerAdapter()
 {
     settings = new XmlWriterSettings();
     settings.OmitXmlDeclaration = true;
     ns = new XmlSerializerNamespaces();
     ns.Add("", "");
 }
예제 #9
0
 /// <summary>
 /// Сериализация Базы знаний в xml.
 /// </summary>
 /// <param name="frames"></param>
 /// <returns></returns>
 public bool SaveXml(GroopFrame frames)
 {
     bool result = false;
     using (StreamWriter writer =
         new StreamWriter("frame.xml"))
     {
         try
         {
             XmlSerializerNamespaces ns =
                 new XmlSerializerNamespaces();
             ns.Add("", "");
             XmlSerializer serializer =
                 new XmlSerializer(frames.GetType());
             serializer.Serialize(writer, frames, ns);
             result = true;
         }
         catch (Exception e)
         {
             // Логирование
         }
         finally
         {
             writer.Close();
         }
     }
     return result;
 }
예제 #10
0
        public void ForTypesWithoutInterfacesCustomSerializerSerializesTheSameAsDefaultSerializer(
            object instance,
            string defaultNamespace,
            Type[] extraTypes,
            string rootElementName,
            Encoding encoding,
            Formatting formatting,
            XmlSerializerNamespaces namespaces)
        {
            var defaultSerializer =
                (IXmlSerializer)Activator.CreateInstance(
                    typeof(DefaultSerializer<>).MakeGenericType(instance.GetType()),
                    defaultNamespace,
                    extraTypes,
                    rootElementName);
            var customSerializer =
                (IXmlSerializer)Activator.CreateInstance(
                    typeof(CustomSerializer<>).MakeGenericType(instance.GetType()),
                    defaultNamespace,
                    extraTypes,
                    rootElementName);

            var defaultXml = defaultSerializer.SerializeObject(instance, namespaces, encoding, formatting);
            var customXml = customSerializer.SerializeObject(instance, namespaces, encoding, formatting);

            Console.WriteLine("Default XML:");
            Console.WriteLine(defaultXml);
            Console.WriteLine();
            Console.WriteLine("Custom XML:");
            Console.WriteLine(customXml);

            Assert.That(customXml, Is.EqualTo(defaultXml));
        }
 public XmlSerializationOptions(
     XmlSerializerNamespaces namespaces = null,
     Encoding encoding = null,
     bool shouldEncryptRootObject = false,
     string defaultNamespace = null,
     bool shouldIndent = false,
     string rootElementName = null,
     bool shouldAlwaysEmitTypes = false,
     bool shouldRedact = true,
     bool shouldEncrypt = true,
     bool treatEmptyElementAsString = false,
     bool emitNil = false,
     IEncryptionMechanism encryptionMechanism = null,
     object encryptKey = null,
     bool ShouldIgnoreCaseForEnum = false)
 {
     _namespaces = namespaces ?? new XmlSerializerNamespaces();
     _encoding = encoding ?? Encoding.UTF8;
     _shouldEncryptRootObject = shouldEncryptRootObject;
     _defaultNamespace = defaultNamespace;
     _shouldIndent = shouldIndent;
     _rootElementName = rootElementName;
     _shouldAlwaysEmitTypes = shouldAlwaysEmitTypes;
     _shouldRedact = shouldRedact;
     _shouldEncrypt = shouldEncrypt;
     _extraTypes = null;
     _treatEmptyElementAsString = treatEmptyElementAsString;
     _emitNil = emitNil;
     _encryptionMechanism = encryptionMechanism;
     _encryptKey = encryptKey;
     _shouldIgnoreCaseForEnum = ShouldIgnoreCaseForEnum;
 }
예제 #12
0
        public void Write(Stream outputStream, object artifact)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new XmlSerializer(artifact.GetType(), "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                ns.Add("ds", "http://schemas.allscripts.com/cds/evaluation");
                ns.Add("am", "http://schemas.allscripts.com/mom");
                serializer.Serialize(stream, artifact, ns);

                // This seems like a bug with the serializer to me, but the outer-most instance of
                // Composite expression within the artifact is serialized with the prefix ds, instead
                // of am, even though the CompositeAssertion class has the XmlNamespaceAttribute with
                // allscripts.com/mom as given above. So we serialize the output to a temporary stream,
                // read it into a string, replace the offending instance with the correct value, and
                // then write the output stream with that string.
                stream.Position = 0;
                using (var sr = new StreamReader(stream))
                {
                    var result = sr.ReadToEnd();

                    using (var sw = new StreamWriter(outputStream))
                    {
                        sw.Write(result.Replace("ds:CompositeAssertion", "am:CompositeAssertion"));
                    }
                }
            }
        }
        ///<summary>
        /// Method to convert a custom Object to XML string
        /// </summary>
        /// <param name="pObject">Object that is to be serialized to XML</param>
        /// <param name="objectType"></param>
        /// <returns>XML string</returns>
        public static String SerializeObject(Object pObject, Type objectType)
        {
            try
            {
                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                settings.Indent = true;
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);

                XmlSerializer xs = new XmlSerializer(objectType);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObject, namespaces);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());

                return XmlizedString;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public override int Run(string[] args)
        {
            string schemaFileName = args[0];
            string outschemaFileName = args[1];

            XmlTextReader xr = new XmlTextReader(schemaFileName);
            SchemaInfo schemaInfo = SchemaManager.ReadAndValidateSchema(xr, Path.GetDirectoryName(schemaFileName));
            schemaInfo.Includes.Clear();
            schemaInfo.Classes.Sort(CompareNames);
            schemaInfo.Relations.Sort(CompareNames);

            XmlSerializer ser = new XmlSerializer(typeof(SchemaInfo));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", SchemaInfo.XmlNamespace);

            using (FileStream fs = File.Create(outschemaFileName))
            {
                try
                {
                    ser.Serialize(fs, schemaInfo, ns);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }

            return 0;
        }
예제 #15
0
        public static String createSerializedXmlStringFromObject(Object oObjectToProcess , Type[] extraTypes)
        {
            if (oObjectToProcess == null)
                DI.log.error("in createSerializedXmlStringFromObject: oObjectToProcess == null");
            else
            {
                try
                {
                    /*// handle cases file names are bigger than 220
                    if (sTargetFile.Length > 220)
                    {
                        sTargetFile = sTargetFile.Substring(0, 200) + ".xml";
                        DI.log.error("sTargetFile.Length was > 200, so renamig it to: {0}", sTargetFile);
                    }*/
                    var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                    xnsXmlSerializerNamespaces.Add("", "");
                    var xsXmlSerializer = (extraTypes != null)
                                              ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                              : new XmlSerializer(oObjectToProcess.GetType());
                    var memoryStream = new MemoryStream();
                    xsXmlSerializer.Serialize(memoryStream, oObjectToProcess, xnsXmlSerializerNamespaces);

                    return Encoding.ASCII.GetString(memoryStream.ToArray());
                }
                catch (Exception ex)
                {
                    DI.log.ex(ex,"In createSerializedXmlStringFromObject");
                }
            }
            return "";
        }
예제 #16
0
        public static PackagePart CreateAppManifest(this Package package, Guid productId, Guid identifier, string title, string launchUrl) {
            AppManifest o = new AppManifest() {
                Name = Guid.NewGuid().ToString(),
                ProductID = productId,
                Version = "1.0.0.0",
                SharePointMinVersion = "15.0.0.0",
                Properties = new AppManifest.AppProperties() {
                    Title = title,
                    LaunchUrl = launchUrl
                },
                Principal = new AppManifest.AppPrincipal {
                    RemoteWebApplication = new AppManifest.RemoteWebApplication {
                        ClientId = identifier
                    }
                }
            };

            Uri partUri = new Uri("/AppManifest.xml", UriKind.Relative);
            string contentType = "text/xml";
            PackagePart part = package.CreatePart(partUri, contentType);
            using (Stream stream = part.GetStream(FileMode.Create, FileAccess.Write))
            using (XmlWriter writer = XmlTextWriter.Create(stream)) {
                XmlSerializer serializer = new XmlSerializer(typeof(AppManifest));
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "http://schemas.microsoft.com/sharepoint/2012/app/manifest");
                serializer.Serialize(writer, o, namespaces);
            }
            return part;
        }
예제 #17
0
        public static void SaveDelta(Delta delta, string file)
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");

            var serializer = new XmlSerializer(typeof(Delta));
            
            var list = new List<ImportObject>();
            foreach (var obj in delta.Objects.Where(x => x.NeedsInclude()))
            {
                var newObj = new ImportObject();
                newObj.SourceObjectIdentifier = obj.SourceObjectIdentifier;
                newObj.TargetObjectIdentifier = obj.TargetObjectIdentifier;
                newObj.ObjectType = obj.ObjectType;
                newObj.State = obj.State;
                newObj.Changes = obj.Changes != null ? obj.Changes.Where(x => x.IsIncluded).ToArray() : null;
                newObj.AnchorPairs = obj.AnchorPairs;
                list.Add(newObj);
            }

            var newDelta = new Delta();
            newDelta.Objects = list.ToArray();

			var settings = new XmlWriterSettings();
			settings.OmitXmlDeclaration = false;
			settings.Indent = true;
            using (var w = XmlWriter.Create(file, settings))
                serializer.Serialize(w, newDelta, ns);
        }
예제 #18
0
 /// <summary>
 /// Kontruktor klasy
 /// </summary>
 public komunikacja()
 {
     names = new XmlSerializerNamespaces();
     names.Add("", "");
     log = "";
     haslo = "";
 }
    /// <summary>
    /// This method converts any object into xml format.
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
        public static string SerializeData(object data)
        {
            //StringBuilder sbData = new StringBuilder();
            //StringWriter swWriter;
            //XmlSerializer employeeSerializer = new XmlSerializer(typeof(object));

            //swWriter = new StringWriter(sbData);
            //employeeSerializer.Serialize(swWriter, data);
            //return sbData.ToString();

            if (data == null)
            {
                return string.Empty;
            }
            try
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, String.Empty);
                var xmlserializer = new XmlSerializer(data.GetType(),String.Empty);
                var stringWriter = new StringWriter();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                using (var writer = XmlWriter.Create(stringWriter,settings))
                {
                    xmlserializer.Serialize(writer, data,ns);
                    return stringWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }
예제 #20
0
        // This actually calls the service to perform the tax calculation, and returns the calculation result.
        public async Task<GetTaxResult> GetTax(GetTaxRequest req)
        {
            // Convert the request to XML
            XmlSerializerNamespaces namesp = new XmlSerializerNamespaces();
            namesp.Add(string.Empty, string.Empty);
            XmlWriterSettings settings = new XmlWriterSettings {OmitXmlDeclaration = true};
            XmlSerializer x = new XmlSerializer(req.GetType());
            StringBuilder sb = new StringBuilder();
            x.Serialize(XmlWriter.Create(sb, settings), req, namesp);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sb.ToString());

            // Call the service
            Uri address = new Uri(_svcUrl + "tax/get");
            var request = HttpHelper.CreateRequest(address, _accountNumber, _license);
            request.Method = "POST";
            request.ContentType = "text/xml";
            //request.ContentLength = sb.Length;
            Stream newStream = await request.GetRequestStreamAsync();
            newStream.Write(Encoding.ASCII.GetBytes(sb.ToString()), 0, sb.Length);
            GetTaxResult result = new GetTaxResult();
            try
            {
                WebResponse response = await request.GetResponseAsync();
                XmlSerializer r = new XmlSerializer(result.GetType());
                result = (GetTaxResult) r.Deserialize(response.GetResponseStream());
            }
            catch (WebException ex)
            {
                XmlSerializer r = new XmlSerializer(result.GetType());
                result = (GetTaxResult) r.Deserialize(((HttpWebResponse) ex.Response).GetResponseStream());
            }

            return result;
        }
예제 #21
0
        // Similar code exist in O2.DotNetWrappers.DotNet.Serialize
        public static bool createSerializedXmlFileFromObject(Object oObjectToProcess, String sTargetFile, Type[] extraTypes)
        {
            FileStream fileStream = null;
            try
            {
                var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                xnsXmlSerializerNamespaces.Add("", "");
                var xsXmlSerializer = (extraTypes != null)
                                          ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                          : new XmlSerializer(oObjectToProcess.GetType());

                fileStream = new FileStream(sTargetFile, FileMode.Create);

                xsXmlSerializer.Serialize(fileStream, oObjectToProcess, xnsXmlSerializerNamespaces);
                //fileStream.Close();

                return true;
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "In createSerializedXmlStringFromObject");
                return false;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

        }
예제 #22
0
        public string Cancelar()
        {
            try
            {
                XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
                nameSpaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                nameSpaces.Add("tipos", "http://*****:*****@"D:\Ret_CANC_LOTE_2805131157.xml";

                RetornoCancelamentoNFSe objretorno = SerializeClassToXml.DeserializeClasse<RetornoCancelamentoNFSe>(sPathRetConsultaCanc);

                string sMessageRetorno = TrataRetornoCancelamento(objretorno);
                return sMessageRetorno;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #23
0
파일: GeoRSS.cs 프로젝트: halljames/GeoRSS
        public XmlDocument ToXML()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                // xmlns:georss="http://www.georss.org/georss"
                // xmlns:gml="http://www.opengis.net/gml"
                //xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
                //xmlns:kml="http://www.opengis.net/kml/2.2"
                //xmlns:dc="http://purl.org/dc/elements/1.1/"
                var ns = new XmlSerializerNamespaces();
                ns.Add("georss", "http://www.georss.org/georss");
                ns.Add("gml", "http://www.opengis.net/gml");
                ns.Add("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#");
                ns.Add("kml", "http://www.opengis.net/kml/2.2");
                ns.Add("dc", "http://purl.org/dc/elements/1.1/");

                XmlSerializer s = new XmlSerializer(this.GetType());
                Console.WriteLine("Testing for type: {0}", this.GetType());
                s.Serialize(XmlWriter.Create(stream), this, ns);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                //object o = s.Deserialize(XmlReader.Create(stream));
                //Console.WriteLine("  Deserialized type: {0}", o.GetType());
                XmlDocument xml = new XmlDocument();
                xml.Load(stream);
                Console.Write(xml.InnerXml);
                return xml;
            }

            //var serializer = new XmlSerializer(this.GetType());
            //serializer.Serialize(new StreamWriter("test.xml"), this);
        }
예제 #24
0
 public RegistryObjectList()
 {
     xmlns = new XmlSerializerNamespaces(new []
     {
         new XmlQualifiedName("rim", Namespaces.Rim)
     });
 }
예제 #25
0
        public XmlElement SerializeGovTalkMessageGovTalkDetails(hmrcclasses.GovTalkMessageGovTalkDetails gtDetails)
        {
            // copy of IRenvelope serializer

            using (MemoryStream memStream = new MemoryStream())
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, "http://www.govtalk.gov.uk/CM/envelope");

                var knownTypes = new Type[] { typeof(hmrcclasses.GovTalkMessageGovTalkDetails), typeof(hmrcclasses.GovTalkMessageGovTalkDetailsKey) };

                XmlSerializer serializer =
                    new XmlSerializer(typeof(hmrcclasses.GovTalkMessageGovTalkDetails), knownTypes);

                XmlTextWriter tw = new XmlTextWriter(memStream, UTF8Encoding.UTF8);

                XmlDocument doc = new XmlDocument();
                tw.Formatting = Formatting.Indented;
                tw.IndentChar = ' ';
                serializer.Serialize(tw, gtDetails, ns);
                memStream.Seek(0, SeekOrigin.Begin);
                doc.Load(memStream);
                XmlElement returnVal = doc.DocumentElement;

                return returnVal;
            }
        }
예제 #26
0
        public void TestMethod1()
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(TestSection));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            var mySection = new TestSection();
            mySection.myDecimal = 2.15M;
            mySection.myInt = 215;
            mySection.myString = "215";
            using (StringWriter sww = new StringWriter())
            using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings() { OmitXmlDeclaration = true }))
            {
                xsSubmit.Serialize(writer, mySection, ns);
                var xml = sww.ToString();
            }

            // Save Xml            
            string configutaionFilePath = Environment.CurrentDirectory;
            var Xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                        <configuration>
                              <configSections>
                              </configSections>
                        </configuration>
                        ";

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(Xml);
            xdoc.Save(configutaionFilePath + @"\config.xml");
        }
예제 #27
0
        //private readonly Utilities sUtilities = Singleton<Utilities>.Instance;
        /// <summary>
        /// Serializes the current instance and returns the result as a <see cref="string"/>
        /// <para>Should be used with XML serialization only.</para>
        /// </summary>
        /// <returns>The serialized instance.</returns>
        public string Serialize()
        {
            //if(!sPlatform.IsLinux)
            //	Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            string data;

            try
            {
                using(var ms = new MemoryStream())
                {
                    var serializer = new XmlSerializer(GetType());
                    var nss = new XmlSerializerNamespaces();
                    nss.Add(string.Empty, string.Empty);
                    serializer.Serialize(ms, this, nss);

                    using(var reader = new StreamReader(ms))
                    {
                        data = reader.ReadToEnd();
                    }
                }
            }
            catch(InvalidOperationException x)
            {
                throw new WolframException(sLConsole.GetString("Error during serialization"), x);
            }

            if(string.IsNullOrEmpty(data))
                throw new WolframException(string.Format(sLConsole.GetString("Error while serializing instance! Type: {0}"), GetType().FullName));

            return data;
        }
예제 #28
0
 public static void Serialize(Stream stream, object value) {
     var ns = new XmlSerializerNamespaces();
     ns.Add("", "");
     var serializer = new XmlSerializer(value.GetType(), "");
     using (var xml = XmlWriter.Create(stream, XmlWriterSettings))
         serializer.Serialize(xml, value, ns);
 }
예제 #29
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();
        }
예제 #30
0
 // this method must be called before any generated serialization methods are called
 internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly) {
     this.w = w;
     this.namespaces = namespaces;
     this.soap12 = (encodingStyle == Soap12.Encoding);
     this.idBase = idBase;
     Init(tempAssembly);
 }
예제 #31
0
        /// <summary>
        /// Serializer object to xml
        /// </summary>
        /// <param name="obj">the object entity</param>
        /// <returns>return a xml string</returns>
        public static string SerializerToStream(object obj)
        {
            System.Xml.Serialization.XmlSerializer           xs = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            // Add two namespaces with prefixes.
            ns.Add(string.Empty, string.Empty);
            MemoryStream      stream  = new MemoryStream();
            XmlWriterSettings setting = new XmlWriterSettings();

            setting.Encoding = new UTF8Encoding(false);
            setting.Indent   = true;
            using (XmlWriter writer = XmlWriter.Create(stream, setting))
            {
                xs.Serialize(writer, obj, ns);
            }

            return(Encoding.UTF8.GetString(stream.ToArray()));
        }
예제 #32
0
        public static string SerializeObjectToXMLString(object obj, System.Xml.Serialization.XmlSerializerNamespaces ns)
        {
            try
            {
                XmlSerializer          xSerializer = new XmlSerializer(obj.GetType());
                System.IO.MemoryStream oMemStream  = new System.IO.MemoryStream();
                XmlDocument            xDoc        = new XmlDocument();
                xSerializer.Serialize(oMemStream, obj, ns);
                string sXML = System.Text.UTF8Encoding.UTF8.GetString(oMemStream.ToArray());
                xDoc.PreserveWhitespace = false;
                xDoc.LoadXml(sXML);

                return(xDoc.OuterXml);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception in Sirona.Utilities.Serialization.Serializer.SerializeObjectToXMLString:" + Environment.NewLine + ex.Message, ex);
            }
        }
예제 #33
0
        public static string Object2Xml(object obj)
        {
            string sXml = "";
            var    x    = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            var    ns   = new System.Xml.Serialization.XmlSerializerNamespaces();

            ns.Add("", "");
            using (var ms = new System.IO.MemoryStream())
            {
                var settings = new System.Xml.XmlWriterSettings();
                settings.Indent             = false;
                settings.OmitXmlDeclaration = true;
                settings.Encoding           = System.Text.Encoding.UTF8;
                var writer = System.Xml.XmlWriter.Create(ms, settings);
                x.Serialize(writer, obj, ns);
                sXml = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());
            }
            return(sXml);
        }
예제 #34
0
        /// <summary>
        /// Serializer Xml To File
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="fileFullPath"></param>
        public static void SerializerXmlToFile <T>(T t, string fileFullPath)
        {
            System.Xml.Serialization.XmlSerializer serializer
                = new System.Xml.Serialization.XmlSerializer(t.GetType());

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            // Add two namespaces with prefixes.
            ns.Add(string.Empty, string.Empty);
            //ns.Add("ExportDate", DateTime.Now.ToString() );

            Stream        fs     = new FileStream(fileFullPath, FileMode.OpenOrCreate);
            XmlTextWriter writer = new XmlTextWriter(fs, Encoding.GetEncoding("utf-8"));

            writer.Formatting  = Formatting.Indented;
            writer.Indentation = 4;

            // Serialize using the XmlTextWriter.
            serializer.Serialize(writer, t, ns);
            writer.Close();
        }
예제 #35
0
        private static string SystemXmlWriter <T>(T value, System.Xml.XmlWriterSettings settings)
        {
            if (value == null)
            {
                return(String.Empty);
            }

            var buffer = new System.Text.StringBuilder();
            var writer = System.Xml.XmlWriter.Create(buffer, settings);

            var namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();

            namespaces.Add(String.Empty, String.Empty);            // tricks the serializer into not emitting default xmlns attributes

            // serialize feed
            var serializer = new System.Xml.Serialization.XmlSerializer(value.GetType());

            serializer.Serialize(writer, value, namespaces);

            return(buffer.ToString());
        }
예제 #36
0
    private static string ToXML <T>(T obj, bool includetype, bool indent = false)
    {
        if (includetype)
        {
            XElement xml = XMLConverter.ToXml(obj, null, includetype);

            if (indent)
            {
                return(xml.ToString());
            }
            else
            {
                return(xml.ToString(SaveOptions.DisableFormatting));
            }
        }
        else
        {
            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            XmlSerializer xs       = new XmlSerializer(typeof(T));
            StringBuilder sbuilder = new StringBuilder();
            var           xmlws    = new System.Xml.XmlWriterSettings()
            {
                OmitXmlDeclaration = true, Indent = indent
            };
            ns.Add(string.Empty, string.Empty);
            using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
            {
                xs.Serialize(writer, obj, ns);
            }
            string result = sbuilder.ToString();
            ns       = null;
            xs       = null;
            sbuilder = null;
            xmlws    = null;
            return(result);
        }
    }
        public void DeserializeDescribeProcess()
        {
            System.IO.FileStream atom       = new System.IO.FileStream("../../Terradue.Portal/Schemas/examples/describeprocess.xml", System.IO.FileMode.Open);
            XmlSerializer        serializer = new XmlSerializer(typeof(ProcessDescriptions));
            ProcessDescriptions  describe   = (ProcessDescriptions)serializer.Deserialize(atom);

            Assert.AreEqual("com.terradue.wps_oozie.process.OozieAbstractAlgorithm", describe.ProcessDescription[0].Identifier.Value);
            Assert.AreEqual("SRTM Digital Elevation Model", describe.ProcessDescription[0].Title.Value);
            Assert.AreEqual(2, describe.ProcessDescription[0].DataInputs.Count);
            Assert.AreEqual("Level0_ref", describe.ProcessDescription[0].DataInputs[0].Identifier.Value);
            Assert.AreEqual("string", describe.ProcessDescription[0].DataInputs[0].LiteralData.DataType.Value);
            Assert.AreEqual("https://data.terradue.com/gs/catalogue/tepqw/gtfeature/search?format=json&uid=ASA_IM__0PNPAM20120407_082248_000001263113_00251_52851_2317.N1", describe.ProcessDescription[0].DataInputs[0].LiteralData.DefaultValue);
            Assert.AreEqual("format", describe.ProcessDescription[0].DataInputs[1].Identifier.Value);
            Assert.AreEqual("string", describe.ProcessDescription[0].DataInputs[1].LiteralData.DataType.Value);
            Assert.AreEqual("gamma", describe.ProcessDescription[0].DataInputs[1].LiteralData.DefaultValue);
            Assert.AreEqual(2, describe.ProcessDescription[0].ProcessOutputs.Count);
            Assert.AreEqual("result_distribution", describe.ProcessDescription[0].ProcessOutputs[0].Identifier.Value);
            Assert.True(describe.ProcessDescription[0].ProcessOutputs[0].Item is SupportedComplexDataType);
            Assert.AreEqual("result_osd", describe.ProcessDescription[0].ProcessOutputs[1].Identifier.Value);

            var stream = new MemoryStream();

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("wps", "http://www.opengis.net/wps/1.0.0");
            ns.Add("ows", "http://www.opengis.net/ows/1.1");
            ns.Add("xlink", "http://www.w3.org/1999/xlink");
            serializer.Serialize(stream, describe, ns);
            stream.Seek(0, SeekOrigin.Begin);
            string executeText;

            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                executeText = reader.ReadToEnd();
            }
            Assert.IsNotNull(executeText);
        }
예제 #38
0
        /// <summary>
        /// Serializes the specified <paramref name="value"/> into XML using the specified <paramref name="encoding"/> and <paramref name="namespaces"/>.
        /// </summary>
        /// <typeparam name="T">The type of the value to serialize.</typeparam>
        /// <param name="value">The value to serialize.</param>
        /// <param name="encoding">The encoding to use when serializing.</param>
        /// <param name="namespaces">The namespaces to use when serializing.</param>
        /// <returns></returns>
        public string SerializeObject <T>(T value, Encoding encoding, Ser.XmlSerializerNamespaces namespaces)
        {
            string result = string.Empty;

            xmlWriterSettings.Encoding = encoding;

            using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(encoding))
            {
                XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings);

                Ser.XmlSerializer serializer = new Ser.XmlSerializer(typeof(T));
                if (namespaces == null)
                {
                    serializer.Serialize(xmlWriter, value);
                }
                else
                {
                    serializer.Serialize(xmlWriter, value, namespaces);
                }
                result = stringWriter.ToString();
            }

            return(result);
        }
예제 #39
0
        public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            Init(xmlWriter, namespaces, encodingStyle, id);

            if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer)
            {
                throw new ArgumentException(SR.Format(SR.XmlInternalError, "xmlMapping"));
            }

            if (xmlMapping is XmlTypeMapping || xmlMapping is XmlMembersMapping)
            {
                _mapping = xmlMapping;
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.XmlInternalError, "xmlMapping"));
            }
        }
예제 #40
0
        private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
        {
            XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();

            writer.Init(xmlWriter, namespaces, null, null, null);
            switch (_primitiveType.GetTypeCode())
            {
            case TypeCode.String:
                writer.Write_string(o);
                break;

            case TypeCode.Int32:
                writer.Write_int(o);
                break;

            case TypeCode.Boolean:
                writer.Write_boolean(o);
                break;

            case TypeCode.Int16:
                writer.Write_short(o);
                break;

            case TypeCode.Int64:
                writer.Write_long(o);
                break;

            case TypeCode.Single:
                writer.Write_float(o);
                break;

            case TypeCode.Double:
                writer.Write_double(o);
                break;

            case TypeCode.Decimal:
                writer.Write_decimal(o);
                break;

            case TypeCode.DateTime:
                writer.Write_dateTime(o);
                break;

            case TypeCode.Char:
                writer.Write_char(o);
                break;

            case TypeCode.Byte:
                writer.Write_unsignedByte(o);
                break;

            case TypeCode.SByte:
                writer.Write_byte(o);
                break;

            case TypeCode.UInt16:
                writer.Write_unsignedShort(o);
                break;

            case TypeCode.UInt32:
                writer.Write_unsignedInt(o);
                break;

            case TypeCode.UInt64:
                writer.Write_unsignedLong(o);
                break;

            default:
                if (_primitiveType == typeof(XmlQualifiedName))
                {
                    writer.Write_QName(o);
                }
                else if (_primitiveType == typeof(byte[]))
                {
                    writer.Write_base64Binary(o);
                }
                else if (_primitiveType == typeof(Guid))
                {
                    writer.Write_guid(o);
                }
                else
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
                }
                break;
            }
        }
예제 #41
0
 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
 internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
 {
     Serialize(xmlWriter, o, namespaces, encodingStyle, null);
 }
예제 #42
0
 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
 {
     Serialize(xmlWriter, o, namespaces, null);
 }
 public XmlSerializerNamespaces(System.Xml.Serialization.XmlSerializerNamespaces namespaces)
 {
 }
 public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces)
 {
 }
예제 #45
0
 public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
 {
     throw new NotImplementedException();
 }
예제 #46
0
 /// <include file='doc\XmlSerializerNamespaces.uex' path='docs/doc[@for="XmlSerializerNamespaces.XmlSerializerNamespaces1"]/*' />
 /// <internalonly/>
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces)
 {
     _namespaces = (Hashtable)namespaces.Namespaces.Clone();
 }
예제 #47
0
 public void Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
 {
     throw new NotImplementedException();
 }
예제 #48
0
        internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            XmlSerializationWriter writer = null;

            try {
                encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key);
                writer        = Contract.Writer;
                writer.Init(xmlWriter, namespaces, encodingStyle, id, this);
                if (methods[mapping.Key].writeMethod == null)
                {
                    if (writerMethods == null)
                    {
                        writerMethods = Contract.WriteMethods;
                    }
                    string methodName = (string)writerMethods[mapping.Key];
                    if (methodName == null)
                    {
                        throw new InvalidOperationException(Res.GetString(Res.XmlNotSerializable, mapping.Accessor.Name));
                    }
                    methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName, pregeneratedAssmbly ? assembly : null);
                }
                methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o });
            }
            catch (SecurityException e) {
                throw new InvalidOperationException(Res.GetString(Res.XmlNoPartialTrust), e);
            }
            finally {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
        private void WriteAttributes(MemberMapping[] members, MemberMapping anyAttribute, Action <object> elseCall, ref object o)
        {
            MemberMapping xmlnsMember = null;
            var           attributes  = new List <AttributeAccessor>();

            while (Reader.MoveToNextAttribute())
            {
                bool memberFound = false;
                foreach (var member in members)
                {
                    if (member.Xmlns != null)
                    {
                        xmlnsMember = member;
                        continue;
                    }

                    if (member.Ignore)
                    {
                        continue;
                    }
                    AttributeAccessor attribute = member.Attribute;

                    if (attribute == null)
                    {
                        continue;
                    }
                    if (attribute.Any)
                    {
                        continue;
                    }

                    attributes.Add(attribute);

                    if (attribute.IsSpecialXmlNamespace)
                    {
                        memberFound = XmlNodeEqual(Reader, attribute.Name, XmlReservedNs.NsXml);
                    }
                    else
                    {
                        memberFound = XmlNodeEqual(Reader, attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "");
                    }

                    if (memberFound)
                    {
                        WriteAttribute(o, member);
                        memberFound = true;
                        break;
                    }
                }

                if (memberFound)
                {
                    continue;
                }

                bool flag2 = false;
                if (xmlnsMember != null)
                {
                    if (IsXmlnsAttribute(Reader.Name))
                    {
                        if (GetMemberType(xmlnsMember.MemberInfo) == typeof(XmlSerializerNamespaces))
                        {
                            var xmlnsMemberSource = GetMemberValue(o, xmlnsMember.MemberInfo) as XmlSerializerNamespaces;
                            if (xmlnsMemberSource == null)
                            {
                                xmlnsMemberSource = new XmlSerializerNamespaces();
                                SetMemberValue(o, xmlnsMemberSource, xmlnsMember.MemberInfo);
                            }

                            xmlnsMemberSource.Add(Reader.Name.Length == 5 ? "" : Reader.LocalName, Reader.Value);
                        }
                        else
                        {
                            throw new InvalidOperationException("xmlnsMemberSource is not of type XmlSerializerNamespaces");
                        }
                    }
                    else
                    {
                        flag2 = true;
                    }
                }
                else if (!IsXmlnsAttribute(Reader.Name))
                {
                    flag2 = true;
                }

                if (flag2)
                {
                    if (anyAttribute != null)
                    {
                        var attr = Document.ReadNode(Reader) as XmlAttribute;
                        ParseWsdlArrayType(attr);
                        WriteAttribute(o, anyAttribute, attr);
                    }
                    else
                    {
                        elseCall(o);
                    }
                }
            }
        }
예제 #50
0
 protected void WriteStartElement(string name, string ns, Object o, bool writePrefixed, XmlSerializerNamespaces xmlns)
 {
     WriteStartElement(name, ns, o, writePrefixed, xmlns != null ? xmlns.ToArray() : null);
 }
 public static string Serialize(this XmlSerializer serializer, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id, XmlFormatOptions options)
 {
     return(XmlHelper.ReformatXml(serializer.Serialize(o, namespaces, encodingStyle, id), options));
 }
예제 #52
0
 static XmlSerializer()
 {
     defaultNamespaces = new XmlSerializerNamespaces();
     defaultNamespaces.Add("xsi", XmlSchema.InstanceNamespace);
     defaultNamespaces.Add("xsd", XmlSchema.Namespace);
 }
예제 #53
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
        public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            try
            {
                if (_primitiveType != null)
                {
                    if (encodingStyle != null && encodingStyle.Length > 0)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
                    }
                    SerializePrimitive(xmlWriter, o, namespaces);
                }
#if !uapaot
                else if (ShouldUseReflectionBasedSerialization())
                {
                    XmlMapping mapping;
                    if (_mapping != null && _mapping.GenerateSerializer)
                    {
                        mapping = _mapping;
                    }
                    else
                    {
                        XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                        mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                    }

                    var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                    writer.WriteObject(o);
                }
                else if (_tempAssembly == null || _typedSerializer)
                {
                    // The contion for the block is never true, thus the block is never hit.
                    XmlSerializationWriter writer = CreateWriter();
                    writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
                    try
                    {
                        Serialize(o, writer);
                    }
                    finally
                    {
                        writer.Dispose();
                    }
                }
                else
                {
                    _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                }
#else
                else
                {
                    if (this.innerSerializer != null)
                    {
                        if (!string.IsNullOrEmpty(this.DefaultNamespace))
                        {
                            this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
                        }

                        XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
                        writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        try
                        {
                            this.innerSerializer.Serialize(o, writer);
                        }
                        finally
                        {
                            writer.Dispose();
                        }
                    }
                    else if (ReflectionMethodEnabled)
                    {
                        XmlMapping mapping;
                        if (_mapping != null && _mapping.GenerateSerializer)
                        {
                            mapping = _mapping;
                        }
                        else
                        {
                            XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                            mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                        }

                        var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        writer.WriteObject(o);
                    }
                    else
                    {
                        throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
                    }
                }
#endif
            }
예제 #54
0
 public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
 {
     throw new NotImplementedException();
 }
예제 #55
0
        private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType, XmlMapping parentMapping = null)
        {
            if (mapping.IsSoap && mapping.TypeDesc.IsRoot)
            {
                return;
            }

            if (mapping.IsSoap)
            {
                throw new PlatformNotSupportedException();
            }

            if (o == null)
            {
                if (isNullable)
                {
                    WriteNullTagLiteral(n, ns);
                }
                return;
            }

            if (!needType &&
                o.GetType() != mapping.TypeDesc.Type)
            {
                if (WriteDerivedTypes(mapping, n, ns, o, isNullable))
                {
                    return;
                }

                if (mapping.TypeDesc.IsRoot)
                {
                    if (WriteEnumAndArrayTypes(mapping, o, n, ns, parentMapping))
                    {
                        return;
                    }

                    WriteTypedPrimitive(n, ns, o, true);
                    return;
                }

                throw CreateUnknownTypeException(o);
            }

            if (!mapping.TypeDesc.IsAbstract)
            {
                if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
                {
                    throw new PlatformNotSupportedException(typeof(XmlSchemaObject).ToString());
                }

                XmlSerializerNamespaces xmlnsSource = null;
                MemberMapping[]         members     = TypeScope.GetAllMembers(mapping);
                int xmlnsMember = FindXmlnsIndex(members);
                if (xmlnsMember >= 0)
                {
                    MemberMapping member = members[xmlnsMember];
                    xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name);
                }

                if (mapping.IsSoap)
                {
                    throw new PlatformNotSupportedException();
                }

                WriteStartElement(n, ns, o, false, xmlnsSource);

                if (!mapping.TypeDesc.IsRoot)
                {
                    if (needType)
                    {
                        WriteXsiType(mapping.TypeName, mapping.Namespace);
                    }
                }

                for (int i = 0; i < members.Length; i++)
                {
                    MemberMapping m           = members[i];
                    string        memberName  = m.Name;
                    object        memberValue = GetMemberValue(o, memberName);

                    bool isSpecified   = true;
                    bool shouldPersist = true;
                    if (m.CheckSpecified != SpecifiedAccessor.None)
                    {
                        string specifiedMemberName = m.Name + "Specified";
                        isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
                    }

                    if (m.CheckShouldPersist)
                    {
                        string     methodInvoke = "ShouldSerialize" + m.Name;
                        MethodInfo method       = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
                        shouldPersist = (bool)method.Invoke(o, Array.Empty <object>());
                    }

                    if (m.Attribute != null)
                    {
                        if (isSpecified && shouldPersist)
                        {
                            WriteMember(memberValue, m.Attribute, m.TypeDesc, o);
                        }
                    }
                }

                for (int i = 0; i < members.Length; i++)
                {
                    MemberMapping m           = members[i];
                    string        memberName  = m.Name;
                    object        memberValue = GetMemberValue(o, memberName);

                    bool isSpecified   = true;
                    bool shouldPersist = true;
                    if (m.CheckSpecified != SpecifiedAccessor.None)
                    {
                        string specifiedMemberName = m.Name + "Specified";
                        isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
                    }

                    if (m.CheckShouldPersist)
                    {
                        string     methodInvoke = "ShouldSerialize" + m.Name;
                        MethodInfo method       = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
                        shouldPersist = (bool)method.Invoke(o, Array.Empty <object>());
                    }

                    if (m.Xmlns != null)
                    {
                        continue;
                    }

                    bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null);

                    if (!checkShouldPersist)
                    {
                        shouldPersist = true;
                    }

                    object choiceSource = null;
                    if (m.ChoiceIdentifier != null)
                    {
                        choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName);
                    }

                    if (isSpecified && shouldPersist)
                    {
                        WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true, parentMapping);
                    }
                }
                if (!mapping.IsSoap)
                {
                    WriteEndElement(o);
                }
            }
        }
 /// <internalonly/>
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces)
 {
     _namespaces = new Dictionary <string, string>(namespaces.Namespaces);
 }
예제 #57
0
        //public enum MessageLogType
        //{
        //    Info,
        //    Debug,
        //    Valid,
        //    Error,
        //    Warning
        //}

        //public class MessageLoggedEventArgs : System.EventArgs
        //{
        //    public MessageLoggedEventArgs()
        //        : this(new List<string> { }, MessageLogType.Info, false, false)
        //    {
        //    }

        //    public MessageLoggedEventArgs(Exception exception)
        //        : this((exception != null ? exception.Message : ""))
        //    {
        //        Exception = exception;
        //    }

        //    public MessageLoggedEventArgs(string message)
        //        : this(message, MessageLogType.Info, false, false)
        //    {
        //    }

        //    public MessageLoggedEventArgs(string message, MessageLogType type)
        //        : this(message, type, false, false)
        //    {
        //    }

        //    public MessageLoggedEventArgs(string message, MessageLogType type, bool doEvents, bool clear)
        //        : base()
        //    {
        //        Exception = null;
        //        Type = type;
        //        Messages = new List<string>();
        //        AddMessage(message);
        //        DoEvents = doEvents;
        //        Clear = clear;
        //    }

        //    public MessageLoggedEventArgs(List<string> messages, MessageLogType type, bool doEvents, bool clear)
        //        : base()
        //    {
        //        Exception = null;
        //        Type = type;
        //        Messages = new List<string>();
        //        if (messages != null)
        //            Messages.AddRange(messages);
        //        DoEvents = doEvents;
        //        Clear = clear;
        //    }

        //    public string Message
        //    {
        //        get { return String.Join("", Messages.ToArray()); }
        //    }
        //    public List<string> Messages { get; private set; }
        //    public Exception Exception { get; private set; }
        //    public bool DoEvents { get; private set; }
        //    public bool Clear { get; private set; }
        //    public MessageLogType Type { get; set; }

        //    public void AddMessage(string message)
        //    {
        //        if (message == null)
        //            return;

        //        Messages.Add(String.Concat("\r\n", DateTime.Now.ToLongTimeString().PadRight(12), message));
        //    }
        //}

        //internal bool RaiseMessageLogged(object sender, MessageLoggedEventArgs e)
        //{
        //    if (MessageLogged != null)
        //    {
        //        MessageLogged(sender, e);
        //        return true;
        //    }
        //    return false;
        //}

        //internal bool RaiseMessageLogged(string message)
        //{
        //    return RaiseMessageLogged(this, new MessageLoggedEventArgs(message));
        //}

        //internal void RaiseMessageLogged(Exception exc)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.AppendLine(exc.Message);

        //    Exception innerException = exc.InnerException;
        //    while (innerException != null)
        //    {
        //        sb.AppendLine(innerException.Message);
        //        innerException = innerException.InnerException;
        //    }

        //    RaiseMessageLogged(sb.ToString());
        //}

        public string Serialize <T>(T t) where T : class
        {
            // see http://stackoverflow.com/questions/1408336/xmlserialization-and-xsischemalocation-xsd-exe
            // add field to ifcXML class
            //public partial class ifcXML : uos
            //{

            //    [System.Xml.Serialization.XmlAttribute("schemaLocation", Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
            //    public string xsiSchemaLocation = @"http://www.buildingsmart-tech.org/ifcXML/IFC4/final http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd";


            //// Original Doku
            //<ifcXML
            //xmlns="http://www.buildingsmart-tech.org/ifcXML/IFC4/final"
            //xmlns:ifc="http://www.buildingsmart-tech.org/ifcXML/IFC4/final"
            //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            //xsi:schemaLocation="http://www.buildingsmart-tech.org/ifcXML/IFC4/final http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd"
            //id="ifcXML4">
            //<!-- any content -->
            //</ifcXML>

            // -------------------------------------------------------------------------------

            //// Catalogue Export
            //<ifcXML
            //xmlns:ifc="http://www.buildingsmart-tech.org/ifcXML/IFC4/final"
            //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            //xsi:schemaLocation="http://www.buildingsmart-tech.org/ifcXML/IFC4/final http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd"
            //xmlns="http://www.buildingsmart-tech.org/ifcXML/IFC4/final"
            //id="ifcXML4">
            //<!-- any content -->
            //</ifcXML>

            // -------------------------------------------------------------------------------

            //// jvTest
            //<ifcXML
            //xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            //xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            //xmlns="http://www.buildingsmart-tech.org/ifcXML/IFC4/final"
            //id="ifcXML4"
            //express=""
            //configuration="">
            //<!-- any content -->
            //</ifcXML>

            // -------------------------------------------------------------------------------

            System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();
            //namespaces.Add("", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final");
            //namespaces.Add("ifc", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final");
            //namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            //namespaces.Add("schemaLocation", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd");

            // Type type = o.GetType();
            string xml = String.Empty;

            //namespaces = new XmlSerializerNamespaces(new System.Xml.XmlQualifiedName[]{
            //    new System.Xml.XmlQualifiedName("ifc", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final"),
            //    new System.Xml.XmlQualifiedName("xsi", "http://www.w3.org/2001/XMLSchema-instance"),
            //    new System.Xml.XmlQualifiedName("schemaLocation", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd")
            //});

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    var xmlWriterSettings = new System.Xml.XmlWriterSettings
                    {
                        Encoding           = new UTF8Encoding(false),
                        OmitXmlDeclaration = false,
                        Indent             = true,
                        NamespaceHandling  = System.Xml.NamespaceHandling.OmitDuplicates,
                        CheckCharacters    = true,
                    };

                    using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        Ifc4.Workspace.CurrentWorkspace.RaiseMessageLogged("Serialize...");
                        if (namespaces.Count > 0)
                        {
                            this.Serialize(xmlWriter, t.GetType(), namespaces);
                        }
                        else
                        {
                            this.Serialize(xmlWriter, t);
                        }
                    }

                    xml = Encoding.UTF8.GetString(memoryStream.ToArray());

                    //// -------------------------------------------------------------------------------
                    //RaiseMessageLogged("Namespace correction...");
                    //xml = xml.Replace(
                    //                    " xmlns:schemaLocation=",
                    //                    " xsi:schemaLocation="
                    //                );
                    //// ---------------------------------------
                }
                return(xml);
            }
            catch (Exception exc)
            {
                Ifc4.Workspace.CurrentWorkspace.RaiseMessageLogged(this, exc);
                return(String.Empty);
            }
        }
 public void Serialize(System.IO.Stream stream, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces)
 {
 }
 public static void Serialize(this XmlSerializer serializer, TextWriter textWriter, object o, XmlSerializerNamespaces namespaces, bool omitStandardNamespaces)
 {
     if (omitStandardNamespaces)
     {
         namespaces = namespaces ?? new XmlSerializerNamespaces();
         namespaces.Add("", "");
     }
     serializer.Serialize(textWriter, o, namespaces);
 }
 public static void Serialize(this XmlSerializer serializer, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id, bool omitStandardNamespaces)
 {
     if (omitStandardNamespaces)
     {
         namespaces = namespaces ?? new XmlSerializerNamespaces();
         namespaces.Add("", "");
     }
     serializer.Serialize(xmlWriter, o, namespaces, encodingStyle, id);
 }