Dan Rigsby - Coding Up Style

.Net, C#, & Wcf Development

Archive for the '.Net' Category


JavaScriptSerializer Undeprecated in .NET 3.5 SP1

Posted by Dan Rigsby on 28th May 2008

According to Scott Guthrie (see comments in this post) it appears that the JavaScriptSerializer will be undeprecated in .NET 3.5 SP1.  In was deprecated in .Net 3.5 and the DataContractJsonSerializer replaced it.  Each of these serializers serializes to Json and each have their pluses and minuses:

  • JavaScriptSerializer supports anonymous types.
  • JavaScriptSerializer works with plain strings so it can be easier to use.
  • DataContractJsonSerializer can serialize DateTimes into UTC format.   Very important over the web!

I guess the big question I have is, do we really need both? Isn’t there a way to combine these into one serializer?

What about the act of undeprecating a class?  Do you think this is a good thing?

See these links for more information about the DataContractJsonSerializer:

Posted in .Net | 2 Comments »

Sexagesimal Conversions in .Net

Posted by Dan Rigsby on 30th April 2008

No, that is not a dirty word, and yes, it is fun to say. [sek-suh-jes-uh-muhl]

7520012074151Sexagesimal is a base-60 number system much like our own base-10 decimal system.  Throughout history different cultures have chosen different base numbering systems based on things they considered common or sacred.  Many people today recognize numbers as always being base-10, and it can be quite difficult to explain a different numbering system to a child.  Those of us in computer science are quite use to a base-2 (binary) system.  Some of the more common historic number systems are:

  1. Base-5 (quinary): This system has been popular because five can easily be represented by the five fingers on one hand
  2. Base-8 (octal): Some cultures used only their fingers to count and used the thumbs as place holders.  While other cultures, such as the Yuki Native American tribe of Northern California , counted the spaces between the fingers.  The Yuki actually started counting with 0 as well (much like C based languages).  So the numbers 0-7 were counted on their fingers.
  3. Base-10 (decimal): We are all familiar with the base-10 system which is almost universally used around the world.  Historical this is based on the fact that humans have ten fingers on which to count.
  4. Base-12 (duodecimal):  This system is based on the knuckles of the four fingers.  Each finger has 3 knuckles and the thumb is used as the place holder.  Twelve is also an important unit in British measurement such as 12 inches in a foot, 12 pennies to a shilling, 12 numbers used in our time units, etc.
  5. Base-20 (vigesimal): The base-20 system originates from the combination of ten fingers and ten toes on which to count.  This is most widely known to be used by the Mayan civilization.
  6. Base-60 (sexigesimal): The base-60 system dates back to the Sumerians and the early cultures of Mesopotamia.  It’s hard to say where this system originated from, but common belief is that it is a combination of the base-10 and base-12 systems.

So why is the base-60 system still important to us today?  Well for one, there are 60 seconds in a minute and 60 minutes in an hour.  This measurement one of the Sumerian’s lasting impressions today.  Their calendar and type systems have been adopted and modified throughout the Asia and Europe.  We can blame the Sumerian’s for not having enough time in the day.

180px-Geographic_coordinates_sphere.svg Another popular use for the base-60 system is in angular measure in our spherical coordinate system of the Earth.  A degree is divided into 60 minutes and a minute is divided into 60 seconds.  Our system of Latitudes and Longitudes is expressed in these terms.  With the popularity of geo-spatial and mapping tools such as Google Maps and Microsoft Live Maps, it has become important to be able to convert from degrees/minutes/seconds into a decimal notation and vice versa.

Example:

(49°30′02"N, 123°30′30")

 

49 degrees, 30 minutes, and 2 seconds by 123 degrees, 30 minutes, and 30 seconds

Below is a utilities class that I originally wrote for an astronomical observatory simulation application called StellarResults (which is available on codeplex).  This program would simulate observatories around the world and what astronomical objects they could see at a give time of day.  I soon realized that I needed to push this library down to a more basic level so that I could use it for other geo-spatial calculations such as working with geo-coded locations, or entering locations into a database.  Libraries like this will also be useful when working with the new spatial database features in Microsoft SQL Server 2008.

public static class GISUtilities
{
    #region Sexagesimal
    /// <summary>
    /// Converts from degrees, minues, seconds to a double.
    /// </summary>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static double ConvertSexagesimalToDouble(
        int degrees,
        int minutes,
        int seconds)
    {
        return ((double)degrees % 360) + ((double)minutes / 60) + ((double)seconds / 3600);
    }

    /// <summary>
    /// Converts from degrees, minues, seconds to a string.
    /// </summary>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static string ConvertSexagesimalToString(
        int degrees,
        int minutes,
        int seconds)
    {
        return String.Format(
            "{0}° {1}’ {2}”",
            degrees.ToString(),
            minutes.ToString(),
            seconds.ToString());
    }

    /// <summary>
    /// Converts from a double to degrees, minues, seconds.
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    public static void ConvertDoubleToSexagesimal(
        double value,
        out int degrees,
        out int minutes,
        out int seconds)
    {
        degrees = (int)value;
        minutes = (int)((value - degrees) * 60);
        seconds = (int)((value - degrees - (minutes / 60)) * 3600);
    }
    #endregion Sexagesimal

    #region HMS
    /// <summary>
    /// Converts from hours, minues, seconds to a double.
    /// </summary>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static double ConvertHMSToDouble(
        int hours,
        int minutes,
        int seconds)
    {
        return ((double)hours % 360) * 15 + ((double)minutes / 60) * 15 + ((double)seconds / 3600) * 15;
    }

    /// <summary>
    /// Converts from hours, minues, seconds to a string.
    /// </summary>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static string ConvertHMSToString(
        int hours,
        int minutes,
        int seconds)
    {
        return String.Format(
            "{0}h {1}m {2}s",
            hours.ToString(),
            minutes.ToString(),
            seconds.ToString());
    }

    /// <summary>
    /// Converts from a double to hours, minues, seconds.
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    public static void ConvertDoubleToHMS(
        double value,
        out int hours,
        out int minutes,
        out int seconds)
    {
        double totalseconds = value / 15 * 3600;

        hours = (int)Math.Truncate(totalseconds / 3600);
        minutes = (int)Math.Truncate((totalseconds - hours * 3600) / 60);
        seconds = (int)Math.Truncate(totalseconds - (hours * 3600) - (minutes * 60));
    }
    #endregion HMS
}
 

So a conversion from Latitude or Longitude to a double would look something like this:

double latitude = GISUtilities.ConvertSexagesimalToDouble(100, 34, 20);
 
There are also methods in this library to convert between hours/minutes/seconds as well as the degree/minutes/seconds primarily used in geo-spatial calculations.
 

kick it on DotNetKicks.com

 

Posted in .Net | 3 Comments »

How to grayout an image in .Net

Posted by Dan Rigsby on 28th March 2008

Here is a handy method for making a grayscale version of an image.  I use this method a lot to grayout icons that I wish to show as disabled.  All you need to do is pass in the image and it will apply a grayscale over it.  The key to getting all of this to work is the ColorMatrix.  There is a detailed article about how this works on codeproject: http://www.codeproject.com/KB/GDI-plus/colormatrix.aspx.

public static void ApplyGrayscale(
    ref Image image)
{
    // Build color matrix set at 1/3
    ColorMatrix matrix = new ColorMatrix();
    matrix[0, 0] = 1/3f;
    matrix[0, 1] = 1/3f;
    matrix[0, 2] = 1/3f;
    matrix[1, 0] = 1/3f;
    matrix[1, 1] = 1/3f;
    matrix[1, 2] = 1/3f;
    matrix[2, 0] = 1/3f;
    matrix[2, 1] = 1/3f;
    matrix[2, 2] = 1/3f;

    // Create image attributes that will applied to the image
    ImageAttributes attributes = new ImageAttributes();
    attributes.SetColorMatrix(matrix);

    Graphics g = null;
    try
    {
        // Get the graphics object from the image
        g = Graphics.FromImage(image);

        // Redraw the image on the graphics object using the grayscale color matrix
        g.DrawImage(image,
            new Rectangle(0, 0, image.Width, image.Height),
            0,
            0,
            image.Width,
            image.Height,
            GraphicsUnit.Pixel,
            attributes);
    }
    finally
    {
        if (g != null)
        {
            g.Dispose();
        }
    }
}

 

Here are some sample before and after images (of my daughter Claire):

claire clairegray

 

Here is another example with a more typical line-of-business image:

disk_blue disk_bluegray

 

To make this easier to try out or use, I have wrapped the method into a executable as well.  You can download the source for this here: http://www.danrigsby.com/Files/Rigsby.ImageUtilities.Grayscale.zip

To run the program, compile the code and execute the exe file while passing in the source file name and the file name you want to save the new grayscaled image to, like this:

Rigsby.ImageUtilities.Grayscale.exe "c:\Claire.jpg" "c:\Claire-Gray.jpg"
 

Posted in .Net, Common Libraries | 9 Comments »

Disposable Base Class

Posted by Dan Rigsby on 15th March 2008

trashcanMany classes are built that implement System.IDisposable, which is a good thing.  This pattern makes for a good design to clean up your objects and can be used by the using statement to easily dispose of your objects.  This article already assumes that you know the basics of the Dispose Pattern. However sometimes having just a Dispose() method isn’t always enough.  Many times you a combination of a Disposed event, a void Dispose(bool disposing) method for use by a deconstructor, a boolean flag to check if the object IsDisposed, and maybe a method to check if the object is disposed that can throw an exception.  Some "best practices" often dictate that you should be using some of these additional things.  You may be writing this logic over and over again for each class, or you might start with a basic IDisposable pattern and weeks later you decide to refactor it to add in something like the boolean flag for IsDisposed.

After facing these same issues for awhile, I decided to put together a simple Diposable base class with all of the recommended patterns for using Disposable.  Of course, this can’t always be used since you might already have a base class.  But many times a class will derive from IDisposable and nothing else.  This is just screaming for a Disposable base class that encapsulates this logic!  For classes that already have a base class, I also have a code snippet to include everything that’s in the base class.

Here are the features of the Disposable Base Class and Code Snippet:

  1. void Dispose() Method - This is just the standard Dispose method that is defined in the IDisposable interface.
  2. void Dispose(bool disposing) Method - This method is called from the Dispose() method passing in true.  Its called from the deconstructor using false.  This is the method that you should override in your parent class and check if disposing is true before disposing of managed code.  The reason for this is that the deconstructor would have already disposed of the managed code, so you shouldn’t try to do it again.  If the deconstrutor called this method, you should only dispose of unmanaged code.
  3. void CheckDisposed() Method - This method is marked protected and is used by the parent class to check if the object is disposed.  It will throw an ObjectDisposedException if necessary.
  4. bool IsDisposed Property - A simple property to check whether or not this object has been disposed yet.
  5. Disposed Event - This event is fired when the object has been disposed.

To use the base class, you just override the Dispose(bool disposing) method. An example of this base class in use could look like this:

public class MyClass : Disposable
{
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Dispose any managed code here
        }

        // Dispose any unmanaged code here

        base.Dispose(disposing);
    }
}

 

Here is the base class:

using System;
using System.ComponentModel;

namespace Rigsby
{
    /// <summary>
    /// Represents a basic disposable class.
    /// </summary>
    public abstract class Disposable : IDisposable
    {
        #region Private Properties
        private bool m_IsDisposed = false;
        #endregion Private Properties

        #region Public Properties
        /// <summary>
        /// Gets a value indicating whether this instance is disposed.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is disposed; otherwise, <c>false</c>.
        /// </value>
        [Browsable(false)]
        public bool IsDisposed
        {
            get
            {
                return m_IsDisposed;
            }
        }
        #endregion Public Properties

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="Disposable"/> class.
        /// </summary>
        public Disposable()
        {
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="Disposable"/> is reclaimed by garbage collection.
        /// </summary>
        ~Disposable()
        {
            Dispose(false);
        }
        #endregion Constructors

        #region IDisposable Members
        private event System.EventHandler m_Disposed;

        /// <summary>
        /// Occurs when this instance is disposed.
        /// </summary>
        public event System.EventHandler Disposed
        {
            add
            {
                m_Disposed += value;
            }
            remove
            {
                m_Disposed -= value;
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public void Dispose()
        {
            if (!m_IsDisposed)
            {
                this.Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    EventHandler handler = m_Disposed;
                    if (handler != null)
                    {
                        handler(this, EventArgs.Empty);
                        handler = null;
                    }
                }
            }
            finally
            {
                m_IsDisposed = true;
            }
        }
        #endregion IDisposable Members

        /// <summary>
        ///    <para>
        ///        Checks if the instance has been disposed of, and if it has, throws an <see cref="ObjectDisposedException"/>; otherwise, does nothing.
        ///    </para>
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        ///    The instance has been disposed of.
        ///    </exception>
        ///    <remarks>
        ///    <para>
        ///        Derived classes should call this method at the start of all methods and properties that should not be accessed after a call to <see cref="Dispose()"/>.
        ///    </para>
        /// </remarks>
        protected void CheckDisposed()
        {
            if (m_IsDisposed)
            {
                string typeName = GetType().FullName;

                // TODO: You might want to move the message string into a resource file
                throw new ObjectDisposedException(
                    typeName,
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                        "Cannot access a disposed {0}.",
                        typeName));
            }
        }
    }
}

Here is the code snippet version, or download it here.  If you use the snippet, you will want to manually change your class to derive from the IDisposable interface, then add this snippet.

<?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">   <CodeSnippet Format="1.0.0">     <Header>       <Title>IDisposable</Title>       <Shortcut>       </Shortcut>       <Description>Implements the IDisposable interface with additional best practices.</Description>       <Author>Dan Rigsby</Author>     </Header>     <Snippet>       <Code Language="csharp"><![CDATA[        #region IDisposable Members
        private bool m_IsDisposed = false;
        private event System.EventHandler m_Disposed;

        /// <summary>
        /// Gets a value indicating whether this instance is disposed.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is disposed; otherwise, <c>false</c>.
        /// </value>
        [System.ComponentModel.Browsable(false)]
        public bool IsDisposed
        {
            get
            {
                return m_IsDisposed;
            }
        }

        /// <summary>
        /// Occurs when this instance is disposed.
        /// </summary>
        public event System.EventHandler Disposed
        {
            add
            {
                m_Disposed += value;
            }
            remove
            {
                m_Disposed -= value;
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public void Dispose()
        {
            if (!m_IsDisposed)
            {
                this.Dispose(true);
                System.GC.SuppressFinalize(this);
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    System.EventHandler handler = m_Disposed;
                    if (handler != null)
                    {
                        handler(this, System.EventArgs.Empty);
                        handler = null;
                    }
                }
            }
            finally
            {
                m_IsDisposed = true;
            }
        }

        /// <summary>
        ///    <para>
        ///        Checks if the instance has been disposed of, and if it has, throws an <see cref="ObjectDisposedException"/>; otherwise, does nothing.
        ///    </para>
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">
        ///    The instance has been disposed of.
        ///    </exception>
        ///    <remarks>
        ///    <para>
        ///        Derived classes should call this method at the start of all methods and properties that should not be accessed after a call to <see cref="Dispose()"/>.
        ///    </para>
        /// </remarks>
        protected void CheckDisposed()
        {
            if (m_IsDisposed)
            {
                string typeName = GetType().FullName;

                // TODO: You might want to move the message string into a resource file
                throw new System.ObjectDisposedException(
                    typeName,
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                        "Cannot access a disposed {0}.",
                        typeName));
            }
        }
        #endregion IDisposable Members]]></Code>     </Snippet>   </CodeSnippet> </CodeSnippets>

kick it on DotNetKicks.com

Posted in .Net, Common Libraries | 1 Comment »

Generic Notify Property Change Controller

Posted by Dan Rigsby on 14th March 2008

This is another example of a class you could put into a common library.   Suppose I want to create a class that fires an event every time the value of a property changes.  I could implement such a class like this:

public class MyClass : INotifyPropertyChanged
{
    private string m_Text;
    public string Text
    {
        get { return m_Text; }
        set
        {
            if (m_Text != value)
            {
                m_Text = value;
                OnPropertyChanged(“Text”);
            }
        }
    }

    protected virtual void OnPropertyChanged(
        string propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        if (handler != null)
        {
            m_PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region INotifyPropertyChanged Members
    private event PropertyChangedEventHandler m_PropertyChanged;
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyChanged += value; }
        remove { m_PropertyChanged -= value; }
    }
    #endregion INotifyPropertyChanged Members
}
 
If you have a large class library and a lot of properties, this can add up to a lot of code.  There is an easier way to do this at a very small cost of performance.  Ill show the code for the PropertyController class at the end of this post, but this is an example of what the above code could look like:
 
public class MyClass : INotifyPropertyChanged
{
    private PropertyController m_PropertyController
    private string m_Text;
    public string Text
    {
        get { return m_Text; }
        set { m_PropertyController.ChangeProperty(“Text”, value);
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyController.PropertyChanged += value; }
        remove { m_PropertyController.PropertyChanged -= value; }
    }
    #endregion INotifyPropertyChanged Members
}

 

That is significantly less code and much cleaner.  Just, imagine if I had a class library with 30 classes.

You could also do this:

set { m_PropertyController.ChangeProperty(“Text”, value);

 

instead of:

set { m_PropertyController.ChangeProperty(value);

 

The cost of doing this is that the PropertyController has to look at the stack trace, but depending on what you are doing, this may be worth the cost.

The ChangeProperty method returns a boolean to indicate whether or not the value was changed.  So inside your property code you could react depending on the result.

Here is the complete PropertyController class.  Feel free to use it, modify it, ignore it, etc. You could even use this class and not even expose the PropertyChanged event, if you don’t need it.

public class PropertyController : INotifyPropertyChanged, IDisposable
{
    private Dictionary<string, PropertyInfo> m_Properties =
        new Dictionary<string, PropertyInfo>();

    public PropertyController()
    {
    }

    #region INotifyPropertyChanged Members
    private event PropertyChangedEventHandler m_PropertyChanged;

    public event PropertyChangedEventHandler PropertyChanged
    {
        add
        {
            m_PropertyChanged += value;
        }
        remove
        {
            m_PropertyChanged -= value;
        }
    }
    #endregion INotifyPropertyChanged Members

    protected PropertyInfo GetProperty(string propertyName)
    {
        if (!m_Properties.ContainsKey(propertyName))
        {
            m_Properties.Add(propertyName, this.GetType().GetProperty(propertyName));
        }

        return m_Properties[propertyName];
    }

    public virtual bool ChangeProperty(object newValue)
    {
        return ChangeProperty(new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name, newValue);
    }

    public virtual bool ChangeProperty(string propertyName, object newValue)
    {
        System.Reflection.PropertyInfo property =
            GetProperty(propertyName);

        if (property.GetValue(this, null) != newValue)
        {
            property.SetValue(this, newValue, null);
            OnPropertyChanged(propertyName);

            return true;
        }

        return false;
    }

    public virtual void OnPropertyChanged(
        string propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        if (handler != null)
        {
            m_PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region IDisposable Members
    public void Dispose()
    {
        m_PropertyChanged = null;
    }
    #endregion IDisposable Members
}

Posted in .Net, Common Libraries | 2 Comments »

.Net EventHandlers - Best Practices

Posted by Dan Rigsby on 9th March 2008

One question that comes up a lot is, “How can I can clean up my event handlers in an object?”.  What are the best practices for cleaning up event handlers?  This is actually a pretty important question.  One of the number one reasons for memory drains in .Net is because event handlers aren’t removed.   For instance: if ObjectA is registered for an event on ObjectB and ObjectB goes out of scope and should be garbage collected, it can’t because ObjectA still has a reference to do it via the event handler.  Get into some complex circular patterns, and you are just eating memory.

In an ideal world every time an object registers for an event, it should remove it when that object is destroyed, but what happens when the object it is listening for events on should be destroyed?

One way I use to get around this, is to declare the event as private, then expose it through a public property with Add and Remove accessor methods like so:

private System.EventHandler m_MyEvent;  

public event System.EventHandler MyEvent
{
    add
    {
        m_MyEvent += value;
    }
    remove
    {
        m_MyEvent -= value;
    }
}

Then in your Dispose() method or in some other clean up method, you can set the private event to null to remove all subscriptions to the event.

public void Dispose()
{
    m_MyEvent = null;
}

By setting the private event to null, you are basically telling it to remove any events listening to it. So that there are no more references to the object, so it can be disposed cleaning. This is similar to getting the invocation list of the event and removing all of the delegates:

foreach(System.EventHandler e in MyEvent.GetInvocationList())
{
    MyEvent -= e;
}

You could also use WeakReference objects which can be used to bypass this same situation.  However, it does involve rewriting a good chuck of code, and take a bit of thought to decide where to put it and where not to.  Using the method above can work with a WeakReference as well.  The nice thing about the method above is that the object is cleaning itself up and doesn’t rely on the GC or something else to do its dirty work.

Posted in .Net | No Comments »

XmlSerializer vs DataContractSerializer: Serialization in Wcf

Posted by Dan Rigsby on 7th March 2008

wwwf The XmlSerializer has been in .Net since version 1.0 and has served us well for everything from Remoting, Web Services, serializing to a file, etc. However in .Net 3.0 the DataContractSerializer came along.  And all of a sudden a lot of guidance suggests that we should use it over the old tried and true XmlSerializer. Wcf even uses this as the default mechanism for serialization.  The question is, “Is it really better?”.  The verdict is yes, and no.  Like most things it depends on your implementation and what you need.  For Wcf, you should prefer to use the DataContractSerializer.  If you need full control over how the xml looks though, you should go back to the XmlSerializer.

Lets look at the both of these in detail and leave it up to you to decide which is best for your implementation.  Here are a few of the advantages and disadvantages of each of them:

XmlSerializer DataContractSerializer
Advantages:
1. Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize, only those you don’t wan to serialize2. Full control over how a property is serialized including it it should be a node or an attribute

3. Supports more of the XSD standard

Disadvantages:
1. Can only serialize properties

2. Properties must be public

3. Properties must have a get and a set which can result in some awkward design

4. Supports a narrower set of types

5. Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too

Advantages:
1. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize

2. Because it is opt in you can serialize not only properties, but also fields.  You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)

3. Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.

4. Can understand the SerializableAttribute and know that it needs to be serialized

5. More options and control over KnownTypes

Disadvantages:
1. No control over how the object is serialized outside of setting the name and the order

What is Serialization?

Let’s start with the basics.  Serialization has been a key part of .Net since version 1.  It is basically the process of converting an object instance into a portable and transferable format.  The objects can be serialized into all sorts of formats.  Serializing to Xml is most often used for its interoperability.  Serializing to binary is useful when you want to send the object from one .Net application to another.  .Net even supports the interfaces and base classes to build your own serializes. There are libraries out there to serialize to comma delimited strings, JSON, etc.

Deserialization is basically the reverse of serialization.  Its the process of taking some data (Xml, binary, etc) and converting it back into an object.

What is the XmlSerialzer?

For those that may not be familiar with System.Xml.Serialization.XmlSerializer let’s go over it briefly.  This is the xml serializer that has been around since .Net version one.  To serialize or deserialize an object, you basically just need to create an instance of the XmlSerializer for the type you want to work with, then just call Serialize() or Deserialize().  It works with streams, so you could serialize to any stream such as an MemoryStream, FileStream, etc.

// Create serializer for the type
System.Xml.Serialization.XmlSerializer xmlSerializer =
    new System.Xml.Serialization.XmlSerializer(typeof(MyType)); 

// Serialize from an object to a stream
xmlSerializer.Serialize(stream, myInstanceOfMyType); 

// Deserialize from a stream to an object
myInstanceOfMyType = (MyType)xmlSerializer.Deserialize(stream);

However not just any object can be serialized.  It supports a number of the base types in .Net and most custom types.  Many people think that the SerializableAttribute is required on the class in order for it to be serializable by the XmlSerializer, but this is not the case.  It is good practice to use the SerializableAttribute, but it not required.  As long as your class contains all types that the serializer understands, then it will work.  You need to break out IXmlSerializable to implement your own custom serialization for types that the XmlSerializer cannot understand.  Any public property that is of a known serializable type and has a get and set will be serialized by the XmlSerialzer.  This can be referred to as an “opt-out” approach, because you chose what you don’t want to include, not what you want to include.

There are a number of attributes you can use in your class to change how it is serialized:

  1. System.Xml.Serialization.XmlIgnoreAttribute: This is used to mark a public property as “not to be serialized”. This is the “opt-out” approach used by the XmlSerializer.  There are no properties on this attribute.
  2. System.Xml.Serialization.XmlRootAttribute: This is used on the class itself to change the name or namespace of the root node. The following properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.
  3. System.Xml.Serialization.XmlAttributeAttribute: Serialize the property as an xml attribute.  You can specify things such as the name to use (instead of the property name).  The following properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.
  4. System.Xml.Serialization.XmlElementAttribute: Serialize the property as an xml element.  You can specify things such as the name to use (instead of the property name), whether or not to serialize it if it is null, the order to serialize the property in relative to other properites, etc. The following properties are supported on the attribute:
    1. ElementName: Gets or sets the name of the XML element.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
    3. Form: Gets or sets a value that indicates whether the XML attribute name generated by the XmlSerializer is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. IsNullable: Gets or sets a value that indicates whether the XmlSerializer must serialize a member that is set to nullNothingnullptra null reference (Nothing in Visual Basic) as an empty tag with the xsi:nil attribute set to true.
    6. Order: Gets or sets the explicit order in which the elements are serialized or deserialized.
    7. Type: Gets or sets the complex type of the XML attribute.
    8. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.

Here is an example class setup to use the XmlSerializer.  The only thing fancy here is that I don’t want to serialize the Social Security number:

[System.Serializable]
public class Individual
{
    private string m_FirstName;
    private string m_LastName;
    private int m_SocialSecurityNumber; 

    public string FirstName
    {
        get { return m_FirstName; }
        set { m_FirstName = value; }
    } 

    public string LastName
    {
        get { return m_LastName; }
        set { m_LastName = value; }
    } 

    [System.Xml.Serialization.XmlIgnore]
    public int SocialSecurityNumber
    {
        get { return m_SocialSecurityNumber; }
        set { m_SocialSecurityNumber = value; }
    } 

    public Individual()
    {
    }
    public Individual(string firstName, string lastName)
    {
        m_FirstName = firstName;
        m_LastName = lastName;
    }
}

What is the DataContractSerializer?

The System.Runtime.Serialization.DataContractSerializer is new in .Net 3.0 and was designed for contract-first development and speed.  Specifically it was brought in to be used by Wcf, but can be used for general serialization as well. Using the DataContractSerializer isn’t that much different than using the XmlSerializer.  There are a few more options, but the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize instead of a Deserialize() method.  It works with the same types of streams, so you can write to memory, files, etc.

DataContractSerializer dataContractSerializer =
    new DataContractSerializer(typeof(MyType)); 

// Serialize from an object to a stream
dataContractSerializer.WriteObject(stream, myInstanceOfMyType); 

// Deserialize from a stream to an object
myInstanceOfMyType = (MyType)dataContractSerializer.ReadObject(stream);

One thing to note: before you can use the DataContactSeriliazer, you must include a reference to System.Runtime.Serialization.  mscorelib gives you some parts of System.Runtime.Serialization, but you must include this reference to get the DataContactSeriliazer and the associated attributes.

image

Again, not just any object can be serialized.  It supports a number of the base types in .Net and most custom types.  One nice advantage that the DataContractSerializer has over the XmlSerializer is that it understands the SerializableAttribute and classes built for the XmlSerializer or ISerializable.  So if your class is declared with an DataContactAttribute and it contains a type that uses the SerializableAttibute, all will be well.  Unlike the XmlSerializer though you must define either the SerializableAttribute or the DataContractAttributeon the class in order for it to be serializable by the DataContractSerializer.

The DataContactSerializer implements an “opt-in” approach.  The basically means that you have to explicitly say what will be serialized by adding the DataMemeberAttribute to it.  The nice thing about this is that this attribute can be applied to fields and well as properties, you can set it on any access modified (private, protected, etc) not just public, and you can use it on properties that do not have a “set”.  However if you label a property that doesn’t have a “set”, then you can only serialize that property.  You won’t be able to deserialize it since it has no idea how to set the property.  This also means you cant use it for communication over Wcf.  But you can still use a “private set” to ensure that your model is clean.  However, you cannot specify that properties should be xml attributes and control other more complex things about how the xml will look.  It hurts not having this flexibility, but because of this rigidness, the format is highly predictable and the serializer can make some big optimizations.  The DataContractSerializer can serialize and deserialize about 10% faster than the XmlSerializer.  This can be pretty significant if you are working with a lot of data.

There are really only 2 attributes to use in your class:

  1. System.Runtime.Serialization.DataContactAttribute: Declares that the class is serializable and allows you to specify the namespace and name to serialize it as.  This is similar to a combination of the SerializableAttribute and XmlRootAttribute in the XmlSerializer. The following properties are supported on the attribute:
    1. Name: Gets or sets the name of the data contract for the type.
    2. Namespace: Gets or sets the namespace for the data contract for the type.
    3. TypeId:When implemented in a derived class, gets a unique identifier for this Attribute.
  2. System.Runtime.Serialization.DataMemberAttribute: This is used to declare a property or a field to be serialized.  This can work with any access modifier.  The following properties are supported on the attribute:
    1. EmitDefauleValue: Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.
    2. IsRequired: Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializing.
    3. Name: Gets or sets a data member name.
    4. Order: Gets or sets the order of serialization and deserialization of a member.  This can be pretty powerful if you have fields that might depend on one another and you really need to define the order that the properties are serialize and deserialized in.
    5. TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.

If you are going to work with the DataMemberAttribute, here is an concise post about best practices around it: http://blogs.msdn.com/drnick/archive/2008/02/22/datamember-best-practices

Below example class setup to use the DatContractSerializer.  Notice that I am explicitly setting the DataMemberAttribute on the properties I want to serialize, but not on the others.

[DataContract]
public class Individual
{
    private string m_FirstName;
    private string m_LastName;
    private int m_SocialSecurityNumber; 

    [DataMember]
    public string FirstName
    {
        get { return m_FirstName; }
        set { m_FirstName = value; }
    } 

    [DataMember]
    public string LastName
    {
        get { return m_LastName; }
        set { m_LastName = value; }
    } 

    public int SocialSecurityNumber
    {
        get { return m_SocialSecurityNumber; }
        set { m_SocialSecurityNumber = value; }
    } 

    public Individual()
    {
    }
    public Individual(string firstName, string lastName)
    {
        m_FirstName = firstName;
        m_LastName = lastName;
    }
}

 

One other important thing to talk about with the DataContractSerializer are the ServiceKnownTypeAttribute and KnownTypeAttribute attributes.  These are similar to the XmlIncludeAttribute used by the XmlSerializer.  When used in Wcf, these identify what types should be represented in the WSDL that is generated.

The KnownTypeAttribute specifies types that should be recognized by the DataContractSerializer when serializing and deserializing a type.  It is applied to a class and basically specifies what other types are used in the class.  You don’t need to specify known .Net types, but any custom classes should be added here.  This attribute can be used multiple times to identify multiple types.

[DataContract]
[KnownType(typeof(MyOtherType))]
public class MyType
{
    [DataMember]
    public MyOtherType TheOtherType;
} 

[DataContract]
public class MyOtherType
{
    [DataMember]
    public string MyValue;
}

The ServiceKnownTypeAttribute specifies known types to be used by a service when serializing or deserializing.  It is applied to a ServiceContract or to an OperationContract and specifies what types are used in the methods.  Again (like the KnownTypeAttribute), you don’t need to specify known .Net types and this attribute can be used multiple times to identify multiple types.

[ServiceContract]
[ServiceKnownType(typeof(MyType))]
[ServiceKnownType(typeof(MyOtherType))]
public interface MyService
{
    [OperationContract]
    [ServiceKnownType(typeof(YetAnotherType))]
    void MyMethod();
}

What about the NetDataContractSerializer?

I haven’t really mentioned this yet because it is just like the DataContractSerializer, but there is also a System.Runtime.Serialization.NetDataContractSerializer.  It differs from the DatContactSerializer in that it includes CLR type information in the serialized xml, whereas the DataContractSerializer does not.  So it can only work if the serializing and derserializing ends share the same CLR types.   The nice thing about this serializer is that since the CLR type information is sent around, you don’t have to implement the ServiceKnownTypeAttirbute or KnownTypeAttribute. Like the DataContractSerializer it can work serialize types that implement either the DataContractAttribute, SerializableAttribute, or ISerializable.

I don’t recommend using this serializer often.  If possible you should declare your known types explicitly for better understand of the code and of course for the greater interoperability.

Why another xml serializer?

So why the need to even create another xml serializer? The XmlSerializer has served us well over the years.  Well part of it it speed.  Since the DataContracts are faster to serialize because the structure is predictable and can be more highly optimized.  This results in about a 10% performance gain.  If you are working with pure Wcf the gain in speed is probably worth the trade off in loss of control over what the Xml is to look like.  Sometimes you might need to control what the xml looks like to get it to fit to some other schema.  If that is the case, then you will want to switch to the XmlSerializer.

There is more to the story.  Microsoft wants us think of in terms of “Contracts” with Wcf.  We often hear the term “Contract First Development”.  Some of this principal is already in play by forcing all Wcf Services to be defined in an interface (contract).  In the old days of pure WebServices, you could just tag a class as WebService and you didn’t need a separate interface or contract.  In some respects, the DataContractSerializer is pushing us down this route too.  By declaring a class as a DataContract and explictily setting the DataMembers, you are building a contract of how the class should look.  One could argue that you could do this through the Serializable attribute, however you don’t define what goes in the contract. Instead you only specify what isn’t suppose to be serialized and the serializer decides what is should serialize.  There is no way to look at the class or use reflection and really get a good feel for the data contract for the class.  While with the DataContract and DataMember attributes, you could use reflection to see exactly what the contract is.

How to change Wcf to use a different serializer?

By default Wcf uses the DataContactSerializer, so if you want to use it, you need to do nothing else.  If you want to use the XmlSerializer through, all you need to do is add the System.ServiceModel.XmlSerializerFormatAttribute to the contact interface.  The nice thing about this attribute is that it can be applied to the entire service contract, or just to an operation contract.  So you could keep the entire service as a whole using the DataContractSerializer, but only the methods you chose to use the XmlSerializer.

[ServiceContract]
[XmlSerializerFormat]
public interface MyService
{
    [OperationContract]
    [XmlSerializerFormat]
    void MyMethod();
}

You can also set the service to use the XmlSerilizer by default, but specify which methods use the DataContractSerializer with the help of the System.ServiceModel.DataContractFormatAttribute:

[ServiceContract]
[XmlSerializerFormat]
public interface MyService
{
    [OperationContract]
    [DataContractFormat]
    void MyMethod();
}

 

Now what about changing to use the NetDataContractSerializer.  Or what if I want to use a different serializer or create my own? In order to do this you need to create a custom operation behavior using the IOperationBehavior interface and the Attribute class.

Here is an example of a custom operation behavior written to use the NetDataContractSerialier.  You could use this, build your own, or modify it to work with a different serializer.

public class NetDataContractFormatAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
    {
    } 

    public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
    {
        ReplaceDataContractSerializerOperationBehavior(description);
    } 

    public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
    {
        ReplaceDataContractSerializerOperationBehavior(description);
    }
    public void Validate(OperationDescription description)
    {
    } 

    private static void ReplaceDataContractSerializerOperationBehavior (OperationDescription description)
    {
        DataContractSerializerOperationBehavior dcs = description.Behaviors.Find<DataContractSerializerOperationBehavior>(); 

        if (dcs != null)
            description.Behaviors.Remove(dcs); 

        description.Behaviors.Add(new NetDataContractSerializerOperationBehavior(description));
    } 

    public class NetDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
    {
        private static NetDataContractSerializer serializer = new NetDataContractSerializer(); 

        public NetDataContractSerializerOperationBehavior(OperationDescription operationDescription) : base(operationDescription) { } 

        public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
        {
            return NetDataContractSerializerOperationBehavior.serializer;
        } 

        public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
        {
            return NetDataContractSerializerOperationBehavior.serializer;
        }
    }
}Once you have this you can just mark up your service like before using the new attribute:

[ServiceContract]
[NetDataContractSerializerFormat]
public interface MyService
{
    [OperationContract]
    void MyMethod();
}

Once you have this you can just mark up your service like before using the new attribute:

[ServiceContract]
[NetDataContractSerializerFormat]
p