Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF - How to send GUIDs efficiently (not as strings)

Tags:

c#

wcf

I have a collection containing a LOT of Data Transfer Objects that I need to send to a Silverlight client over WCF. I'm using the default DataContractSerializer and an HTTPS channel.

Here's an example of one type of DTO.

[DataContract(Namespace = Constants.OrgStructureNamespace)]
public class EntityInfo : IExtensibleDataObject
{
    [DataMember] public Guid EntityID { get; set; }
    [DataMember] public EntityType EntityType { get; set; }
    [DataMember] public IList<Guid> EntityVersions { get; set; }
    [DataMember] public IList<Guid> OrganisationStructures { get; set; }

    #region IExtensibleDataObject Members
    ...
    #endregion
}

The domain entities on the server side use GUIDs as primary keys. These get serialized to strings which are 36 bytes long. A GUID in binary form should only be 16 bytes long.

Is there a trick to get the DataContractSerializer serialize my GUIDs as binary rather than as the verbose strings to increase performance?

like image 463
Simon Brangwin Avatar asked Nov 18 '10 22:11

Simon Brangwin


2 Answers

Try this:

[DataContract(Namespace = Constants.OrgStructureNamespace)]
public class EntityInfo : IExtensibleDataObject
{
    public Guid EntityID { get; set; }

    [DataMember(Name="EntityID")]
    byte[] EntityIDBytes
    {
        get { return this.EntityID.ToByteArray(); }
        set { this.EntityID = new Guid(value); }
    }

    [DataMember]
    public EntityType EntityType { get; set; }
    [DataMember]
    public IList<Guid> EntityVersions { get; set; }
    [DataMember]
    public IList<Guid> OrganisationStructures { get; set; }

    #region IExtensibleDataObject Members
    // ...
    #endregion
}

It looks like the DataContractSerializer handles byte arrays by Base64-encoding them, whereas it appears to just use the Guid.ToString method for Guids.

like image 108
Dr. Wily's Apprentice Avatar answered Oct 10 '22 00:10

Dr. Wily's Apprentice


There is no way that this can be overcome from what I know. Guids are not universally understood by all languages. Therefore they are serialized into a more interoperable format, string

on your service side convert it back to a guid from a string and that should take care of it

var g = new Guid(string);

unless you specifically tell the system what you want it to serialize the guid is then i believe it will choose string

like image 26
stack72 Avatar answered Oct 10 '22 00:10

stack72