Tag Archives: Microsoft Azure

So I took up on TravelMonkey, the Xamarin + Cognitive Services Challenge!

Let me share my little adrenaline filled panic adventure into earning some awesome Xamarin Swag! from the Xamarin + Cognitive Challenge hosted by Microsoft, the TravelMonkey Challenge! 😀

Well it’s come to 2020, in the middle of a pandemic, a lock down, and it’s been a while since I took up on an actual challenge outside my work and personal coding experiments! Then I suddenly came across this little challenge posted by Microsoft, TravelMonkey – the Cognitive Services + Xamarin Combo Challenge! (https://devblogs.microsoft.com/xamarin/cognitive-services-xamarin-challenge/)


As usual, the first thing I checked, what’s in it for me, you know what I mean! 😉 YES! they had promised some awesome Microsoft swag! Xamarin t-shirts, monkeys, and stickers!?! Say no more, I was in! 😀 well at least I thought to myself… their Submission deadline was April 30, 2020 11:59 PM PDT!

The days went by, one by one, without even any second thoughts, yeah I’d do it tomorrow, or day after or some time… I’ll get it done!

Then suddenly, it was 29th April, the Friday night, oh shoot! tomorrow’s the deadline for submission of the awesome TravelMonkey challenge! Yeah well I could say it was my own procrastination that got me in that situation, I had waited till the last day!

Procrastination is bad!

Just like in that GTA San Andreas scene, in my head I was like, “Ah sh*t, here we go again!” it was literally a moment of panic, and I was the fence about giving it up. But then it was Friday night, the day I usually watch a good night movie and fall asleep to wake up very late on Saturday! 😦

But then again, it was middle of a pandemic lock down, and I haven’t really had this kind of a fun challenge in a while, so I thought of pulling an all nighter and getting it done! at least something worth while before the next 24 hours ended… 😮

At this point, I didn’t have a plan of what I’m going to be building or expand up on, so I thought of simply exploring the current implementation and figure out where are the points in which I could improve as for the challenge. Once again, it was a bad idea to start working on it, at a time when it was less than 24 hours before the submission! lol 😀

Sneak Peek!

But at the end, here the beauty I ended up building…

I know right.. gorgeous!

Yeah well behind all that eye-candy glamour there was a painful sleepless all-nighter experience, waiting to be unraveled…

Getting started…

So first, I forked the github repo from https://github.com/jfversluis/TravelMonkey into my own github repo: https://github.com/UdaraAlwis/TravelMonkey and set up the Azure Cognitive services in Free tier with the following,

  • Azure Computer Vision
  • Bing Translation
  • Bing Image Search

Then I got the API keys and hooked up into the Xamarin Mobile app project.

New Featurettes!

This is a travel related app! even though it is fictional. lol So I wanted to think of it as being used by smart Monkeys like us, who would love to see beautiful scenic photos of the top travel destinations in the world.

Why stop there? I should allow the users to search for a destination and view the top scenic photos of that destination, as a little cherry on top! 😉

Also how about letting the user translate any text into any language they choose? That would definitely come in handy for any traveller!

Bing Image Search FTW!

So I picked up the most visited destinations by international tourist arrivals data from Wikipedia, https://en.wikipedia.org/wiki/World_Tourism_rankings and hooked it up into the Bing Search Service to load images of those destinations. Each destination would be taken up with 10 images and we would randomize through them in the Home page carousel.

var client = new ImageSearchClient(
new Microsoft.Azure.CognitiveServices.Search.

var imageResult = await client.Images.
	$"{destination} attractions", 
	minWidth: 500, 
	minHeight: 500, 
	imageType: "Photo", 
	license: "Public", 
	count: 10, 
	maxHeight: 1200, 
	maxWidth: 1200);

See how I modified the Bing Image search query there, {destination} attractions where as it would be executed as “France attractions”, “Thailand attractions”, and etc. So just like that I refined the search terms for scenic tourist photos from Bing Images.

Destination scenic Gallery!

I decided to add a travel destination Gallery page, consisting of scenic travel photos from Bing. User would be able to pick a destination from a presented list of countries in the Home page itself, and then navigate to its Gallery page to view the top 10 most scenic photos from Bing.

Here I did a little trick to load a list of countries in C# by tapping into CultureInfo object provided by .NET framework, pretty handy!

private static List<string> GetCountries()
	List<string> countryList = new List<string>();

	var getCultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

	foreach (var getCulture in getCultureInfo)
		var regionInfo = new RegionInfo(getCulture.LCID);
		if (!countryList.Contains(regionInfo.EnglishName))

	return countryList;

This would return the list of countries in the world which I will be presenting to the user to choose from! I will use the Bing Image Search that I had already modified to load the scenic travel images set on the go.

Bing Translation FTW!

So I thought of adding some improvements to the Translation features, where currently they had a pre-set of languages they would translate to given the input text. I wanted to make it completely dynamic, by getting the list of languages available in Bing Translation service, and letting the user pick the languages they want to translate to.

Here’s how I got the list of supported languages Bing Translation,

public async Task<List<AvailableLanguage>> GetLanguageList() 
	string endpoint = ApiKeys.TranslationsEndpoint;
	string route = "/languages?api-version=3.0";

	using (var client = new HttpClient())
	using (var request = new HttpRequestMessage())
		request.RequestUri = new Uri(endpoint + route);
		// Send request, get response
		var response = client.SendAsync(request).Result;

	List<AvailableLanguage> availableLanguages = new List<AvailableLanguage>();
	foreach (var item in translationStatsResult.Translation)
	{ ... }
	return availableLanguages;

Once I got the available languages list, I would present them to the user to pick from for translating their input text. But during the app’s first time launch I would randomly pick 5 languages and show the translations.

So here’s how I extended the Translation service call with the dynamic request language list,

public async Task<List<AvailableTranslation>> 
TranslateText(string inputText, List<AvailableLanguage> listOfLanguages)
	// build the translate url chunk
	string requiredTranslationsString = "";
	foreach (var item in listOfLanguages)
		requiredTranslationsString = requiredTranslationsString + $"&to={item.Key}";
	request.RequestUri = new Uri(ApiKeys.TranslationsEndpoint + "/translate?api-version=3.0" + requiredTranslationsString);
	translations.Add( new AvailableTranslation()
		InputLanguage = bestResult.DetectedLanguage.Language,
		InputText = inputText,
		TranslatedLanguageKey = t.To,
		TranslatedLanguageText = t.Text,
		TranslatedLanguageName = MockDataStore.Languages.FirstOrDefault(x => x.Key == t.To).Name,
	return translations;

I’m dumping them all into a list of AvailableTranslation objects which I will be unpacking in the UI for displaying the results of the input text translation.

Caching a bit of data!

Now this is something I had kept till the last minute, hence I couldn’t complete it as I expected, but I still managed to store some data in the app memory during run time to reduce repetitive duplicate queries to Bing services, which will also help me reduce the free tier quota usage.

I managed to store the list of destination scenic image result data and translation text in memory as a simple static singleton data object.

Emoji Support 😀

It would be nice to have some Emoji support for our text labels in the app, I thought. So I added it with the following nice little snippet I came across, https://github.com/egbakou/EmojisInXamarinForms

So with that nice little snippet I could insert emojis into a text and bind them to any Label element in Xamarin.Forms, nice and easy!

Title = 
$"Something went wrong 
{new Emoji(0x1F615).ToString()} 
Here is a cat instead!"

It will display the given emoji natively to the run time platform hence we’re using unicode representation of that emoji! 😉

No more icon files!

I really don’t like using physical image files for representing icons, so I got rid of them and introduced full Font Awesome based icons to the entire app. Setting it up in Xamarin.Forms is pretty easy now!

[assembly: ExportFont("fa-regular.otf", Alias = "FontAwesomeRegular")]
[assembly: ExportFont("fa-solid.otf", Alias = "FontAwesomeSolid")]

Like this label that shows a little globe icon using Font Awesome!

	VerticalOptions="Center" />

Yeah Font Awesome is pretty handy!


Fix Android Status bar…

I know its annoying to deal with Android Status bar styling, and most of the time devs don’t even bother fixing it accordingly to their app theme. They end up leaving the ugly blue color bar at the top of the app.

But I wanted to make it right. May be I am too much of a perfectionist! 😛

    <style name="MainTheme.Base"
        <item name="colorPrimary">#bfbfbf</item>
        <item name="colorPrimaryDark">#d9d9d9</item>
        <item name="colorAccent">#808080</item>

So I updated the Android Status bar styling values accordingly to my intended color scheme for the app.

PancakeView is yummy!

Yo this right here is a gem, such an awesome element to have in your app, provides loads of features and customization. https://github.com/sthewissen/Xamarin.Forms.PancakeView

It’s super simple to use, where I’ve used it as a container for many elements to provide a beautiful Shadow effect.

	<Grid Margin="0">
		<Image Aspect="AspectFill" Source="{Binding ImageUrl}" />

I’ve used this beauty across the entire app in all pages to give a gorgeous gradient effect of Page background as shown below…


I’m so glad I came across this awesome nugget thanks to this challenge! 😀

Beautify XAML…

One thing I noticed in the original project was that the XAML wasn’t properly formatted and it was inconsistent with different tabs and spacing.

I would recommend using any XAML formatting tool in Visual Studio like XAMLStyler which automatically formats your XAML properly while you code. Something nice to have I assume. 😉

Let me make it prettier…

On top of my head, I did not like the UI, not at all. Not blaming the original devs, who’s done a great job putting it together, but I wanted to re-skin it my way, and sprinkle a bit of eye-candy awesomeness… 😉

One thing I love for sure, is building sleek, responsive, minimalistic and yummy looking Mobile App UIs. So that’s what I did. 😀 I decided to implement a minimalistic unified-white color based gradient-ized sleek UI, which called for a whole bunch of restructures in the UI.

So I changed all the color schemes they used and replace them with a white and dark-gray based gradient style in almost all the elements across the app.

Let’s look at those one by one…


Who doesn’t love some good old gradient effects, at least when its well done!

Thanks to the PancakeView we can now easily add this effect to Xamarin.Forms elements, which I have used extensively in my UI design changes as well…

Here’s one example where I modified the AddPicture page with my new color scheme.

Splash it up!

One of the first things I wanted to get rid of was the original splash screen, I did not like it at all, and it was honestly scaring to see a cute little monkey exploding in a high speed animation on the screen. lol

So I change the whole splash screen animation into a smooth zoom-in and fade-out effect as shows in the code below…

private async Task AnimateTransition()
	await Task.Delay(1000);

	// Scaling up smoothly upto 5x and Fading out as the next page comes up.
	var explodeImageTask = Task.WhenAll(
		Content.ScaleTo(5, 300, Easing.CubicOut),
		Content.FadeTo(0, 300, Easing.CubicInOut));

Once it completes we navigate to the MainPage. Now that animation was much pleasing to look at…

I felt like that cute little monkey got some justice! lol

Home page!

So like I mentioned before I laid out a full layout design restructure and one of the main pages was the Home page.

  • Getting rid of confusing layout
  • Focusing on the travel photo background
  • Getting rid of the empty space
  • Making sure content properly fills the page

This is a travel related app, so it should be focused on giving such experience for the user so I decided to maximize on the scenic travel photos in the home page, thus resizing the Image element to take up to 70% of the page space.

Also I’ve added navigation for the user to click on the destination name to and to be navigated to that travel destination’s scenic travel photo gallery page.

Look at that beauty eh! 😉

The user picture grid at the bottom, while giving it a fixed height, I managed to fix a whole bunch of alignment issues inside the template container as well.

I added a new element above the translation text element for the user, to select a destination where they would like to view, and navigate to that page from home page itself.

Woot! woot!

Next’s let’s see that beauty in action…

Travel Destination Page…

So from the home page once User selects a travel destination to view, then they get navigated to this gorgeous page filled with scenic travel photos of that destination, pulled from Bing Image Search results…

It gets even better, here’s what you see when you select Italy…

Truly gorgeous… Well I’ve used Pancake View here for the full page background for the gradient effect and shadow effect for the Image containers.

		... >
		<Grid Margin="0">
			<Image Aspect="AspectFill" Source="{Binding ImageUrl}" />


Translation revamped!

So as I mentioned before I’ve implemented a new feature extending Bing Translation, allowing the user to pick the languages they want to have their input text translated into.

Here’s the new Page I implemented for it, where I load the list of languages for the user to choose from. I love how Bing translation actually provides the native word for the languages in their own language. 🙂 pretty neat eh!

Once the user selects the languages, I will be saving that in the memory as user preferences. Then next time User enters any text for translation, I would be showing them the list of translations according to their preferred languages. 😀

Now ain’t that handy! 😉

Last minute Pull requested!

Yes, literally last minute! So after all that panic filled sleepless all-nighter effort, I manged to finish up some good looking app with cool features added, and trust me when I say, I literally submitted the Pull Request at the very last minute, exactly at 11:58 PM on April 30, 2020 PDT. Just one minute before the deadline! 😀

Here’s my Pull Request on github: https://github.com/jfversluis/TravelMonkey/pull/25

That was such an adventure, I think this was the first time I stayed up all night for coding, after many years since graduation! 😀

Here’s the repo in my github: https://github.com/UdaraAlwis/TravelMonkey

Well I could have done a much better job, in terms of features, code refactoring and standards, if I hadn’t procrastinated till last minute. I wouldn’t blame someone, if they looked at the code and complained, hence its not the cleanest considering my usual quality standards! but I would consider it was a satisfying completion, given the whole last minute stress and staying up a whole night! 😛

We got Swag!

So as they promised we got them swags yo! 😀

But but… later I got even a better news,

Well at the end all the participants got $25 gift codes to spend at .NET Foundation store! 😀 yaay! 😍

Oh well.. what an adventure! Thank you Microsoft! ❤️


This was such an awesome opportunity, and I’m glad I pulled through somehow even if it was last minute effort! It was actually fun! Learned another lesson not to procrastinate stuff like these till last minute, at least not till 24 hours prior to submission deadline. lol

Sharing a bit of Azure bits, it was surprisingly easy to integrate all these kinds of cool features with Azure Cognitive Services without having to deal with any complicated computing. If it was few years back I would have to deal with all these language translation and image processing stuff all by myself.

So glad I found the new PancakeView thanks to this challenge, it was quite handful, specially in crafting those beautiful gradient and shadow effects.

Finally I should send special thanks to Microsoft and @jfversluis @codemillmatt for this awesome opportunity!

Share the love! 😀 Cheers yol!

How to resolve – Failed to validate credentials with APNS in Azure Notification Hub …

So this happened when I was in the midst of moving one of my Azure Notification Hubs into a new one, where during the configuration I removed the APNS certificate (p12 file) from the old Azure Hub and tried uploading to the new Azure Hub, but during the upload there was some network interference and it didn’t get uploaded and I refreshed the page.

So then I tried again, I got to be honest the internet connection was pretty messed up that day, and the above same scenario happened two more times and I wasn’t able to upload the file. Then after yelling at the Network admin, and getting the connection fixed up, I tried reuploading the p12 file.

Then suddenly this error popped up…

Failed to validate credentials with APNS. Error is Authentication failed because the remote party has closed the transport stream…

Below is a screenshot of the weird moment I experienced.


The reason why I called it was weird because, there shouldn’t be any issue with the p12 file as I had generated it accordingly and I also had used it before. So I dived into the issue online.

After going through some posts, I couldn’t find anyone who’s had the same above issue, and even they had similar issues, they were able to fix it by regenerating the p12 file as they had missed some steps during the previous creation. So just like that I was clueless…

So I assumed that this must be coming from the APNS authentication service end, which should probably be some unexpected error. And also could be the cause of me trying to upload the same p12 file several time and got interrupted in the middle of the upload due to the network connectivity issues.

So what I did was I waited for about 15 minutes, hoping for the APNS service to clear out the logged error and stop my upload from being rejected, cleared the web browser cache in case if some cookies were messing it up, and changed my IP Address, as if by any chance they were tracking the upload client through the IP address, so with a new IP it would be considered as a fresh upload. Then I tried uploading, guess what ? it worked like a charm ! 😀

It seemed to be my above assumption was right, and probably I was being kicked out by the APNS service for continually failing the file upload.

So I just put up this blog post if by any chance someone experiences the same issue and had no clue what to do, and this is how I resolved it… 😀

Hope this was helpful for any of your fellow awesome developers out there…

Cheers ! 😀 Stay Awesome ! ^_^


Microsoft Azure Notification Hub Diagnostics in Visual Studio…

So the other day I wanted to Monitor some activities in my Azure Notification Hubs, well of course you get the “Monitor” tab in the ANH panel online, but it’s hard to get into details with it as it only shows numerical statistics. I wanted to be more specifically look into the Device registrations, platform types, available Tags usage, registration expiration and so on.

Then quite surprisingly I came through this tool which was sitting right inside Visual Studio this whole time, which I hadn’t noticed before. Behold, the “Azure Notification Hubs Diagnostics” tool in Visual Studio. (Well actually Microsoft hasn’t given it a proper name though 😛 , but I wish if they did…)



(Sorry I had to blacken out the sensible information 😉 )

Just as a side-note I actually wish if Microsoft included these features in the online Azure Notification Hub Monitoring panel as well.

I’m really surprised why I haven’t noticed about this tool this whole time working with Azure PNH ! Therefore I thought of writing a small article about this awesome tool, if by chance any of you fellow awesome developers had missed on this tool… 🙂

Yes its pretty useful…

With the use of this tool you could do easily accomplish all the following requirements,

  • Easily Send Test/Debug Push Notifications (A huge variety of devices through respective PNS)
  • View all the Device Registrations along with their Platform types, Tags, PNS Identifiers, Registration IDs, and Expiration Days.
  • View all the above info in real time as it updates
  • Edit any Tags of the registered devices
  • Remove any Registrations
  • Sort through your specific Tags of the registered Devices
  • View overall registration stats of each platform
  • and many more uses if you are smart enough… 😉

Yep it’s sitting right here…

Simply go to your Sever Explorer Panel -> Sign into your Azure Account (click on Connect to Microsoft Azure Subscription) -> expand Notification Hubs -> choose your desired Notification Hub -> Right Click -> Diagnose !


It will open up the Azure NH diagnostics tool, and let the fun begin… 😉

Sending Test/Debug Push Notifications…

When you open up the Diagnostics, by default it opens up the Test/Debug Push Notification Panel as follows.


As I have highlighted above, this option beings some very useful features. You could include the tags you need to include in your test push notification messages easily or if you want to send without tags, you could keep the Broadcast option.

Next you will be surprised that there is a long list of mobile platforms you could choose to send the test notification as shown below.


Best yet it also by default generates the sample body, and you just have to insert the required parameters and values, and hit send.

Let’s say if you wanted Widows Phone – Toast type notification ? No problem !


oh how about Apple iPhone type notification ? Here you go…


Likewise, it is super easy to send test push notifications right from here.

Not only sending. but also viewing their results could be done in a very specific manner, which devices received them, any errors occurred and so on. 😉

Viewing Device Registrations and other Stats…

This awesome tiny tool also allows you to view all of the Device Registrations along with the following very useful information.

  • Platform
  • Registration Type
  • Tags
  • PNS Identifier
  • Registration ID
  • Expiration Date

Now the above information may seem quite preliminary, but still when it comes for serious monitoring and debugging those are very useful.


Simply go to the “Device Registrations” tab to navigate to this section and start playing…

Now we all know how much we use tags along with our Azure Notifications, which is an incredible feature that allows us to send targeted push notifications to groups or individual devices. And guess what ? this tool allows you to easily search and filter through any available tags and view those registration information.


Also you can easily sort through the above listed information columns (Platform, Registration Type, Tags, etc) by acceding or descending order as you wish, which makes it really easy to monitor and debug.


What if you ever wanted to Edit or Remove some registrations or their data in case of an emergency ? Yep you can easily do that from this tool.


Yep do you see that tiny set of controls in the top left side of the panel ? It allows you to easily,

  • Edit any available Tags
  • Delete any selected Registrations
  • Refresh the Registrations in real time

which are very much useful when monitoring and debugging push notification processes. 😉

Finally another feature this brings is the overall registration statistics of any given platform, which is useful but not very informative though as much as the “Monitor” tab in the online Azure NH Console.


There you go, if you haven’t yet noticed about this useful tool, head in right now and give it a try. I grantee you it will come very handy in cases of monitoring and debugging you push notification related executions… 😉
I still wish if Microsoft had made all the above features available in the online Azure Hub Monitoring section, which I sincerely hope they would do someday.
The above mentioned features may not seem to be advance enough, but still they become very handy and useful and if you are smart enough you could use this for many more other purposes.. 😀

Hope this was helpful for any of your fellow awesome developers out there… 🙂

CHEERS ! Stay Awesome ! ^_^

UPDATE 26/10/2015 : 

One of our readers @milenppavlov has suggested another great tool for even more detailed diagnostics for Azure Notification Hub. And yes I agree with him, it seem to be a very useful tool. So if any of you are looking for more specific diagnostics try his recommendation here. https://code.msdn.microsoft.com/windowsapps/Service-Bus-Explorer-f2abca5a



So I just implemented Push Notifications in awesome Xamarin.Forms … ;)


So about one month back my boss asked me to implement Push Notification support in one of the Xamarin cross platform based enterprise apps we were working on, which is fully implemented with Xamarin.Forms ! We had a Microsoft Azure Account purchased and dedicated for this certain project, which was a lucky point for me having worked with Azure Notification Hub before.

Praising Documentations…

Being all enthusiastic, I started by going through the official Microsoft Azure Documentation. It was very well documented, they had articles for Android, iOS, Windows Phone, Xamarin.iOS, Xamarin.Android and even Baidu. But unfortunately not for Xamarin.Forms, the ultimate cross platform awesomeness from Xamarin 😦 !


Oh well that was most certainly a saddening moment… Actually it was said that there isn’t any proper library which supports Azure Push Notifications in pure Xamarin.Forms yet…

The decision time…

The requirement of my task was a bit simple, Send a push notification to the client’s mobile phone with some parameters and values in it, and when the user tap on the push notification, the app should open up and display any given information through the push notification.

So as the requirement sounded bit simple, I thought of implementing the Azure calls natively in Xamarin (such as Xamarin.Android and Xamarin.iOS project levels), rather than worrying about not being able to implement in PCL project code.

Of course I could have also used dependency injection in this case, but I didn’t have to go that far as my requirement was a bit simple.

Something tid bits to Consider…

Took me about a few days to figure out the whole implementation and get it to working properly. I gotta say the official Azure Notification Hub documentation by Microsoft was a great help, despite it didn’t give any support for Xamarin.Forms ! So I thought of sharing some of the code I had used during my implementation here, which I believe might be useful for you and better optimized than the documented ones. I won’t be explaining everything here as most of the steps are very well documented in the Microsoft Azure documentation, in order to avoid repetition…
Please keep in mind, if this is the first time you are implementing Azure Push Notifications in your Xamarin project, please refer to the official Microsoft Azure documentation first and then only come back here, otherwise it could be a bit confusing for some of you.


Before you get started, this is what you need to keep ready… 😉

Working Azure Account – We are going to use Azure Notification Hub as our Push Notification distribution server. Your GCM and APNs services will be connected to this and Azure will handle all the delivering the notifications through them.

Create an Azure Notification Hub service – If you haven’t created a Notification Hub yet please follow the easy steps through the Azure documentation. And also under that, you can check out how to enable the Push Notification in your Windows Phone App.

Working Google Cloud Messaging Service (GCM) – We need this in order to deliver our Push Notifications to the Android users . This will be connected this to our Azure Notification Hub. If you don’t have a GCM enabled, then head into the Azure documentation and follow the well explained steps. Trust me it only takes few minutes… Get started with Notification Hubs – Xamarin.Android

Working Apple Push Notification Service (APNs) authenticated app registration – We need this in order to connect the APNs to our Azure Hub, which will deliver the Push Notifications to the iPhone users.  In iPhone dev, you need to enable Push Notification services from the provisioning profiles of your app and regenerate them. You may refer to the Azure documentation, which is very well explained.. Get started with Notification Hubs – Xamarin.iOS

So all in all, please refer to the official Azure documentation, and get the basics Project setting up done as I haven’t mentioned every detail here to avoid repetition, and then refer to this documentation. 🙂

PCL Implementation…

So you wanna open the app and direct your user to a separate page in the app when the User taps on the Notification displayed on the device ? Then you could use the following sample code in your PCL shared project.

public class App : Application
   public App(String PushNotifParameter = null)
	   if (PushNotifParam == null)
		   // The root page of your application
		   MainPage = new NavigationPage(new HomePage());
		   // For Android and WinPhone
		   // Process the Push Notification click....
		   MainPage = new PushNotifMessageDisplay(PushNotifParameter);


As you have seen I added a parameter with a default null in the App() constructor, so that when the user taps on the Push notification on the phone, we can call the constructor with any given parameter, so we can determine whether to direct the user to the default home page or the push notification display page.
But keep in note this method only works for Android and Windows Phone, as in iOS you can’t catch the Push Notification message tap in the FinishedLaunching() method which is the executing point in Xamarin.iOS ! But not to worry, I have solved that issue as well, which I will show you in the iOS implementation section.

Here is the push notification display page. This is where the user will be directed when they click on the Push Notification displayed on the device.

public class PushNotifMessageDisplay : ContentPage
	public PushNotifMessageDisplay(String parameterValue)
		Title = "Awesome App";

		Button btn_GobackToHome = new Button
			Text = "Go back to Homepage",
			TextColor = Color.White,
			BackgroundColor = Color.FromHex("#FF3300"),
			BorderRadius = 0,
			BorderWidth = 0,
			BorderColor = Color.FromHex("#FF3300"),
			VerticalOptions = LayoutOptions.EndAndExpand,
			HorizontalOptions = LayoutOptions.FillAndExpand,

		btn_GobackToHome.Clicked += (sender, args) =>
			App.Current.MainPage = new NavigationPage(new HomePage());

		Content = new StackLayout
			VerticalOptions = LayoutOptions.FillAndExpand,
			HorizontalOptions = LayoutOptions.FillAndExpand,
			BackgroundColor = Color.White,
			Padding = new Thickness(10, 5, 10, 10),
			Children = {
				new Label {
					VerticalOptions = LayoutOptions.CenterAndExpand,
					HorizontalOptions = LayoutOptions.CenterAndExpand,
					XAlign = TextAlignment.Center,
					FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
					Text = "This is the Push Notification Message Display Page ! The paramaters from the Push Notification will be displayed here..." + "\n\n" + parameterValue,


You may customize the above as anyway you wish to… 😉

Xamarin.Android Implementation…

Now lets move on to the Native implementation, please keep in mind, most of these native implementation code is much similar to the official document code. But I have improved them to perform better and cater for the exact requirement I was hoping to achieve…

Create a new class called ConstantsPushNotif and add the necessary information. Please make sure to insert your Google Cloud Messaging API information and Azure Notification Hub connection information. This class will hold all the necessary constant values for accessing GCM and Azure Notification Hub through our app.

class PushNotifications_Constants
	public const string SenderID = "xxxxxxxxxx"; // Google API Project Number

	// Azure app specific connection string and hub path
	public const string ConnectionString = "<Listen connection string>";
	public const string NotificationHubPath = "<hub name>";


Now some of you might get confused about those values above, so here is a small how-to guide. These constant values will be used in all three native platforms projects. Or else for your ease of use, you could define those values in your PCL class as public and refer to them when required from the native project code.

Azure Hub Path / Hub Name


Azure Hub Listening connection string

how you get the Azure Hub Listening connection string,


Google API Project Number

Wondering how to get the Google API Project Number ? Here it is..


We need to create a broadcast receiver for receiving Push Notifications, and below is the code I have used. Most of the below code was extracted from the Azure documentation, but some I had optimized, such as the Android Notification display section and please note that I have removed all the debug messages.

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is only needed for android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace WhateverYourNamespace.Droid
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    public class MyBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
        public static string[] SENDER_IDS = new string[] { PushNotifications_Constants.SenderID };

        public const string TAG = "MyBroadcastReceiver-GCM";

    [Service] // Must use the service tag
    public class PushHandlerService : GcmServiceBase
        public static string RegistrationID { get; private set; }
        private NotificationHub Hub { get; set; }

        public PushHandlerService()
            : base(PushNotifications_Constants.SenderID)

        protected override void OnError(Context context, string errorId)


        protected override void OnMessage(Context context, Intent intent)
            var msg = new StringBuilder();

            if (intent != null && intent.Extras != null)
                foreach (var key in intent.Extras.KeySet())
                    msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());

            string messageText = intent.Extras.GetString("msg");
            string parameterText = intent.Extras.GetString("param");
            if (!string.IsNullOrEmpty(messageText))
                CreateNotification("Awesome Notification...", messageText, parameterText);

            // If the incoming message's parameters couldn't be recognized, then this Notification will be published...
            CreateNotification("Awesome Notification...", msg.ToString());

        protected override void OnRegistered(Context context, string registrationId)
            RegistrationID = registrationId;

            Hub = new NotificationHub(PushNotifications_Constants.NotificationHubPath, PushNotifications_Constants.ConnectionString, context);
            catch (Exception ex)


            var tags = new List<string>() { "falcons" }; // create tags if you want

                var hubRegistration = Hub.Register(registrationId, tags.ToArray());
            catch (Exception ex)

        protected override void OnUnRegistered(Context context, string registrationId)

        void CreateNotification(string title, string desc, string parameters = null)
            Intent startupIntent = new Intent(this, typeof(MainActivity));

            startupIntent.PutExtra("param", parameters.ToString());

            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);



            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(this)

            // Build the notification:
            Notification notification = builder.Build();
            notification.Flags = NotificationFlags.AutoCancel;

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);


Parameter Passing through Push Notification..

Now as shown above you might have noticed a keyword calle “param”, and thats the parameter I’m planning passing pass through. We can pass any amount of parameters or values through Push Notifications, just gotta figure out the pattern to include it in the code for each specific platform. 😉
When you move ahead this article, you may see how I have handled the “param” value in three native platform code and as well as server side. I hope you would be able to take that as an example and add more parameters as you wish. 🙂

Now lets see the code for the MainActivity class of your Xamarin.Android project. There as you can see, inside the OnCreate() method I’m catching the parameter passed through the Intent, which will be passed in by the Push Notification alert message displayed in the phone. Based on that I’m redirecting the user to the home page or the separate Notification info display page.
And also every time the app starts up it will get registered withe GCM service for updating the notification token for the device.

namespace WhateverYourNamespace.Droid
    [Activity(Label = "WhateverYourNamespace", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
        protected override void OnCreate(Bundle bundle)

            global::Xamarin.Forms.Forms.Init(this, bundle);

            string parameterValue = this.Intent.GetStringExtra("param");      
            if (parameterValue != null)
                LoadApplication(new App(parameterValue));
                LoadApplication(new App());


        private void RegisterWithGCM()
            // Check to ensure everything's setup right

            // Register for push notifications
            GcmClient.Register(this, PushNotifications_Constants.SenderID);


So let’s head into iOS implementation…

Xamarin.iOS Implementation…

Before you begin make sure you have enabled Push Notification Services in your App’s Provisioning Profiles… If you haven’t done it yet, as I mentioned earlier please follow the official Microsoft Azure Documentation for Xamarin.iOS  which explains very well step by step..

Here is how you could make sure… In the dev center, check the Services section under your app ID..


And check your Provisioning Profile status…


Don’t forget to re-download all your Provisioning profiles and install them in your iOS buld host through XCode !

So when it comes to the coding, first add the Constants class as we did in Xamarin.Android..

class PushNotifications_Constants
	// Azure app specific connection string and hub path
	public const string ConnectionString = "<Azure connection string>";
	public const string NotificationHubPath = "<Azure hub path>";


Then replace your AppDelegate code as following…

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
	private SBNotificationHub Hub { get; set; }
	public override bool FinishedLaunching(UIApplication app, NSDictionary options)
		if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
			var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
							   UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
							   new NSSet());

			UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;

		LoadApplication(new App());

		return base.FinishedLaunching(app, options);

	public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
		Hub = new SBNotificationHub(PushNotifications_Constants.ConnectionString, PushNotifications_Constants.NotificationHubPath);

		Hub.UnregisterAllAsync(deviceToken, (error) =>
			if (error != null)
				Console.WriteLine("Error calling Unregister: {0}", error.ToString());

			NSSet tags = null; // create tags if you want
			Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
				if (errorCallback != null)
					Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());

	public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
		ProcessNotification(userInfo, false);

	void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
		// Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
		if (null != options && options.ContainsKey(new NSString("aps")))
			//Get the aps dictionary
			NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

			string alertString = string.Empty;
			string paramString = string.Empty;

			if (aps.ContainsKey(new NSString("alert")))
				alertString = (aps[new NSString("alert")] as NSString).ToString();

			if (aps.ContainsKey(new NSString("param")))
				paramString = (aps[new NSString("param")] as NSString).ToString();

			if (!fromFinishedLaunching)
				//Manually show an alert
				if (!string.IsNullOrEmpty(alertString))
					UIAlertView avAlert = new UIAlertView("Awesome Notification", alertString , null, 
						NSBundle.MainBundle.LocalizedString("Cancel", "Cancel"),
						NSBundle.MainBundle.LocalizedString("OK", "OK"));

					avAlert.Clicked += (sender, buttonArgs) =>
						if (buttonArgs.ButtonIndex != avAlert.CancelButtonIndex)
							if (!string.IsNullOrEmpty(paramString))
								App.Current.MainPage = new NavigationPage(new PushNotifMessageDisplay(paramString));



As you can see above I have utilized the code whereas when ReceivedRemoteNotification() gets fired by receiving the push notification from APNs, a message will be displayed, and if the user selects ‘OK’ then the user will be redirected to the notification message display page. Or else if they click ‘Cancel’ the notification will be dismissed.

So let’s move on to Windows Phone implementation.

Xamarin.WinPhone Implementation…

I must admit that Windows Phone implementation was the easiest of all, Thanks to Microsoft’s direct support.

Before you start make sure that you have enabled Push Notifications permission in your WinPhone Project’s WMAppManifest configuration.


First of all in your App class, replace the Application_Launching method as following…

private void Application_Launching(object sender, LaunchingEventArgs e)
	var channel = HttpNotificationChannel.Find("MyPushChannel");
	if (channel == null)
		channel = new HttpNotificationChannel("MyPushChannel");

	channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
		var hub = new NotificationHub("<Azure hub path>", "<Azure connection string>");
		await hub.RegisterNativeAsync(args.ChannelUri.ToString());


Its actually pretty much the official documentation code. And below is how you should change your MainPage class whereas the native firing point of the native WinPhone execution…

public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage
	public MainPage()
		SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)

		if (NavigationContext.QueryString.ContainsKey("param"))
			string strValue = this.NavigationContext.QueryString["param"];

			LoadApplication(new WhateverYourNamespace.App(strValue));
			LoadApplication(new WhateverYourNamespace.App());


And that’s all for the Windows Phone…. TADAAAAA ! 😀
WAIT ! We are not done yet… Now that we have developed the Push Notification enabled client apps, how we are gonna send Push Notifications to them ? 😀

Push Notification Distribution Back-end

One way to send notifications to your Push Notifications enabled apps would be through the  Debug feature in Azure Notification Hub, which is a really great feature.
Simply navigate to the “Debug” tab in your notification hub, choose the platform, type the Push Notification message and finally hit send. Well based on the type of mobile platform it gives some extra features as well, give them a try if you are interested…


PLOT TWIST ! 😀 Or you could create your own Push Notification Distribution server… 😉

Create your own Push Notification Distribution Back-end

For that you need a Azure Hub Full Access connection string, which might cause for some confusion for some of you as we have used the Listening Access string. This connection gives us the permission to send push messages through our Azure Notification Hub.

Azure Hub Full Access connection string…



Now If you want to create you own dummy server, here is some well optimized code you could use by creating a simple .net Console Application, which I coded by myself when I was playing around for the first time…

class Program
	static void Main(string[] args)
		String PushNotif_Message = "Hello World !";
		String PushNotif_Parameter = "THISISATESTPARAMETER";
		Console.WriteLine("Press any key to send the Android push Notifications...");
		SendNotification_Android_Async(PushNotif_Message, PushNotif_Parameter);

		Console.WriteLine("Press any key to send the Windows Phone push Notifications...");
		SendNotification_WinPhone_Async(PushNotif_Message, PushNotif_Parameter);

		Console.WriteLine("Press any key to send the iPhone push Notifications...");
		SendNotification_iOS_Async(PushNotif_Message, PushNotif_Parameter);

		Console.WriteLine("Completed ! :)");

	public static async void SendNotification_Android_Async(String Message, String parameter)
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
			String pushMessage = "{ \"data\" : {\"msg\":\"" + Message + "\",\"param\":\"" + parameter + "\"}}";
			NotificationOutcome result = await hub.SendGcmNativeNotificationAsync(pushMessage);

		catch (Exception ex)


	private static async void SendNotification_WinPhone_Async(String Message, String parameter)
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
			string toast = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
			  "<wp:Notification xmlns:wp=\"WPNotification\">" +
				 "<wp:Toast>" +
					  "<wp:Text1>" + Message + "</wp:Text1>" +
					  "<wp:Param>?param=" + parameter + "</wp:Param>" +
				 "</wp:Toast> " +
			NotificationOutcome result = await hub.SendMpnsNativeNotificationAsync(toast);

		catch (Exception ex)


	private static async void SendNotification_iOS_Async(String Message, String parameter)
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");

			var alert = "{\"aps\":{\"alert\":\"" + Message + "\",\"param\":\"" + parameter + "\"}}";
			NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(alert);

		catch (Exception ex)


Also you can see how I have attached parameter value to my push notifications, by adding the “param” variable as I explained at the beginning of this article. Likewise you can add any amount of parameters and pass through your Push Messages, but to keep in mind you have to handle those parameters properly in the Mobile app level as well… 🙂

AAAAND THATS IT !!!!!! 😀 Hit F5 and Send the Push Notifications as you wish ! 😉

but be cautious, there is a high possibility of you going crazy by sending random push notifications to your test devices when you try this out for the first time… lol 😀 (personal experience) 😉

Eh bunch of unexplained phenomena… O_o


Yep that’s right, when I was playing around with Azure Notification Hub and Push Messages, I encountered a few anomalies or in other words a few unexplainable phenomena… 😛 lol don’t worry I ain’t talking about Aliens or Ghosts.. 😉

Incompatibility in Azure Messaging Components

When I followed the Azure documentation, I downloaded the Azure Messaging component for Xamarin (for Xamarin.Android and Xamarin.iOS) as it instructed. After I finished coding, the project compiled without any issue, but then when I deployed it and executed in the device, the app started crashing. Then I tried to debug the app and realized it was giving a runtime exception in both Xamarin.Android and Xamarin.iOS projects, when it initializes the Azure library.
After a while I found out its causing the runtime error due to this,
System.MissingMethodException: Method not found: ‘Android.Runtime.JNIEnv.StartCreateInstance’
Frankly it’s because of some incompatibilities in the Message Component library version and Xamarin.Forms ! 😦

So I tried out an older version of the Azure Messaging component for Xamarin and it luckily worked. Therefore if you are not using the latest Xamarin version, I recommend you use this version for you Xamarin Azure Messaging Component library, http://components.xamarin.com/view/azure-messaging?version=


Anomalies in Azure Notification Hub

Here is another weird situation I noted, after finishing the coding I tried to send my first set of push notifications through the command line client I built. But it wasn’t working, there were no compiling errors or any runtime errors also. But then just out of random I thought of sending a debug push message right from the Azure Hub, and suddenly it all started working fine.

So for the first time if the Push Notification you send from the Command Prompt client are not being delivered to your devices, then try sending a debug test push notification from the Notification Hub directly. It will work… this is pretty strange though, hope Microsoft will fix this soon. 🙂

When you follow the official documentation code…

If you are following the Azure Documentation code when creating your Push Notification distribution back-end client, make sure to await for the response from the SendNotificaitonAsync() method.
Otherwise right after calling the method you are probably closing the Command Prompt window before the action is actually completed asynchronously. This could also cause of unsuccessful message delivery from your client to the Azure Notification Hub. Create an instance of NotificationOutcome class and await for the result from the SendNotificationAsync() method, as I have done in my code in above example and below… 😉

NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(alert);

Console.WriteLine("Result : " + result.State.ToString());


A Ghost activity in Google Cloud Messaging API…

So once I was doing some continuous testing Xamarin.Android with Push Notifications using Azure Notification Hub, and suddenly out of nowhere Push Notifications stopped working for Android. I sent several push notifications for Android but none of them got delivered for the test devices. I was wondering whether I was sending too many pushes and the server was rejecting my requests, but it was just about 2 or 3 pushers per hour as displayed in Azure Hub statistics. I tried sending a debug message from the Azure Notification Hub as well, but it didn’t work either.

Then I checked on my Google Cloud Console, and I saw that Android Cloud Message API has gotten disabled out of nowhere, which I had enabled way before. Then I enabled it, but still no luck. So just to take a shot in the dark, I regenerated  the Public access key in the GCM and re-added it to Azure Notification Hub, and BOOM ! it started working…

Looks like some kind of a bug in GCM API, so if you ever come across anything similar as above, try out the steps I took, might also work for you… 🙂

POST UPDATE 16/09/2015

Once again proving Microsoft has done a great job at their documentation, I found out this article, where it will guide you through all your troubles in NS related issues. Did you know you could view the actual status of the published notification message ? and you could view the registered devices right from Visual Studio ? Yep ! head into this link for any issues your having, it will surely help you as it did for me… 🙂



Well folks thats all about it… I must say the new Azure Notification Hub is a great way to be used for Push Notifications and its very easily manageable. Even though it is not yet directly supported for Xamarin.Forms, you can easily get around that issue by utilizing its support for Windows Phone and Xamarin overall as I have done… 😉

Through this article I didn’t want to spoon feed everything from the scratch because there is already a great documentation out there by Microsoft (kudos to that), just wanted to share some of my personal project implementation and experience. I sincerely hope this was helpful for you all, if so please share this article with your fellow developers… 😀

Stay awesome fellow Geeks ! ^_^