Sunday, 3 February 2019

Firebase FCM Push & subscribe Notification Topics Using Firebase Cloud Messaging Using .NET

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. 

Steps to get server key / SenderID
  1. To get the keys, log in to Firebase account.
  2. Select the project from the list.
  3. Click on "Setting" gear icon and click "Project Settings". 
  1. //Create the web request with fire base API  
  2. WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");  
  3. tRequest.Method = "post";  
  4. //serverKey - Key from Firebase cloud messaging server  
  5. tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));  
  6. //Sender Id - From firebase project setting  
  7. tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));  
  8. tRequest.ContentType = "application/json";  
  9. var payload = new {  
  10.     to = deviceId,  
  11.         priority = "high",  
  12.         content_available = true,  
  13.         notification = new {  
  14.             body = txtmsg,  
  15.                 title = txttitle.Replace(":", ""),  
  16.                 sound = "sound.caf",  
  17.                 badge = badgeCounter  
  18.         },  
  19. };  
  20. var serializer = new JavaScriptSerializer();  
  21. Byte[] byteArray = Encoding.UTF8.GetBytes(payload);  
  22. tRequest.ContentLength = byteArray.Length;  
  23. using(Stream dataStream = tRequest.GetRequestStream()) {  
  24.     dataStream.Write(byteArray, 0, byteArray.Length);  
  25.     using(WebResponse tResponse = tRequest.GetResponse()) {  
  26.         using(Stream dataStreamResponse = tResponse.GetResponseStream()) {  
  27.             if (dataStreamResponse != null) using(StreamReader tReader = new StreamReader(dataStreamResponse)) {  
  28.                 String sResponseFromServer = tReader.ReadToEnd();  
  29.                 result.Response = sResponseFromServer;  
  30.             }  
  31.         }  
  32.     }  
  33. }  

Subscribe Topics FCM :

The FCM JavaScript API lets you receive notification messages in web apps running in browsers.


Retrieve a messaging object
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("XXXdd");


Request permission to receive notifications

messaging.requestPermission().then(function() {
  console.log('Notification permission granted.');
  // TODO(developer): Retrieve an Instance ID token for use with FCM.
  // ...
}).catch(function(err) {
  console.log('Unable to get permission to notify.', err);
});

Access the registration token
The messaging service requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token.

// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
  if (currentToken) {
    sendTokenToServer(currentToken);
    updateUIForPushEnabled(currentToken);
  } else {
    // Show permission request.
    console.log('No Instance ID token available. Request permission to generate one.');
    // Show permission UI.
    updateUIForPushPermissionRequired();
    setTokenSentToServer(false);
  }
}).catch(function(err) {
  console.log('An error occurred while retrieving token. ', err);
  showToken('Error retrieving Instance ID token. ', err);
  setTokenSentToServer(false);
});



Receive Messaging :
When your app is in the foreground (the user is currently viewing your web page), you can receive data and notification payloads directly in the page.
//   `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage(function(payload) {
  console.log('Message received. ', payload);
  // ...
});

firebase-messaging-sw.js
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

Wednesday, 19 December 2018

ConcurrentDictionary in C# - Introduction, Examples

One of the best thread safe programming we can do with ConcurrentDictionary ,
ConcurrentDictionary is one of five collection classes introduced in .NET 4.0. It exists in System.Collections.Concurrent namespace. ConcurrentDictionary is thread-safe collection class to store key/value pairs. ConcurrentDictionary can be used with multiple threads concurrently. 
Without ConcurrentDictionary class, if we have to use Dictionary class with multiple threads, then we have to use locks to provides thread-safety which is always error-prone. ConcurrentDictionary provides you an easy option. It internally manages the locking gives you an easy interface to add/update items.
ConcurrentDictionary uses different methods to add, retrieve, update and remove items.

Add items in ConcurrentDictionary

We can use TryAdd method to add a new key/value pair. Below is the example:
1
2
3
4
5
6
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    dict.TryAdd("1", "First");
    dict.TryAdd("2", "Second");
}
TryAdd methods returns true if key/value pair is added, and returns false if key already exists in dictionary.
1
2
3
4
5
6
7
8
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    bool firstItem = dict.TryAdd("1", "First");  //returns true
    bool secondItem = dict.TryAdd("2", "Second");  //returns  true
 
    bool thirdItem = dict.TryAdd("1", "Third"); //returns false;
}
In the above example, we try to add new item with the same key, TryAdd method returns false.

Retrieve Single Item using Key

To retrieve single item, ConcurrentDictionary provides TryGetValue method.
We have to provide Key in the TryGetValue method. It takes the out parameter to return the value of key. TryGetValue returns true if key exists, or returns false if key does not exists in dictionary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    bool firstItem = dict.TryAdd("1", "First");
    bool secondItem = dict.TryAdd("2", "Second");
 
    string itemValue1;
    string itemValue2;
    bool isItemExists1 = dict.TryGetValue("1", out itemValue1);  //returns true
    Console.WriteLine(itemValue1); //Print "First"
 
    bool isItemExists2 = dict.TryGetValue("3", out itemValue2);  //returns false
    Console.WriteLine(itemValue2); //Print blank
}

Retrieve all items in ConcurrentDictionary

As ConcurrentDictionary implements the IEnumerable interface, we can use foreach loop to enumerate all items in dictionary.
As with other dictionary class in .NET, It also does not returns all items in the order we have added in dictionary. We may get second item in first index, and first item in second index. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    foreach(var item in dictionary)
    {
        Console.WriteLine(item.Key + "-" + item.Value);
    }
    //Returns
    // 4- Fourth
    // 3 - Third
    // 2 - Second
    // 1 - First
}
Note: Enumeration is thread-safe in ConcurrentDictionary.
We have created two tasks. First task is adding new values and second task is enumerating all the items. We will not get any exception in below example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
 
 
    Task t1 = Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; ++i)
            {
                dictionary.TryAdd(i.ToString(), i.ToString());
                Thread.Sleep(100);
            }
        });
 
    Task t2 = Task.Factory.StartNew(() =>
        {
            Thread.Sleep(300);
            foreach (var item in dictionary)
            {
                Console.WriteLine(item.Key + "-" + item.Value);
                Thread.Sleep(150);
            }
        });
 
    try
    {
        Task.WaitAll(t1, t2);
    }
    catch (AggregateException ex) // No exception
    {
        Console.WriteLine(ex.Flatten().Message); 
    }
 
}

Update item

ConcurrentDictionary provides TryUpdate methods to update any key. TryUpdate takes three parameters. Three parameters are:
  1. Key - key to modify
  2. New Value - new value of the key
  3. Old Value - old value of the key
TryUpdate method update only when Key value matches with the old value, then it update the key with new value. It returns true if it successfully update the value else returns false. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    string newValue;
 
    bool returnTrue = dictionary.TryUpdate("1", "New Value", "First"); //Returns true
    dictionary.TryGetValue("1", out newValue);
    Console.WriteLine(newValue); //Print "New Value"
 
    bool returnsFalse = dictionary.TryUpdate("2", "New Value 2", "No Value"); //Returns false
    dictionary.TryGetValue("2", out newValue);  //Returns "Second" Old value
    Console.WriteLine(newValue);    //Print "Second"
}

Remove item

For remove any item, ConcurrentDictionary provides TryRemove method. TryRemove returns true if it successfully removes the item else returns false. It also returns the removed item in the out parameter. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    string removedItem;
    bool result = dictionary.TryRemove("2", out removedItem); //Returns true
    Console.WriteLine(removedItem); //Print "Second"
}

Remove all items in ConcurrentDictionary

For removing all items, we can use Clear method. It removes all the keys and its values from dictionary. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
 
    dictionary.Clear();
 
    foreach (var item in dictionary) //enumerate 0 times
    {
        Console.WriteLine(item.Key);
    }
}

Count all Items

ConcurrentDictionary provides Count method to returns the total number of items. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    int totalItems = dictionary.Count(); // Returns 4
 
    int filterItems = dictionary.Count(w => w.Value.ToLower().Contains("t")); //Returns 3
}
ConcurrentDictionary also provides an overloaded method of Count() which takes the Predicate to filter the items.

Check Key exists

To check particular key exits in dictionary, we can use ContainsKey method. It returns true if key exists otherwise returns false.
1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    bool firstItemFound = dictionary.ContainsKey("1"); //Returns true
    bool fifthItemFound = dictionary.ContainsKey("5"); //Returns false
}

Copy ConcurrentDictionary items to another Collection classes

For copy stored key/values pairs to another collection class, It provides different "To..." methods.
  1. ToArray
  2. ToDictionary
  3. ToList
  4. ToLookup
We can use above methods to copy over dictionary values into another collection classes. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
 
    KeyValuePair<string, string>[] keyValues = dictionary.ToArray();
 
    Dictionary<string, string> dict = dictionary.ToDictionary(w => w.Key, m => m.Value);
 
    List<KeyValuePair<string, string>> lst = dict.ToList();
 
    ILookup<string, string> lookup = dict.ToLookup(w => w.Key, m => m.Value);
}

Final Words

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.
Do post your queries for the same.