Search code examples
c#.netwcfsizedatacontract

Calculate size of a package(datacontract) that goes over WCF?


Is it possible to calculate the size of a (complexed) object (with dataContract) that I send over WCF? What I need is to calculate the size on both the request and the response objects and I need to do this in a winform application.

Could I maybe serlize the objects and then get the total size?


Solution

  • You can manually serialise / deserialise the objects yourself. Here's a simple example of serialisation and obtaining the length.

    [DataContract(Name = "Person", Namespace = "http://www.woo.com")]
        class Person
        {
            [DataMember()]
            public string Name;
            [DataMember()]
            public int Age;        
        }
    

    calling code (in a console app)

            Person p = new Person();
            p.Name = "Sean Cocteau";
            p.Age = 99;
    
            DataContractSerializer ds = new DataContractSerializer(p.GetType());
    
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                ds.WriteObject(ms, p);                
                // Spit out
    
                Console.WriteLine("Output: " + System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                Console.WriteLine("Message length: " + ms.Length.ToString());
            }
    
            Console.ReadKey();
    

    In respect to performing this automatically, say on each WCF call may involve you having to create your own Custom Binding that adds this to the message.