Пример #1
0
        /// <summary>
        /// Serialize object into StringWriter using XmlSerialization
        /// </summary>
        /// <param name="objectToSerialize">object to serialize</param>
        /// <returns></returns>
        /// <remarks>
        /// Unknown Original Author
        /// Edited, Andrew Powell 10.26.07
        /// - Modified method to use EncodedStringWriter.
        /// </remarks>
        private static StringWriter XmlSerialize(object objectToSerialize, System.Text.Encoding encoding)
        {
            EncodedStringWriter writer = new EncodedStringWriter(encoding);

            try
            {
                XmlSerializer serializer = new XmlSerializer(objectToSerialize.GetType());

                //This is used to remove the standard XMl namespaces from the serialized output
                //so as to make it easier to see in the browser output
                XmlQualifiedName[] dummyNamespaceName = new XmlQualifiedName[1];
                dummyNamespaceName[0] = new XmlQualifiedName();
                serializer.Serialize(writer, objectToSerialize, new XmlSerializerNamespaces(dummyNamespaceName));
            }
            catch (InvalidOperationException ex)
            {
                //If we cannot serialize then we can't leave it at that
            }
            catch (System.Runtime.Serialization.SerializationException ex)
            {
                //Ignore This can happen when some objects are just not Serializable using XML serialization
            }
            catch (Exception ex)
            {
                //Ignore. This can happen when storing a set of custom objects in a collection.
                //The XmlSerializer will start to serialize the collection come across the custom objects
                //amd not know what to do. The use of custom serialization attributes will help the serializer.
            }
            //This will only be hit by a failed serialization execution
            return(writer);
        }
Пример #2
0
        /// <summary>
        /// Writes the NMSTemplate object to an .exml file.
        /// </summary>
        /// <param name="outputpath">The location to write the .exml file.</param>
        /// <param name="hideVersionInfo">If true, version info is not written to the EXML file.</param>
        public static string WriteTemplate(NMSTemplate template, bool hideVersionInfo)
        {
            var origCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            var xmlSettings = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = Encoding.UTF8
            };

            using (var stringWriter = new EncodedStringWriter(Encoding.UTF8))
                using (var xmlTextWriter = XmlWriter.Create(stringWriter, xmlSettings))
                {
                    string ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    if (!hideVersionInfo)
                    {
                        xmlTextWriter.WriteComment(String.Format("File created using MBINCompiler version ({0})", ver.Substring(0, ver.Length - 2)));
                    }
                    var data = template.SerializeEXml(false);
                    Serializer.Serialize(xmlTextWriter, data, Namespaces);
                    xmlTextWriter.Flush();

                    var xmlData = stringWriter.GetStringBuilder().ToString();
                    Thread.CurrentThread.CurrentCulture = origCulture;
                    return(xmlData);
                }
        }
		/// <summary>
		///   Преобразовать документ в XML-строку
		/// </summary>
		/// <param name="document"> Документ </param>
		/// <param name="encoding"> Кодировка документа </param>
		/// <param name="options"> Опции сохранения </param>
		/// <returns> </returns>
		public static string ToXml(this XDocument document, Encoding encoding, SaveOptions options)
		{
			using (var writer = new EncodedStringWriter(encoding))
			{
				document.Save(writer, options);
				return writer.ToString();
			}
		}
        public void CausesTheEncodingPropertyToReturnTheEncodingParameter()
        {
            var encoding = Encoding.BigEndianUnicode;

            var writer = new EncodedStringWriter(new StringBuilder(), CultureInfo.CurrentCulture, encoding);

            Assert.That(writer.Encoding, Is.SameAs(encoding));
        }
 /// <summary>
 ///   Преобразовать документ в XML-строку
 /// </summary>
 /// <param name="document"> Документ </param>
 /// <param name="encoding"> Кодировка документа </param>
 /// <param name="options"> Опции сохранения </param>
 /// <returns> </returns>
 public static string ToXml(this XDocument document, Encoding encoding, SaveOptions options)
 {
     using (var writer = new EncodedStringWriter(encoding))
     {
         document.Save(writer, options);
         return(writer.ToString());
     }
 }
Пример #6
0
 // TODO: also move to .net std 1.1 helper
 public static string ToString(this XmlSchema schema, Encoding encoding)
 {
     using (var stringWriter = new EncodedStringWriter(encoding))
     {
         schema.Write(stringWriter);
         return(stringWriter.ToString());
     }
 }
        public void CausesTheEncodingPropertyToReturnTheEncodingParameter()
        {
            var encoding = Encoding.BigEndianUnicode;

            var writer = new EncodedStringWriter(encoding);

            Assert.That(writer.Encoding, Is.SameAs(encoding));
        }
Пример #8
0
        public static IXPathNavigable XmlSerialize(this object value)
#endif
        {
            if (null == value)
            {
                throw new ArgumentNullException("value");
            }

            var result = new XmlDocument();

            var buffer = new StringBuilder();

            var exception = value as Exception;

#if NET20
            if (ObjectExtensionMethods.IsNotNull(exception))
#else
            if (exception.IsNotNull())
#endif
            {
                using (var stream = new MemoryStream())
                {
                    new SoapFormatter().Serialize(stream, value);
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(stream))
                    {
                        buffer.Append(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                using (TextWriter writer = new EncodedStringWriter(buffer, CultureInfo.InvariantCulture, Encoding.UTF8))
                {
                    XmlSerializerNamespaces namespaces;
                    var obj = value as IXmlSerializerNamespaces;
                    if (null == obj)
                    {
                        namespaces = new XmlSerializerNamespaces();
                        namespaces.Add(string.Empty, string.Empty);
                    }
                    else
                    {
                        namespaces = obj.XmlNamespaceDeclarations;
                    }

                    new XmlSerializer(value.GetType()).Serialize(writer, value, namespaces);
                }
            }

            result.LoadXml(buffer.ToString());

            return(result);
        }
Пример #9
0
 public static string ToClearXml <T>(this T value, Encoding Encoding) where T : class
 {
     using (EncodedStringWriter writer = new EncodedStringWriter(Encoding))
     {
         XmlSerializer           serializer = new XmlSerializer(value.GetType());
         XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
         namespaces.Add("", "");
         serializer.Serialize(writer, value, namespaces);
         return(writer.ToString());
     }
 }
Пример #10
0
 public static string SerializeToString <T>(T obj, Encoding encoding, params PrefixTuple[] prefixes)
     where T : class
 {
     using (var sw = new EncodedStringWriter(encoding ?? Encoding.UTF8))
         using (var xw = XmlWriter.Create(sw, new XmlWriterSettings {
             OmitXmlDeclaration = true, NewLineOnAttributes = true, Indent = true
         }))
         {
             return(SerializeToString(obj, encoding, xw, sw, prefixes));
         }
 }
        public string SerializeToString(object item, Type type)
        {
            type = CheckType(type, item);

            var sb = new StringBuilder();

            using (var writer = new EncodedStringWriter(sb, _encoding))
            {
                var serializer = new XmlSerializer(type);
                serializer.Serialize(writer, item);
            }

            return sb.ToString();
        }
        public string SerializeToString(object item, Type type)
        {
            var sb = new StringBuilder();

            using (var stringWriter = new EncodedStringWriter(sb, _encoding))
            {
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    _jsonSerializer.Serialize(jsonWriter, item, type);
                }
            }

            return(sb.ToString());
        }
Пример #13
0
        public string SerializeToString(object item, Type type)
        {
            type = CheckType(type, item);

            var sb = new StringBuilder();

            using (var writer = new EncodedStringWriter(sb, _encoding))
            {
                var serializer = new XmlSerializer(type);
                serializer.Serialize(writer, item);
            }

            return(sb.ToString());
        }
        public string SerializeToString(object item, Type type)
        {
            var sb = new StringBuilder();

            using (var stringWriter = new EncodedStringWriter(sb, _encoding))
            {
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    _jsonSerializer.Serialize(jsonWriter, item, type);
                }
            }

            return sb.ToString();
        }
        public string SerializeToString(object item, Type type)
        {
            var sb = new StringBuilder();

            using (var stringWriter = new EncodedStringWriter(sb, _encoding))
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Encoding = _encoding }))
                {
                    var serializer = new DataContractSerializer(type);
                    serializer.WriteObject(xmlWriter, item);
                }
            }

            return sb.ToString();
        }
Пример #16
0
        private static string ConvertResponseObjectToXml <T>(T objectToSerialize, Encoding encoding)
        {
            var serializer   = new XmlSerializer(typeof(T));
            var stringWriter = new EncodedStringWriter(encoding);

            var settings = new XmlWriterSettings
            {
                Encoding = encoding
            };

            using (var writer = XmlWriter.Create(stringWriter, settings))
            {
                serializer.Serialize(writer, objectToSerialize);
                return(stringWriter.ToString());
            }
        }
        public string SerializeToString(object item, Type type)
        {
            var sb = new StringBuilder();

            using (var stringWriter = new EncodedStringWriter(sb, _encoding))
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings {
                    Encoding = _encoding
                }))
                {
                    var serializer = new DataContractSerializer(type);
                    serializer.WriteObject(xmlWriter, item);
                }
            }

            return(sb.ToString());
        }
Пример #18
0
        public static string WriteTemplate(NMSTemplate template)
        {
            var xmlSettings = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = Encoding.UTF8
            };

            using (var stringWriter = new EncodedStringWriter(Encoding.UTF8))
                using (var xmlTextWriter = XmlWriter.Create(stringWriter, xmlSettings))
                {
                    EXmlData data = template.SerializeEXml();
                    Serializer.Serialize(xmlTextWriter, data, Namespaces);
                    xmlTextWriter.Flush();
                    return(stringWriter.GetStringBuilder().ToString());
                }
        }
Пример #19
0
        protected string SerializeToString(XmlSerializer serializer, object obj, Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();

            using (TextWriter writer = new EncodedStringWriter(sb, encoding))
            {
                XmlTextWriter xtw = new XmlTextWriter(writer);
                if (SerializationSettings.Current.Indent)
                {
                    xtw.Formatting  = Formatting.Indented;
                    xtw.Indentation = 2;
                }
                XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
                xmlns.Add(string.Empty, string.Empty);
                serializer.Serialize(xtw, obj, xmlns);
            }

            return(sb.ToString());
        }
Пример #20
0
        public void TestTransform()
        {
            var xml =
                @"<?xml-stylesheet type='text/xsl' href='hello.xsl'?>
<foo><bar>thing</bar><baz>other</baz></foo>";
            var xslt     = @"<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" version=""1.0"">
<xsl:template match='foo'><a>bar=<xsl:value-of select='bar'/>;<xsl:apply-templates select='baz'/></a></xsl:template>
<xsl:template match='baz'>baz=<xsl:value-of select='.'/>;</xsl:template>
</xsl:stylesheet>";
            var expected = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a>bar=thing;baz=other;</a>";

            (var transform, var error) = XmlEditorService.CompileStylesheet(xslt, "test.xml");
            Assert.NotNull(transform);
            Assert.IsNull(error);

            var outWriter = new EncodedStringWriter(System.Text.Encoding.UTF8);

            using (var reader = XmlReader.Create(new StringReader(xml))) {
                transform.Transform(reader, null, outWriter);
            }
            Assert.AreEqual(expected, outWriter.ToString());
        }
Пример #21
0
        /// <inheritdoc />
        public string SerializeToString(object item, Type type)
        {
            Guard.Guard.Against.Null(item, nameof(item));
            Guard.Guard.Against.Null(type, nameof(type));

            type = CheckType(type, item);

            var builder = new StringBuilder();

            if (WriterSettings.IsNull())
            {
                using (var writer = new EncodedStringWriter(builder))
                    new XmlSerializer(type).Serialize(writer, item, Namespaces);
            }
            else
            {
                using (var stringWriter = new EncodedStringWriter(builder, WriterSettings.Encoding))
                    using (var writer = XmlWriter.Create(stringWriter, WriterSettings))
                        new XmlSerializer(type).Serialize(writer, item, Namespaces);
            }

            return(builder.ToString());
        }
Пример #22
0
        public static string WriteTemplate(NMSTemplate template)
        {
            var origCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            var xmlSettings = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = Encoding.UTF8
            };

            using (var stringWriter = new EncodedStringWriter(Encoding.UTF8))
                using (var xmlTextWriter = XmlWriter.Create(stringWriter, xmlSettings))
                {
                    var data = template.SerializeEXml(false);
                    Serializer.Serialize(xmlTextWriter, data, Namespaces);
                    xmlTextWriter.Flush();

                    var xmlData = stringWriter.GetStringBuilder().ToString();
                    Thread.CurrentThread.CurrentCulture = origCulture;
                    return(xmlData);
                }
        }
Пример #23
0
        private static string ParseImpl(PageInfo pageInfo, ContextInfo contextInfo, string version, string title, string description, string scopeTypeString, string groupChannel, string groupChannelNot, string groupContent, string groupContentNot, string tags, string channelIndex, string channelName, int totalNum, int startNum, string orderByString, bool isTop, bool isTopExists, bool isRecommend, bool isRecommendExists, bool isHot, bool isHotExists, bool isColor, bool isColorExists)
        {
            var parsedContent = string.Empty;

            var feed = new RssFeed();

            feed.Encoding = ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset);
            if (string.IsNullOrEmpty(version))
            {
                feed.Version = RssVersion.RSS20;
            }
            else
            {
                feed.Version = (RssVersion)TranslateUtils.ToEnum(typeof(RssVersion), version, RssVersion.RSS20);
            }

            var channel = new RssChannel();

            channel.Title       = title;
            channel.Description = description;

            EScopeType scopeType;

            if (!string.IsNullOrEmpty(scopeTypeString))
            {
                scopeType = EScopeTypeUtils.GetEnumType(scopeTypeString);
            }
            else
            {
                scopeType = EScopeType.All;
            }

            var channelID = StlCacheManager.NodeId.GetNodeIdByChannelIdOrChannelIndexOrChannelName(pageInfo.PublishmentSystemId, contextInfo.ChannelID, channelIndex, channelName);

            var nodeInfo = NodeManager.GetNodeInfo(pageInfo.PublishmentSystemId, channelID);

            if (string.IsNullOrEmpty(channel.Title))
            {
                channel.Title = nodeInfo.NodeName;
            }
            if (string.IsNullOrEmpty(channel.Description))
            {
                channel.Description = nodeInfo.Content;
                if (string.IsNullOrEmpty(channel.Description))
                {
                    channel.Description = nodeInfo.NodeName;
                }
                else
                {
                    channel.Description = StringUtils.MaxLengthText(channel.Description, 200);
                }
            }
            channel.Link = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetChannelUrl(pageInfo.PublishmentSystemInfo, nodeInfo)));

            var dataSource = StlDataUtility.GetContentsDataSource(pageInfo.PublishmentSystemInfo, channelID, 0, groupContent, groupContentNot, tags, false, false, false, false, false, false, false, false, startNum, totalNum, orderByString, isTopExists, isTop, isRecommendExists, isRecommend, isHotExists, isHot, isColorExists, isColor, string.Empty, scopeType, groupChannel, groupChannelNot, null);

            if (dataSource != null)
            {
                foreach (var dataItem in dataSource)
                {
                    var item = new RssItem();

                    var contentInfo = new BackgroundContentInfo(dataItem);
                    item.Title       = StringUtils.Replace("&", contentInfo.Title, "&amp;");
                    item.Description = contentInfo.Summary;
                    if (string.IsNullOrEmpty(item.Description))
                    {
                        item.Description = StringUtils.StripTags(contentInfo.Content);
                        if (string.IsNullOrEmpty(item.Description))
                        {
                            item.Description = contentInfo.Title;
                        }
                        else
                        {
                            item.Description = StringUtils.MaxLengthText(item.Description, 200);
                        }
                    }
                    item.Description = StringUtils.Replace("&", item.Description, "&amp;");
                    item.PubDate     = contentInfo.AddDate;
                    item.Link        = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetContentUrl(pageInfo.PublishmentSystemInfo, contentInfo)));

                    channel.Items.Add(item);
                }
            }

            feed.Channels.Add(channel);

            var builder    = new StringBuilder();
            var textWriter = new EncodedStringWriter(builder, ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset));

            feed.Write(textWriter);

            parsedContent = builder.ToString();

            return(parsedContent);
        }
Пример #24
0
        private static string ParseImpl(PageInfo pageInfo, ContextInfo contextInfo, string title, string description, string scopeTypeString, string groupChannel, string groupChannelNot, string groupContent, string groupContentNot, string tags, string channelIndex, string channelName, int totalNum, int startNum, string orderByString, bool isTop, bool isTopExists, bool isRecommend, bool isRecommendExists, bool isHot, bool isHotExists, bool isColor, bool isColorExists)
        {
            var feed = new RssFeed
            {
                Encoding = ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset),
                Version  = RssVersion.RSS20
            };

            var channel = new RssChannel
            {
                Title       = title,
                Description = description
            };

            var scopeType = !string.IsNullOrEmpty(scopeTypeString) ? EScopeTypeUtils.GetEnumType(scopeTypeString) : EScopeType.All;

            var channelId = StlDataUtility.GetChannelIdByChannelIdOrChannelIndexOrChannelName(pageInfo.SiteId, contextInfo.ChannelId, channelIndex, channelName);

            var nodeInfo = ChannelManager.GetChannelInfo(pageInfo.SiteId, channelId);

            if (string.IsNullOrEmpty(channel.Title))
            {
                channel.Title = nodeInfo.ChannelName;
            }
            if (string.IsNullOrEmpty(channel.Description))
            {
                channel.Description = nodeInfo.Content;
                channel.Description = string.IsNullOrEmpty(channel.Description) ? nodeInfo.ChannelName : StringUtils.MaxLengthText(channel.Description, 200);
            }
            channel.Link = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetChannelUrl(pageInfo.SiteInfo, nodeInfo, pageInfo.IsLocal)));

            var minContentInfoList = StlDataUtility.GetMinContentInfoList(pageInfo.SiteInfo, channelId, 0, groupContent, groupContentNot, tags, false, false, false, false, false, false, false, startNum, totalNum, orderByString, isTopExists, isTop, isRecommendExists, isRecommend, isHotExists, isHot, isColorExists, isColor, string.Empty, scopeType, groupChannel, groupChannelNot, null);

            if (minContentInfoList != null)
            {
                foreach (var minContentInfo in minContentInfoList)
                {
                    var item = new RssItem();

                    var contentInfo = ContentManager.GetContentInfo(pageInfo.SiteInfo, minContentInfo.ChannelId, minContentInfo.Id);
                    item.Title       = StringUtils.Replace("&", contentInfo.Title, "&amp;");
                    item.Description = contentInfo.Summary;
                    if (string.IsNullOrEmpty(item.Description))
                    {
                        item.Description = StringUtils.StripTags(contentInfo.Content);
                        item.Description = string.IsNullOrEmpty(item.Description) ? contentInfo.Title : StringUtils.MaxLengthText(item.Description, 200);
                    }
                    item.Description = StringUtils.Replace("&", item.Description, "&amp;");
                    item.PubDate     = contentInfo.AddDate.Value;
                    item.Link        = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetContentUrl(pageInfo.SiteInfo, contentInfo, false)));

                    channel.Items.Add(item);
                }
            }

            feed.Channels.Add(channel);

            var builder    = new StringBuilder();
            var textWriter = new EncodedStringWriter(builder, ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset));

            feed.Write(textWriter);

            return(builder.ToString());
        }
		public static string CreateSchema (TextEditor doc, string xml)
		{
			using (System.Data.DataSet dataSet = new System.Data.DataSet()) {
				dataSet.ReadXml(new StringReader (xml), System.Data.XmlReadMode.InferSchema);
				using (EncodedStringWriter writer = new EncodedStringWriter (Encoding.UTF8)) {
					using (XmlTextWriter xmlWriter = XmlEditorService.CreateXmlTextWriter (doc, writer)) {
						dataSet.WriteXmlSchema(xmlWriter);
						return writer.ToString();
					}
				}
			}
		}
        public void Constructor()
        {
            TextWriter stringWriter = new EncodedStringWriter(Encoding.ASCII);

            Assert.Equal(Encoding.ASCII, stringWriter.Encoding);
        }