Tuesday, March 8, 2016

Google Protocol Buffer in C#

It claims to be much efficient on the wire format than .Net Binary Serializer. So the follow summary how to use it in Visual Studio

Nuget Package Console: install-package Google.ProtocolBuffers. This will bring in Dll and tools like ProtoGen.exe to convert .proto file into C# class.
 using packages\..\tools\ProtoGen.exe as follows will generate a class to be used in serialization.

 ProtoGen -public_classes=true, -generate_private_ctor=false address.proto

this class does not allow constructor and setter, instead must use builder and parser.

.proto file and C# code to build, serialize/deserialize as file on disk

 syntax = "proto2";
 package tryout;

message Person {
   optional string name = 1;
   required int32 id = 2;
   optional string email = 3;

  enum PhoneType {
     MOBILE = 0;
     HOME = 1;
     WORK = 2;
   }

  message PhoneNumber {
     optional string number = 1;
     optional PhoneType type = 2;
   }

  repeated PhoneNumber phones = 4;
 }

message AddressBook {
   repeated Person people = 1;
 }

        static void Main(string[] args)
         {
             var bdr = Person.CreateBuilder();
             bdr.Id = 1;
             bdr.Name = "John";
             bdr.Email = "john@yahoo.com";
             Person john = bdr.Build();


             using (var output = File.Create("john.dat"))
             {
                 john.WriteTo(output);
             }
             var john2= Person.ParseFrom(File.OpenRead("john.dat"));
         }



No comments:

Post a Comment