Other Posts in IO

  1. Uploading and Downloading a File to an FTP Server Using C#
  2. Deserializing/Serializing SOAP Messages in C#

Deserializing/Serializing SOAP Messages in C#

7/24/2009

For those of you that don't know what SOAP is, SOAP is an XML based syntax that allows programs communicate with one another. In other words, just like RSS, etc. it is just another XML document with specific syntax. There really isn't much to it, but serializing/deserializing them can be a pain. Luckily for us .Net has a built in class for us. Specifically in the System.Runtime.Serialization.Formatters.Soap namespace (you may need to add a reference to it). So let's look at how to use this class:

   1: /// <summary>
   2: /// Converts a SOAP string to an object
   3: /// </summary>
   4: /// <typeparam name="T">Object type</typeparam>
   5: /// <param name="SOAP">SOAP string</param>
   6: /// <returns>The object of the specified type</returns>
   7: public static T SOAPToObject<T>(string SOAP)
   8: {
   9:     if (string.IsNullOrEmpty(SOAP))
  10:     {
  11:         throw new ArgumentException("SOAP can not be null/empty");
  12:     }
  13:     using (MemoryStream Stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
  14:     {
  15:         SoapFormatter Formatter = new SoapFormatter();
  16:         return (T)Formatter.Deserialize(Stream);
  17:     }
  18: }
  19:  
  20: /// <summary>
  21: /// Converts an object to a SOAP string
  22: /// </summary>
  23: /// <param name="Object">Object to serialize</param>
  24: /// <returns>The serialized string</returns>
  25: public static string ObjectToSOAP(object Object)
  26: {
  27:     if (Object == null)
  28:     {
  29:         throw new ArgumentException("Object can not be null");
  30:     }
  31:     using (MemoryStream Stream = new MemoryStream())
  32:     {
  33:         SoapFormatter Serializer = new SoapFormatter();
  34:         Serializer.Serialize(Stream, Object);
  35:         Stream.Flush();
  36:         return UTF8Encoding.UTF8.GetString(Stream.GetBuffer(), 0, (int)Stream.Position);
  37:     }
  38: }

It's pretty simple and if you've done XML or binary serialization in .Net, it's going to look fairly similar. Anyway, I can't believe how long it took me before I ran into a project that actually required SOAP. But I finally ran into one and decided to go about writing a couple of generic functions to help me out in serializing and deserializing the objects and will hopefully help you out as well. So try it out, leave feedback, and happy coding.



Comments