Tuesday, May 5, 2015

protobuf-net

 

Protocol Buffers is the name of the binary serialization format used by Google for much of their data communications. It is designed to be: small in size - efficient data storage (far smaller than xml) cheap to process - both at the client and server platform independent - portable between different programming architectures extensible - to add new data to old messages. protobuf-net is a .NET implementation of this, allowing you to serialize your .NET objects efficiently and easily. It is compatible with most of the .NET family, including .NET 2.0/3.0/3.5/4.0, .NET CF 2.0/3.5, Mono 2.x, Silverlight, etc.

See the following samples where you can use it.

Step 1: Install protobuff

To install protobuf-net, run the following command in the Package Manager Console

PM> Install-Package protobuf-net

Step 2: Create the Data Models

Unlike XmlSerializer, the member-names are not encoded in the data - instead, you must pick an integer to identify each member. Additionally, to show intent it is necessary to show that we intend this type to be serialized. See the following sample.

  1. [ProtoContract]
  2.   class Person {
  3.       [ProtoMember(1)]
  4.       public int Id {get;set;}
  5.       [ProtoMember(2)]
  6.       public string Name { get; set; }
  7.       [ProtoMember(3)]
  8.       public Address Address {get;set;}
  9.   }
  10.   
  11.   [ProtoContract]
  12.   class Address {
  13.       [ProtoMember(1)]
  14.       public string Line1 {get;set;}
  15.       [ProtoMember(2)]
  16.       public string Line2 {get;set;}
  17.   }

Notes for Identifiers

  • they must be positive integers
  • they must be unique within a single type
    • but the same numbers can be re-used in sub-types if inheritance is enabled
  • the identifiers must not conflict with any inheritance identifiers lower numbers take less space - don't start 100,000,000
  • the identifier is important; you can change the member-name, or shift it between a property and a field, but changing the identifier changes the data

 

Step 3: Serialize to stream

Class with protobuf functions
  1. public class ProtoBuf
  2.   {
  3.  
  4.      public static MemoryStream Serialize(object content)
  5.      {
  6.          MemoryStream objectStream=new MemoryStream();
  7.          Serializer.Serialize(objectStream,content);
  8.          return objectStream;
  9.      }
  10.  
  11.  
  12.      public static T Deserialize<T>(MemoryStream objectStream)
  13.      {
  14.          objectStream.Position = 0;
  15.          T content = Serializer.Deserialize<T>(objectStream);
  16.          return content;
  17.      }
  18.   }

 

Calling the methods
  1. var person = new Person
  2.           {
  3.               Id = 12345,
  4.               Name = "Fred",
  5.               Address = new Address
  6.               {
  7.                   Line1 = "Flat 1",
  8.                   Line2 = "The Meadows"
  9.               }
  10.           };
  11.  
  12.  
  13.           //serialize to stream
  14.           MemoryStream stream=  ProtoBuf.Serialize(person);
  15.  
  16.  
  17.           //deserilize to person object
  18.           stream.Position = 0;
  19.           Person personObject = ProtoBuf.Deserialize<Person>(stream);

 

Step 3: Serialize and write to a file.

  1. var person = new Person
  2.             {
  3.                 Id = 12345,
  4.                 Name = "Fred",
  5.                 Address = new Address
  6.                 {
  7.                     Line1 = "Flat 1",
  8.                     Line2 = "The Meadows"
  9.                 }
  10.             };
  11.  
  12.  
  13.             using (var file = File.Create("person.bin"))
  14.             {
  15.                 Serializer.Serialize<Person>(file, person);
  16.             }
  17.             
  18.     
  19.             using (var file = File.OpenRead("person.bin"))
  20.             {
  21.                 Person personObject = ProtoBuf.Deserialize<Person>(file);
  22.            
  23.             }

 

for more information in protobuf visit here

Happy Coding !!!

Sunday, April 5, 2015

Clean Code Practices : Conditions

 

It is said

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

so that we have to make sure the code we write should be easily read and understood by the other developers. This post I will be discussing practices we can follow to make our conditional statements clean. In this post I will mention code dirty and clean to you to understand the difference

Principles:-

  1. Clear Intent
  2. Use the right tool
  3. Bite-size logic
  4. Sometimes code isn’t the answer

 

1.Use Positive Conditionals

When you write conditions always try to use positive conditionals rather using negative because humans are more comfortable in grabbing positive things.

Dirty
if (!isNotlogggedIn)
            {
            }

see above example it is bit confusing to understand the meaning in first time.

Clean
  1. if (logggedIn)
  2.             {
  3.             }

 

2.Use Ternary operator

see the following example first.

Dirty

  1. int bookingFee;
  2.  
  3.           if (isEarlyBirdBooking)
  4.           {
  5.               bookingFee = 5000;
  6.           }
  7.  
  8.           else
  9.           {
  10.               bookingFee = 8000;
  11.           }

we can see the variable “bookingfee” is referenced two places and this code has 11 lines of code. For this kind of conditions you can use the ternary operator to make the code cleaner.

Clean

  1. int bookingFee = isEarlyBirdBooking ? 5000 : 8000;

so that you can see, this has

  • less code
  • intention of the logic is short and clearly presented

3.Avoid using ‘Stringly’ types

see the following example first

Dirty

  1. if (user.Type= "Administrator")

in this sample we are checking a condiition against a string. Which might lead to many issues. There could be case mismatch, also developer might make spelling mistakes. To avoid these try to use enums rather using string values.

Clean

  1. if(user.UserType==UserType.Administrator)

if you use enums

  • there will be no typos
  • You will get the intellisense support from visual studio as it shows all possible values for user type
  • Also you can easily search where a specific user type is used in the code. Rather using enums if you use sting and then you search it will search commented code and all other unwanted stuff.

 

 

Monday, February 9, 2015

Event Initializer in C# 6.0

 

Take the following sample class which has a property and an event listener

  1. public class Lecturer
  2.     {
  3.         public string Name { get; set; }
  4.         public EventHandler<EventArgs> Speaking;
  5.  
  6.     }
.

In C# 6.0 when you initialize a new object wire up delegate to the event inside the object initialization syntax. Before C# 6.0 it was illegal.

  1. static void Main(string[] args)
  2.       {
  3.           EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.           Lecturer mathsLecturer = new Lecturer
  6.           {
  7.               Name = "Perera",
  8.               Speaking += log
  9.           };
  10.       }

Also you can directly assign the lambda to the event as follows.

  1. static void Main(string[] args)
  2.         {
  3.             EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.             Lecturer mathsLecturer = new Lecturer
  6.             {
  7.                 Name = "Perera",
  8.                 Speaking += (e, o) => Console.WriteLine("Speaking")
  9.             };
  10.         }

 

Happy Coding !!!

Sunday, February 8, 2015

Dictionary Initializer in C# 6.0

 

After C# 3.0 is released we had the ability of initializing lists and dictionaries using following syntax.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.             {
  3.                 { "admin",new User("Sammani") },
  4.                   { "Guest",new User("Hemal") },
  5.             };

Here we add the key value pairs inside the “{ }”. In c# 6.0 it has a new syntax as follows which gives more look like working with key value pairs.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.           {
  3.               [ "admin"]=new User("Sammani") ,
  4.                ["Guest"]=new User("Hemal")
  5.           };

you can the number of characters are almost same in both the syntax but in c# 6.0 syntax looks more a like key value pair.

This is another syntax sugar added in c# 6.0.

Happy Coding

Sunday, January 4, 2015

Primary Constructor in C# 6.0

 

In my previous post I explain about Auto Property Initializer in C# 6.0. Now lets see another new feature in C# 6.0 which is Primary constructor.

First we will see the following code.

  1. public class Country
  2. {
  3.     public string Name { get; private set; }
  4.  
  5.     public Country(string name)
  6.         {
  7.         Name = name;
  8.         }
  9.  
  10. }

here we have a class which has a property with a private setter and assigning the value for the name property inside the constructor.

Now in C# 6.0 you can write the above code in a more simplified manner as follows.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get;}=name;
  4.  
  5.  
  6.     }

This is what is called primary constructor in C# 6.0 . Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Country class with one parameters: name. So we don’t need to create separate constructor with parameters and then assign the values to the property , compiler do all those for us.

For one class only one primary constructor is allowed. If you want to have constructors with some more parameters you can create new constructor and also call the primary constructor inside it. See the following example.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get; } = name;
  4.     public List<string> Regions { get; private set; }
  5.     public Country(List<string> regions, string name):this(name)
  6.     {
  7.         Regions = regions;
  8.     }
  9. }

Here when you call the constructor with two parameters it will assign the value to the property “Regions” and it has call the primary constructor it will set the value to the property “Name”. Hope you understand the concept behind this.

Hope this is helpful.

Happy Coding !!!!!!

Friday, January 2, 2015

Auto Property Initializer

 

Anyone who have worked with properties in a class must have experienced that it was little annoying that we have to have private fields and assigned if we want to have default values for properties.

See the following example which we used to do when we have collection property.

  1. public class Country
  2.     {
  3.         private List<string> _regions = new List<string>();
  4.         public List<string> Regions { get { return _regions} set { value = _regions; } }
  5.  
  6.     }

but this is no more needed. We can simply write it as below.

  1. public class Country
  2.     {
  3.         public List<string> Regions { get; set; }=new List<string>();
  4.  
  5.     }

Also this is useful when you want to assign default values for read only fields.

Before C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }
  4.       public Country()
  5.       {
  6.           this.Name = "Sri Lanka";
  7.       }
  8.  
  9.   }

In C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }="Sri Lanka";
  4.  
  5.   }

 

This is syntactic sugar added in c# 6.0. hope this is helpful.

 

Happy Coding !!!!!!