Tag Archives: Azure Push Notifications

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…)

Capture22

Capture21

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

Capture20

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.

Capture23

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.

Capture24

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 !

Capture25

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

Capture26

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.

Capture19

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.

Capture24

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.

Capture25

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.

Capture24

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.

Capture26

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

 

 

Advertisements

Handling Push Notifications in Xamarin iOS when App is Closed…

Few months back I wrote an article on implementing Push Notification in awesome Xamarin Forms, So I just implemented Push Notifications in awesome Xamarin.Forms … 😉 after my personal experience at work. And YES ! it works like a charm without any doubt.

Something Spooky…

But after a while I noticed something in Xamarin iOS app, whereas when we send out the Push Notification from Azure Hub, the notification gets received by iPhone, and when I click on the Notification alert, it gets opened up in the app and displays the redirected page. But sometime, when I click on the received push notification alert, the app opens up, but the push notification message box doesn’t get displayed or gets redirected to the message display page. In short, sometimes the push notification alert click only opens up the app, nothing else.

Okay What is happening…

After careful observation I noticed that, when the app is running or if its in the background, and I click on the push notification alert, it gets opened up in the app and everything works fine. But when the app is closed or not running in the background, the push notification alert only opens up the app, and it doesn’t get redirected to the message display page or anything.

But Why is this happening…

I realized this after going through the push notification alert click event, which is ReceivedRemoteNotification() 

Capture

This method gets fired when the User clicks on the received push notification alert on the phone. And from there it calls the ProcessNotification method where it displays the Push Notification alter Message Box and redirects the user to the give page in the app.

But it gets fired only when the app is already running or if its running in the background stack. If you have restarted the phone or closed the app or by any chance if the app is not running in the background, this method will not get fired upon above push notification action. And thereby it will only open up the app. 😦

So What is the Solution…

So what we need to do here is to detect at the FinishedLaunching() method whether the app was opened up by a Push Notification alert click or manual app icon click by the User.

This is a common scenario most of the developers has faced, not only in Xamarin Forms related iOS even in native iOS development. But most of us don’t realize this as it’s very hard to notice this scenario, because we usually don’t manually close apps in our iPhone devices. Even I got curious about this when my boss complained about this once, and yes took me a while to figure it out too… 😉

Alright ! Let’s patch it up !

Even though it took me a while to figure out the solution, it was quite simple to implement. The reason I’m sharing this is because there’s not much resources regarding this issue, probably because we don’t easily notice this issue.

This solution can be implemented easily for anyone even without following my previous Xamarin Forms push notifications implementation article, just do the changes as shown below, then you should be good to go. I’m not going to repost the whole code here, but only the necessary changes, but if you are looking for the full code, you may check up my article,  So I just implemented Push Notifications in awesome Xamarin.Forms !
Let’s begin…

Did you know, when our iOS app is closed and it gets opens up by the click on a Push Notification Alert, the system passes through a parameter in the NSDictionary options parameter in the FinishedLaunching() method which is called UIApplicationLaunchOptionsRemoteNotificationKey !

All we have to do is capture this parameter value in our FinishedLaunching() method and process the notification. Inside this key object contains the whole push notification object which we could easily extract. So add the following code to the end of your FinishedLaunching() method in AppDelegate class.

// Handling Push notification when app is closed if App was opened by Push Notification...
if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
{
	NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

	ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, false);
}

 

As you can see above we are checking for the existence of the UIApplicationLaunchOptionsRemoteNotificationKey object key value in the options parameter of FinishedLaunching() method. After extracting the object we are passing it to our usual ProcessNotification() method in order to do the usual processing of the push notification message.

After that tiny trick your FinishedLaunching() method should look like this… 🙂

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());

		UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
		UIApplication.SharedApplication.RegisterForRemoteNotifications();
	}

	else
	{
		UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
		UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
	}

	global::Xamarin.Forms.Forms.Init();

	LoadApplication(new App());

	// Handling Push notification when app is closed if App was opened by Push Notification...
	if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
	{
		NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

		ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, false);
	}

	return base.FinishedLaunching(app, options);
}

 

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much resources on Handling Push Notifications in Xamarin iOS when App is Closed, and you may save another developer’s time as well… 😉

Stay awesome fellow Geeks ! ^_^

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

Backstory…

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

Capture1

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.

Prerequisites…

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());
	   }
	   else
	   {
		   // 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,
				},
				btn_GobackToHome
			}
		};
	}
}

 

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

Capture7

Azure Hub Listening connection string

how you get the Azure Hub Listening connection string,

Capture2

Google API Project Number

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

Capture

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);
                return;
            }

            // 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);
            try
            {
                Hub.UnregisterAll(registrationId);
            }
            catch (Exception ex)
            {

            }

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

            try
            {
                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);

            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));

            stackBuilder.AddNextIntent(startupIntent);

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

            Notification.Builder builder = new Notification.Builder(this)
                .SetContentIntent(pendingIntent)
                .SetContentTitle(title)
                .SetContentText(desc)
                .SetSmallIcon(Resource.Drawable.icon);

            // 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)
        {
            base.OnCreate(bundle);

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

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


            RegisterWithGCM();
        }

        private void RegisterWithGCM()
        {
            // Check to ensure everything's setup right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);

            // 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..

Capture5

And check your Provisioning Profile status…

Capture6

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…

[Register("AppDelegate")]
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());

			UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
			UIApplication.SharedApplication.RegisterForRemoteNotifications();
		}
		else
		{
			UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
			UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
		}

		global::Xamarin.Forms.Forms.Init();
		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());
				return;
			}

			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));
							}
						}
					};

					avAlert.Show();
				}
			}
		}
	}
}

 

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.

Capture8

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.Open();
		channel.BindToShellToast();
	}

	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()
	{
		InitializeComponent();
		SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
	}
	
	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
	{
		base.OnNavigatedTo(e);

		global::Xamarin.Forms.Forms.Init();
          
		if (NavigationContext.QueryString.ContainsKey("param"))
		{
			string strValue = this.NavigationContext.QueryString["param"];

			LoadApplication(new WhateverYourNamespace.App(strValue));
		}
		else 
		{
			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…

Capture9

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…

Capture4

 

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.ReadLine();

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

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

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

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

			Console.WriteLine(result.State.ToString());
		}
		catch (Exception ex)
		{

		}
	}

	private static async void SendNotification_WinPhone_Async(String Message, String parameter)
	{
		try
		{
			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> " +
			  "</wp:Notification>";
			NotificationOutcome result = await hub.SendMpnsNativeNotificationAsync(toast);

			Console.WriteLine(result.State.ToString());
		}
		catch (Exception ex)
		{

		}
	}

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

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

			Console.WriteLine(result.State.ToString());
		}
		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

Untitled-1

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,
https://bugzilla.xamarin.com/show_bug.cgi?id=29466
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=1.1.5.3

🙂

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… 🙂

https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-diagnosing/

Conclusion

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

Call Asynchronous Methods and return Results within ASP Web API

So the other day my boss asked me to implement a few Azure Push Notifications related Web methods in one of our ASP Web API projects I had developed. Those Web methods were suppose to send Push Notification messages to the Azure Notification Hub, where as those notifications will be delivered to the User’s mobile devices.

When I started implementing I realized when calling the Azure Notification Hub using the Windows Azure Library, I realized there’s only Asynchronous calls available to communicate with the Notification Hub. It got me thinking, How on earth am I gonna call Asynchronous methods inside the ASP Web API (as I haven’t tried that before). Well, after a little bit of playing around I figured it out thanks to some documentations in ASP.NET website.

So here I am sharing the code I used for you all, if you ever come across such an implementation, how to call an Asynchronous methods inside the ASP Web API.

namespace YourNameSpace.Controllers
{
    [RoutePrefix("api/AsyncTest")]
    public class AsyncTestController : ApiController
    {
        [Route("AsyncWebMethod/{whateverValue}", Name = "DoSomeAsyncProcessingAndReturnResult")]
        [HttpPost]
        public async Task<HttpResponseMessage> DoSomeAsyncProcessingAndReturnResult(string whateverValue)
        {
            string Result = await WhateverAsyncMethodCallYouWantToCallInsideWebAPI(whateverValue);

            return Request.CreateResponse(HttpStatusCode.OK, Result);
        }
    }
}

 

Have fun Coding fellas ! 😀