Saturday, June 13, 2015

Localizing Azure Push Notification in Server end

 

Suppose you mobile application supports localization. And you need to send localized push notifications for your mobile app users. In that case now Azure push notification has templates which supports localization.

See the following link which gives good guidance on it.

Use Notification Hubs to send localized breaking news

In this post I will show how we can use resource files and localize some messaged to be sent.

1. First Configure the Resource file as you want with the messages.

2. Configure the supported languages for the notification.

  1. public const string LangzhSG = "zh-sg";
  2.       public const string LangenUS = "en-us";
  3.       public const string LangenGB = "en-gb";
  4.       public const string LangitIT = "it-it";
  5.       public const string LangsiLK = "si-lk";

 

  1. public static List<string> SupportedLanguages
  2.     {
  3.         get { return new List<string> { LangzhSG, LangenUS, LangenGB, LangitIT, LangsiLK }; }
  4.     }

3.  Localize the messages as your need. In here based on work order status message to be sent will be varied.

  1. public static Dictionary<string, string> GetMessageTranslations(WorkorderUpdateNotification message,
  2.                                                                       List<string> supportedLanguages)
  3.       {
  4.           string messageText = string.Empty;
  5.  
  6.           Dictionary<string, string> messageList = new Dictionary<string, string>();
  7.           if (message.Message.ToLower().Equals("failed"))
  8.           {
  9.  
  10.               foreach (var supportedLanguage in supportedLanguages)
  11.               {
  12.                   Resources.terms.Culture = new CultureInfo(supportedLanguage);
  13.                   messageText =
  14.                       string.Format(Resources.terms.webapi_helpers_pushnotification_messages_FailedToUpdateWO1,
  15.                                     message.WorkOrderNumber);
  16.                   messageList.Add(supportedLanguage, messageText);
  17.               }
  18.  
  19.           }
  20.  
  21.           return messageList;
  22.       }
  23.  
  24.   }

4. Create the class which has the properties which notification holds all required data.

  1.  
  2. public class WorkOrderUpdatePushNotification
  3. {
  4.     public string WorkOrderNumber { get; set; }
  5.     public bool IsSuccessful { get; set; }
  6.     public string From { get; set; }
  7.     public string Message { get; set; }
  8.     public string PushNotificationHub { get; set; }
  9. }

5. Create the required JSON string

  1. private static Dictionary<string, string> GetWorkorderUpdatePushNotificationsCollection(
  2.          WorkorderUpdateNotification message)
  3.      {
  4.  
  5.          List<string> supportedLanguages = ResourceKeyConstants.SupportedLanguages;
  6.          Dictionary<string, string> messageList = GetMessageTranslations(message, supportedLanguages);
  7.          Dictionary<string, string> workorderUpdateNotifications = new Dictionary<string, string>();
  8.          string notificationName = "WorkorderUpdateNotification_{0}";
  9.          string alertName = "WorkorderUpdateAlert_{0}";
  10.          foreach (var supportedLanguage in supportedLanguages)
  11.          {
  12.              string localizedNotificationName = string.Format(notificationName,
  13.                                                               supportedLanguage.Replace("-", string.Empty));
  14.              string localizedAlertName = string.Format(alertName, supportedLanguage.Replace("-", string.Empty));
  15.              Resources.terms.Culture = new CultureInfo(supportedLanguage);
  16.              string from = Resources.terms.webapi_helpers_pushnotification_messages_FromDtz;
  17.  
  18.              WorkOrderUpdatePushNotification workOrderUpdatePushNotification = new WorkOrderUpdatePushNotification
  19.                  {
  20.                      WorkOrderNumber = message.WorkOrderNumber,
  21.                      IsSuccessful = message.Message.ToLower().Equals("successful"),
  22.                      From = from,
  23.                      Message = messageList[supportedLanguage],
  24.                      PushNotificationHub = HybridConfig.GetAppSetting("PushNotificationHub")
  25.                  };
  26.  
  27.              var alert = JsonConvert.SerializeObject(workOrderUpdatePushNotification);
  28.  
  29.              workorderUpdateNotifications.Add(localizedNotificationName, alert);
  30.              workorderUpdateNotifications.Add(localizedAlertName, workOrderUpdatePushNotification.Message);
  31.          }
  32.  
  33.  
  34.  
  35.          return workorderUpdateNotifications;
  36.      }

6. Push the notification

  1. public static Dictionary<string, string> SendWorkorderUpdatePushNotificationTest(
  2.          WorkorderUpdateNotification message)
  3.      {
  4.          NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString
  5.              (HybridConfig.GetAppSetting("PushNotificationServiceBus"),
  6.               HybridConfig.GetAppSetting("PushNotificationHub"));
  7.  
  8.  
  9.  
  10.          Dictionary<string, string> workorderUpdateNotifications =
  11.              GetWorkorderUpdatePushNotificationsCollection(message);
  12.  
  13.          hub.SendTemplateNotificationAsync(workorderUpdateNotifications, message.UserUpdated);
  14.  
  15.          return workorderUpdateNotifications;
  16.      }

 

Happy Coding !!!

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 !!!!!!