Quick Intro to Protobuf

Protobuf-net is a .net adaption of Google’s Protocol Buffers and is generally considered to be a really fast serialization/deserialization library.  The target serializable classes are decorated with mainly 3 attributes.

ProtoContract
The target class is decorated with the ProtoContract attributes, indicating that the class can be serialized.

ProtoMember(N)
The ProtoMember attribute indicates the field that will be serialized, while the number N denotes the order in which the property would be serialized. By default, the properties would be serialized in alphabetical order.

ProtoIgnore
As the name suggests, the ProtoIgnore attributes is used to indicate the properties that needs to be ignored while serializing.

Let’s create the example class which we would be serializing.

[ProtoContract]
public class Student
{
  [ProtoMember(1)]
  public string Name { get; set; }
}

In order to serialize the class, you would be using the Static method Serialize.

var stOriginal = new Student() { Name = "jia" };
byte[] array;
           
using (var stream = new System.IO.MemoryStream())
{
   ProtoBuf.Serializer.Serialize(stream, stOriginal);
   array = stream.ToArray();
}

Similarly, the static method Deserialize can be used to deserialize the object back.

Student stDeserialized;
using (var stream = new System.IO.MemoryStream(array))
{
  stDeserialized = ProtoBuf.Serializer.Deserialize(stream);
}

Easy as that !! Happy Coding !!

Serialize Deserialize NameValueCollection

Don’t ask me why one cannot Serialize/Deserialize a NameValueCollection, but the workaround for the same is based on conversion to dictionary. I ended up writing extension methods to NameValueCollection for serializing and deserializing the collection.

public static string JSONSerialize(this NameValueCollection _nvc)
{
return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k, k =>_nvc.GetValues(k)));
}
public static void JSONDeserialize(this NameValueCollection _nvc,string _serializedString)
{
var deserializedobject = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(_serializedString);
foreach (var strCol in deserializedobject.Values)
foreach (var str in strCol)
_nvc.Add(deserializedobject.FirstOrDefault(x => x.Value.Contains(str)).Key, str);
}