http://www.developer.com/net/net/working-with-protobuf-services-in-.net.html

Back to article

Working with Protobuf Services in .NET


June 16, 2011

Take advantage of Google's Protobuf-net to create services that are high performance. Protocol buffers from Google is a binary serialization format that is used for data communication. Protocol Buffer is a very efficient hypermedia type that can be used with RESTful services. Protobuf-net is a .NET implementation of Protocol Buffers that you can use to serialize your .NET objects seamlessly. This article takes a look at Protobuf Objects and how they can be used in .NET.

Pre-requisites

To work with the code examples listed in this article, you need to have the following installed in your system: Visual Studio 2008/2010 Protobuf-net You can download a copy of Protocol Buffers for .NET from here. Before we delve deep into how we can create Protobuf objects in .NET and use Protobuf-net with WCF services, let's have a quick tour of the basic concepts related to Protobuf-net.

Why Protocol Buffers?

Protocol Buffers from Google provide you a language and platform-neutral format for serializing data that is smaller in size than XML or JSON. Here are some of the advantages of using Protocol Buffers at a glance:

  1. Platform independent
  2. Small sizes
  3. Extensible

Creating Protobuf-net Objects

Note that all Protobuf-net classes are stored in files that have .proto extensions. You can store one or more proto classes in a .proto file. Here is an example that illustrates what a typical protobuf-net class looks like:

package Test;
message User 
{
 required int32  UserID = 1;
 required string UserName = 2;
 required string UserEmail = 3;
 required string Password = 4;
 optional string Address = 5;
}

Note that "required" in the above message implies that it is a mandatory property. So, UserID, UserName, UserEmail and Password are mandatory properties. The Address property is an optional property and is prefixed with the optional keyword. Note that message in Protobuf implies a class. If you have a class that contains a list of objects, you need to use the repeated keyword when defining your Protobuf classes. Here is an example:

package Test;
message Customer {
	required string CustomerCode = 1;
	required string FirstName = 2;
	required string LastName = 3;
	repeated Contact ContactList = 4;
}

As you can see, the Customer message contains a list of objects of type Contact. The Contact message is defined as shown below:

package Test;
message Contact 
{
	required string ContactCode = 1;
	required string Address1 = 2;
	required string Address2 = 3;
	required string Address3 = 4;
	required string Phone = 5;
	required string Email = 6;
}

One important thing to note when creating Protobuf-net classes is that each of the properties of the class should be explitly numbered, i.e., each of them should have a proper ordering. Here is how you can configure Visual Studio 2010 to compile your projects that have .proto files inside them:

$(SolutionDir)PreBuildChecker\$(OutDir)PreBuildChecker 
    $(ProjectDir)Customer.proto 
    $(ProjectDir)Customer.cs 
    c:\bin\protobuf\protogen 
      "-i:$(ProjectDir)Customer.proto" 
      "-o:$(ProjectDir)Customer.cs" 
      -t:c:\bin\protobuf\csharp.xslt

Visual Studio 2008 and 2010 now comes with support for creating protobuf-net classes through a custom tool. You can find more information on this from this link.

Using Protobuf-net in WCF Services

In this section we will explore how we can configure a WCF service so as to leverage the benefits of Protobuf-net. Windows Communication Foundation (WCF) is a platform that can be used to design and implement platform independent, scalable services and provides support for unification of a number of enterprise technologies under one single umbrella. According to the MSDN: "Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments." To use protobuf-net with your WCF service, you need to mark your service contract with the ProtoBehavior attribute. You can also specify that your WCF service would use Protobuf-net in the configuration file. Here is an example:

<service name="TestWCFService.Service1" behaviorConfiguration="TestWCFService.Service1Behavior">
<endpoint address="" binding="wsHttpBinding" contract="TestWCFService.IService1" behaviorConfiguration="protoEndpointBehavior">
	<identity>
  	  <dns value="localhost"/>
	</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>

Note that to use Protobuf-net with WCF, your data members in the entity classes should have ordering explicitly set as shown below:

   [ProtoContract]
    class Contact {
        [ProtoMember(1)]
        public string ContactCode {get;set;}           [ProtoMember(2)]
        public string Address1 {get;set;}
        [ProtoMember(3)]
        public string Address2 {get;set;}
        [ProtoMember(4)]
        public string Address3 {get;set;}
        [ProtoMember(5)]
        public string Phone {get;set;}
        [ProtoMember(6)]
        public string Email {get;set;}
    }

Note the usage of the ProtoMember attbute in the code snippet shown above. Also, each of the data members of the Contact class have been ordered.

To consume the WCF Protobuf-net service, you need to specify protoEndpointBehavior. You can specify configuration to access your WCF Protobuf-net service as shown below:

<client>
    <endpoint address="http://localhost:2165/Service1.svc" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
                behaviorConfiguration="protoEndpointBehavior"
                name="WSHttpBinding_IService1">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
</client>
<behaviors>
   <endpointBehaviors>
            <behavior name="protoEndpointBehavior">
               <protobuf/>
            </behavior>
   </endpointBehaviors>
</behaviors>
<extensions>
   <behaviorExtensions>
     <add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=1.0.0.275, 
          Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/>
   </behaviorExtensions>
</extensions>

References

Summary

Protocol Buffers is a binary serialization format that can be used to serialize objects that are much smaller in size and are portable across various platforms. In this article we discussed the basic concepts of Protocol Buffers and how they can be used in .NET applications and WCF services. We also discussed how Protobuf-net classes appear. Happy reading!

Sitemap | Contact Us