Compressing a WCF Message

Every now and then there's a WCF message that passes the MaxReceivedMessageSize threshold. Here's a nice little helper class that will allow you to compress and decompress it, without depending on extra WCF configurations. For serialization it uses the XML-based DataContractSerializer, so you can deserialize the original types into other types and namespaces. For compression it uses a DeflateStream instead of a GZipStream for less overhead.

namespace DockOfTheBay
{
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.IO.Compression;
    using System.Runtime.Serialization;
 
    public static class CompressedSerializer
    {
        [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
        public static T Decompress<T>(byte[] compressedData)
        {
            using (MemoryStream memory = new MemoryStream(compressedData))
            {
                using (DeflateStream zip = new DeflateStream(memory, CompressionMode.Decompress, true))
                {
                    var formatter = new DataContractSerializer(typeof(T));
                    return (T)formatter.ReadObject(zip);
                }
            }
        }
 
        public static byte[] Compress<T>(T data)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                using (DeflateStream zip = new DeflateStream(memory, CompressionMode.Compress, true))
                {
                    var formatter = new DataContractSerializer(typeof(T));
                    formatter.WriteObject(zip, data);
                }
 
                return memory.ToArray();
            }
        }
    }
}


No comments:

Post a Comment