Dec 172012
 
 December 17, 2012  Posted by at 10:54 am C# & F#, Uncategorized Tagged with: , , , ,  Add comments

Using MessagePack in C#

In RE to the last post: Stupid Question 106: What is MessagePack?

Here is just some playground code (I just wanted to write and read from a text file using MessagePack). Seems to be working rather nice 🙂 Not the prettiest code, I just wanted to whip something together in a few minutes, took me maybe 15 min for this example.

To use MessagePack for beginners with C#:
1. Go to Github and download MessagePack
2. Unzip
3. Open the project and build it
4. Create your project and reference the DLL(s) in the MessagePack project

Serializing and deserializing (packing/unpacking) to a file and/or memorystream with MessagePack in C#

[sourcecode language=”csharp”]
using System.IO;
using MsgPack.Serialization;

namespace MsgPack
{
class Program
{
static void Main(string[] args)
{
CreateMsgPack();
}

static void CreateMsgPack()
{
WriteToFile();
ReadFromFile();

using (var stream = new MemoryStream())
{
var serializer = MessagePackSerializer.Create<Person>();
serializer.Pack(stream, CreateIris());
stream.Position = 0;
var person = serializer.Unpack(stream);
}
}

static void WriteToFile()
{
var serializer = MessagePackSerializer.Create<Person>();

using(Stream stream = File.Open(@"C:\Users\Iris\msg.txt", FileMode.Create))
{
serializer.Pack(stream, CreateIris());
}
}

static void ReadFromFile()
{
var serializer = MessagePackSerializer.Create<Person>();

using (Stream stream = File.Open(@"C:\Users\Iris\msg.txt", FileMode.Open))
{
var iris = serializer.Unpack(stream);
}
}

static Person CreateIris()
{
return new Person
{
Age = 28,
Name = "Iris Classon",
FavoriteNumbers = new[] {2,3,4}
};
}

}

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public int[] FavoriteNumbers { get; set; }
}
}

[/sourcecode]

  One Response to “Serializing and deserializing (packing/unpacking) to a file and/or memorystream with MessagePack in C#”

  1. I need to check this out, might be just what I need for my event sourcing storage.

    In case you didn’t know, there’s a Nuget package for MessagePack. (http://nuget.org/packages/MsgPack)

    Continue with the great posts!

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 5 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)