Mark Needham

Thoughts on Software Development

Archive for the ‘examples’ tag

C# Thrift Examples

with 8 comments

As I mentioned in my earlier post I have been working with Facebook’s Thrift messaging project.

Unfortunately there are not currently any C# examples of how to use the Data Transfer Objects the Thrift compiler generates for us on the official wiki.

We managed to figure out how to do it by following the Java instructions and converting them into C# code. Before writing any code we need to import Thrift.dll into our Visual Studio project.

Assuming that we have the following Thrift definition file:

namespace csharp Test.Thrift
 
struct FooBarMessageThrift {
1: string Foo
2: string Bar
}

When we run the Thrift compiler we will end up with the FooBarMessageThrift class. I won’t post this class here as it’s all codegen.

The easiest way to transport this class around is by converting it to a byte array and transporting that:

1
2
3
4
5
6
7
8
var fooBarMessage = new FooBarMessageThrift {Foo = "foo", Bar = "bar"};
var stream = new MemoryStream();
 
TProtocol tProtocol = new TBinaryProtocol(new TStreamTransport(stream, stream));
 
fooBarMessage.Write(tProtocol);
 
byte[] content = stream.ToArray();

To read the byte array back into FooBarMessageThrift we do this:

1
2
3
4
5
var stream = new MemoryStream(content);
TProtocol tProtocol = new TBinaryProtocol(new TStreamTransport(stream, stream));
 
var barFooMessageThrift = new BarFooMessageThrift();
barFooMessageThrift.Read(tProtocol);

‘content’ in this example is the byte[] created in the first example, and that’s all there is to it!

Written by Mark Needham

August 29th, 2008 at 1:39 am

Posted in .NET,Messaging

Tagged with , , ,