<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Sayed Ibrahim Hashimi - MSBuild, Web Deploy (MSDeploy), ASP.NET - DataContractSerializer</title>
    <link>http://sedodream.com/</link>
    <description>MSBuild, C#, Visual Studio and more</description>
    <language>en-us</language>
    <copyright>Sayed Ibrahim Hashimi</copyright>
    <lastBuildDate>Wed, 04 Jun 2008 05:54:58 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>sayed.hashimi@gmail.com</managingEditor>
    <webMaster>sayed.hashimi@gmail.com</webMaster>
    <item>
      <trackback:ping>http://sedodream.com/Trackback.aspx?guid=0a779774-4405-44e4-98a1-af91c1ad8269</trackback:ping>
      <pingback:server>http://sedodream.com/pingback.aspx</pingback:server>
      <pingback:target>http://sedodream.com/PermaLink,guid,0a779774-4405-44e4-98a1-af91c1ad8269.aspx</pingback:target>
      <dc:creator />
      <wfw:comment>http://sedodream.com/CommentView,guid,0a779774-4405-44e4-98a1-af91c1ad8269.aspx</wfw:comment>
      <wfw:commentRss>http://sedodream.com/SyndicationService.asmx/GetEntryCommentsRss?guid=0a779774-4405-44e4-98a1-af91c1ad8269</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <title>DataContract XML Helper</title>
      <guid isPermaLink="false">http://sedodream.com/PermaLink,guid,0a779774-4405-44e4-98a1-af91c1ad8269.aspx</guid>
      <link>http://sedodream.com/2008/06/04/DataContractXMLHelper.aspx</link>
      <pubDate>Wed, 04 Jun 2008 05:54:58 GMT</pubDate>
      <description>&lt;p&gt;
Lately I've been doing some work with WCF and I have had a need to easily convert
from object-&amp;gt;XML and from XML-&amp;gt;object. These XML strings were created using
the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx"&gt;DataContractSerializer&lt;/a&gt;.
So I threw together this util class [yeah I know I probably shouldn't have these,
but you know you do too &lt;span style="FONT-FAMILY: Wingdings"&gt;J&lt;/span&gt; ]. There are
really 2 methods &lt;em&gt;GetDataContractXml&lt;/em&gt; and &lt;em&gt;BuildFromDataContractXml&lt;/em&gt;.
The &lt;em&gt;GetDataContractXml&lt;/em&gt; returns the XML for the object provided and the &lt;em&gt;BuildFromDataContractXml&lt;/em&gt; method
will create the object from the XML string. These methods have both a generic and
non-generic method. The non-generic versions are particularly useful if you are using
this with reflection. Anywayz, the class itself is shown below, and you can download
the file at the bottom of this post. 
&lt;/p&gt;
&lt;pre&gt;///
/// © Copyright Sayed Ibrahim Hashimi
/// www.sedodream.com
///
using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
namespace Sedodream.Sample.Serialization01.Util
{
    public static class XmlUtils
    {
        /// 
&lt;SUMMARY&gt;
/// Builds an object of the specified type from the given /// XML representation that
can be passed to the DataContractSerializer /// 
&lt;/SUMMARY&gt;
public static object BuildFromDataContractXml(string xml, Type type) { if (string.IsNullOrEmpty(xml))
{throw new ArgumentNullException("xml"); } if (type == null) { throw new ArgumentNullException("type");
} object result = null; DataContractSerializer dcs = new DataContractSerializer(type);
using (StringReader reader = new StringReader(xml)) using (XmlReader xmlReader = new
XmlTextReader(reader)) { result = dcs.ReadObject(xmlReader); } return result; } /// 
&lt;SUMMARY&gt;
/// Builds an object from its XML /// representation that can be passed to the DataContractSerializer.
/// 
&lt;/SUMMARY&gt;
public static T BuildFromDataContractXml&lt;T&gt;
(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentNullException("xml");
} T result = default(T); object objResult = BuildFromDataContractXml(xml, typeof(T));
if (objResult != null) { result = (T)objResult; } return result; } /// 
&lt;SUMMARY&gt;
/// Gets the XML representation of the given object /// by using the DataContracSerializer.
/// 
&lt;/SUMMARY&gt;
public static string GetDataContractXml&lt;T&gt;
(T obj) { if (obj == null) { throw new ArgumentNullException("obj"); } return GetDataContractXml(obj.GetType(),
obj); } /// 
&lt;SUMMARY&gt;
/// Gets the XML representation of the given object /// of specfiied 
&lt;C&gt;
type
&lt;/C&gt;
by using the DataContracSerializer. /// 
&lt;/SUMMARY&gt;
public static string GetDataContractXml(Type type, object val) { if (type == null)
{ throw new ArgumentNullException("type"); } if (val == null) { throw new ArgumentNullException("val");
} MemoryStream ms = new MemoryStream(); string xml = null; try { DataContractSerializer
dcs = new DataContractSerializer(type); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms,
System.Text.Encoding.Default)) { xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
dcs.WriteObject(xmlTextWriter, val); xmlTextWriter.Flush(); ms = (MemoryStream)xmlTextWriter.BaseStream;
ms.Flush(); xml = UTF8ByteArrayToString(ms.ToArray()); } } finally { if (ms != null)
{ ms.Close(); ms = null; } } return xml; } /// 
&lt;SUMMARY&gt;
/// Writes the XML representation from the DataContractSerializer /// into the specified
filename. If a file at 
&lt;C&gt;
filename
&lt;/C&gt;
/// already exists then an 
&lt;C&gt;
Exception
&lt;/C&gt;
will be thrown. /// 
&lt;/SUMMARY&gt;
public static void WriteDateContractToFile&lt;T&gt;
(string filename, T obj) { WriteDateContractToFile(filename, obj.GetType(), obj);
} /// 
&lt;SUMMARY&gt;
/// Writes the XML representation from the DataContractSerializer /// into the specified
filename. If a file at 
&lt;C&gt;
filename
&lt;/C&gt;
/// already exists then an 
&lt;C&gt;
Exception
&lt;/C&gt;
will be thrown. /// 
&lt;/SUMMARY&gt;
public static void WriteDateContractToFile(string filename, Type type, object val)
{ if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename");
} if (val == null) { throw new ArgumentNullException("val"); } if (File.Exists(filename))
{ throw new ArgumentException("filname"); } //TODO: Stream this into the file instead
of this!!! File.WriteAllText(filename, GetDataContractXml(type, val)); } private static
String UTF8ByteArrayToString(Byte[] characters) { UTF8Encoding encoding = new UTF8Encoding();
string constructedString = encoding.GetString(characters); return (constructedString);
} private static Byte[] StringToUTF8ByteArray(String pXmlString) { UTF8Encoding encoding
= new UTF8Encoding(); byte[] byteArray = encoding.GetBytes(pXmlString); return byteArray;
} } } 
&lt;/pre&gt;
&lt;p&gt;
To show how this can be used here is a quick sample unit test shown below, this will
be a part of a later post on a related topic. 
&lt;/p&gt;
&lt;p style="MARGIN-LEFT: 38pt"&gt;
&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Sedodream.Sample.Serialization01;
using Sedodream.Sample.Serialization01.Util;

namespace unittest.Sedodream.Sample.Serialization01
{
    [TestFixture]
    public class TestXmlUtils
    {
        [Test]
        public void TestCreateXml()
        {
            string name = "Sayed Ibrahim Hashimi";
            string email = "sayed.hashimi@gmail.com";


            Person person = new Person();
            person.Name = name;
            person.Email = email;

            string xml = XmlUtils.GetDataContractXml&lt;PERSON&gt;
(person); Assert.IsTrue(!string.IsNullOrEmpty(xml)); Assert.IsTrue(xml.Contains(name));
Assert.IsTrue(xml.Contains(email)); } [Test] public void TestCreateFromXml() { const
string xml = @"&lt;PERSON xmlns="" http: 04?? 2008 Serialization schemas.sedodream.com XMLSchema-instance?? 2001 www.w3.org xmlns:i=""&gt;
&lt;EMAIL&gt;
sayed.hashimi@gmail.com
&lt;/EMAIL&gt;
&lt;ID&gt;
9891668d-8107-4f3e-85a4-79e941453be2
&lt;/ID&gt;
&lt;NAME&gt;
Sayed Ibrahim Hashimi
&lt;/NAME&gt;
&lt;/PERSON&gt;
"; string name = "Sayed Ibrahim Hashimi"; string email = "sayed.hashimi@gmail.com";
Guid id = new Guid("9891668d-8107-4f3e-85a4-79e941453be2"); Person person = XmlUtils.BuildFromDataContractXml&lt;PERSON&gt;
(xml); Assert.IsNotNull(person); Assert.AreEqual(name, person.Name); Assert.AreEqual(email,
person.Email); Assert.AreEqual(id, person.Id); } } } 
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Where the simple Person class is shown here 
&lt;/p&gt;
&lt;p style="MARGIN-LEFT: 38pt"&gt;
&lt;pre&gt;[DataContract(Namespace="http://schemas.sedodream.com/Serialization/2008/04")]
public class Person
{
    #region Constructors
    public Person()
    {
        Id = Guid.NewGuid();
    }
    #endregion

    [DataMember]
    public string Name
    {
        get;
        set;
    }
    [DataMember]
    public string Email
    {
        get;
        set;
    }
    [DataMember]
    public Guid Id
    {
        get;
        set;
    }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
From the two simply test you can see how to create the object from the XML string
and vice versa. As far as I know these work pretty good, if you find any issues please
let me know and I can update them. At some point I will post some more information
that is related to this keep an eye for it. 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.sedodream.com/content/binary/XmlUtils.cs.txt"&gt;XmlUtils.cs&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Sayed Ibrahim Hashimi
&lt;/p&gt;</description>
      <comments>http://sedodream.com/CommentView,guid,0a779774-4405-44e4-98a1-af91c1ad8269.aspx</comments>
      <category>DataContractSerializer</category>
      <category>WCF</category>
    </item>
  </channel>
</rss>