WNS Push notification

Push Notification helps you in sending event or alert to your app users even when they are not logged into the app. App42 uses WNS (WIndows Push Notification Service) in order to send Push Notifications to your Windows Store App, your app must be registered with the Windows Store. This process requires a Windows Store developer account. You can send push notifications from AppHQ UI console as well as can use APIs to send and schedule Push notification to your app users. App42 also gives you interesting insight about analytics of push messages too. Here are the few easy steps to get started with App42 Push Notification using a sample project in a few minutes.

1. Prerequisite for WNS Push Notification
  • Register with App42 platform
  • Create an app once you are on Quick-start page after registration.
  • If you are already registered, login to AppHQ console and create an app from App Manager -> Create App.
2. Registering App with Windows Store
  • Go to the Windows Store Dev Center if you are already registered then go to your Dashboard otherwise register with Windows Store Dashboard. This dashboard manages the end-to-end process of managing apps on the Windows Store. If you already have an app for which you would like to add Push Notifications, then select the app in Apps menu and proceed to next step.
  • Click on Services -> Select Push Notifications, click the Live Services site link.

WNSDashboardImagepain

  • Now you can see your app credentials for Push Notification. These credentials consist of a Package Security Identifier (SID) and a Client secret, copy the credentials for later use.

WNSCredentialsImagepain

3. Configure your App With App42
  • Once you successfully get your WNS credentials, Log-in to AppHQ Management Console
  • Select your App -> Click on Unified Notification > Settings
  • Select WNS Settings > Click on View > Click on Add Keys button
  • Enter the Package SID and Client secret which you get in above steps and submit as shown in the below image:

WNSSettingImagepain

4. Using App42 WNS Sample
  • Download WinRT sample projects from our GitHub Repo
  • Unzip the downloaded file and open App42-WNS-Sample in Microsoft Visual Studio 2013 for Windows.
  • Once you done with the above steps, Open AppConstants.cs file and put your API KEY and SECRET KEY which you have received after the success of app creation from AppHQ Console as shown below and also put value of userName for which you want to register for push notifications.
 public const String apiKey = "APP_API_KEY"; // Apikey from AppHQ console.
 public const String secretKey = "APP_SECRET_KEY"; // SecretKey from AppHQ console.
 public const String userName = "UserName"; // UserName for which device has to be registered.
  • Build and Run the sample project on Local Machine or Device.
  • Click on any button to receive push notification on device/machine.
  • If you want to go into detail about the sample code, please see AppHelper.cs which does all WNS related work like registering with WNS and App42 server and generating notifications.
5. Integrating App42 WinRT SDK in your existing project.
  • Create a new app or using existing app in Visual Studio 2013.
  • Download and Import the latest App42 WinRT SDK dll in your project.
  • Associate your Visual Studio project with the Windows Store dashboard app by right clicking on the project in the Solution Explorer and select “Store” -> “Associate App with the Store” and finish the wizard.

WNSStoreAssociationImagepain

  • Enable Toast Notifications by opening your project’s package.appxmanifest file. In the Notifications under Application tab, be sure “Toast Capable” is set to “Yes”.

WNSEnableToastImagepain

6. Sending push notification through App42 WinRT SDK
PushNotificationChannel channel = null;
String channelURI = null;
try
{
   channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
   channelURI = channel.Uri;
   channel.PushNotificationReceived += OnPushNotification; // Calling Push notification listener. 
}
 
catch (Exception ex)
{ 
   // Could not create a channel. 
}
  • Initialize App42API in order to use App42 APIs and build PushNotificationService for using push notifications in your app.
 PushNotificationService pushNotificationService = null;
 public YourMainClassConstructor() 
 {
	// Initializing App42.
	App42API.Initialize(AppConstants.apiKey, AppConstants.secretKey);
	// Initializing PushNotification Service.
	pushNotificationService = App42API.BuildPushNotificationService();
 }
  • Now store the above channelURI as device token through the StoreDeviceToken. It will register the app with App42 server.This is only one time activity and will be done when app will be opened.
pushNotificationService = App42API.BuildPushNotificationService();
String userName = "UserName";
pushNotificationService.StoreDeviceToken(userName, channelURI, new WNSCallback()); // Here User name is identification to whom you want to register, 
// you can also use device id in place of UserName if you don't have 
// username in your app.

class WNSCallback : App42Callback
{

	public void OnException(App42Exception exception)
	{
		System.Diagnostics.Debug.WriteLine(":::EXCEPTION ::: " + exception.ToString());
	}

	public void OnSuccess(object response)
	{
		System.Diagnostics.Debug.WriteLine(":::SUCCESS ::: " + response.ToString());
	}
}
  • Once your app is registered with App42, then you can see the registered users in AppHQ console -> Unified Notifications -> Users -> View.

WNSPushUsersImagepain

Your app is registered you are ready to send push messages to your app users using following code snippet from any App42 SDK. Below is the snippet for App42 WinRT SDK. If you want to send it from other SDK you can do it in the same way.

  • Sending Toast Message to User.
public void SendToast()
{
	String userName = "UserName";
	String toastTitle = "ToastTitle";
	String toastContent = "ToastContent";
	Dictionary<string, object> toastParams = new Dictionary<string, object>();
	toastParams.Add("param1", "Value1");
	toastParams.Add("param2", true);
	toastParams.Add("param3", 1000);
	pushNotificationService.SendPushToastMessageToUser(userName, toastTitle, toastContent, toastParams, new WNSPushCallback());
}

class WNSPushCallback : App42Callback
{
	public void OnException(App42Exception exception)
	{
		System.Diagnostics.Debug.WriteLine(":::EXCEPTION ::: " + exception.ToString());
	}

	public void OnSuccess(object response)
	{
		System.Diagnostics.Debug.WriteLine(":::SUCCESS ::: " + response.ToString());
	}
}
  • Sending Tile Message to User.
public void SendTile()
{
	String userName = "UserName";
	Tile tile = new Tile();
	tile.Title = "TileTitle";
	tile.Content = "TileContent";
	tile.BadgeCount = "2";
	tile.BackgroundImage = "Image_Url";
	pushNotificationService.SendPushTileMessageToUser(userName, tile, new WNSPushCallback());
}

class WNSPushCallback : App42Callback
{
	public void OnException(App42Exception exception)
	{
		System.Diagnostics.Debug.WriteLine(":::EXCEPTION ::: " + exception.ToString());
	}

	public void OnSuccess(object response)
	{
		System.Diagnostics.Debug.WriteLine(":::SUCCESS ::: " + response.ToString());
	}
}
  • Implement push notification listener.
 private void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
        {
            String notificationContent = String.Empty;
            switch (e.NotificationType)
            {
                case PushNotificationType.Badge:
                    notificationContent = e.BadgeNotification.Content.GetXml();
                    System.Diagnostics.Debug.WriteLine("Badge recieved :: " + notificationContent);
                    BadgeNotification badge = new BadgeNotification(e.BadgeNotification.Content);
                    BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
                    break;
                case PushNotificationType.Tile:
                    notificationContent = e.TileNotification.Content.GetXml();
                    System.Diagnostics.Debug.WriteLine("Tile recieved :: " + notificationContent);
                    TileNotification tileNotification = new TileNotification(e.TileNotification.Content);
                    TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
                    break;
                case PushNotificationType.Toast:
                    notificationContent = e.ToastNotification.Content.GetXml();
                    System.Diagnostics.Debug.WriteLine("Toast recieved :: " + notificationContent);
                    ToastNotification toast = new ToastNotification(e.ToastNotification.Content);
                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                    break;
                case PushNotificationType.Raw:
                    notificationContent = e.RawNotification.Content;
                    System.Diagnostics.Debug.WriteLine("Raw recieved :: " + notificationContent);
                    break;
                default:
                    System.Diagnostics.Debug.WriteLine("Unknown notification type recieved :: " + e.NotificationType);
                    break;
            }
            e.Cancel = true;
        }
    }
7. Sending push notification through AppHQ console.

You can also send push messages to your registered app user directly from AppHQ console. To do this follow the simple steps:

  • Login to AppHQ Management Console.
  • Click on Unified Notification -> Push -> Users.
  • Select your App and user
  • Click on Manage from table and click on send push button as shown in the below image:

PushFromConsole

Type your message, once you are done click on send button as show below. This will trigger a push notification message to your app user

SendPushFromConsole

Once you are done click on send button. This will trigger a push notification message to your app user. You can also send tile notification from AppHQ by sending JSON formatted string e.g

{"tile":{"title":"Message","count":2,"backgroundImage":"<Your_remote_image_path>","backBackgroundImage":"Your_remote_image_path>","backTitle":"title","backContent":"content"}}
8. Sending Message to Channel

App42 Push notification also supports channel subscription model where user can subscribe on channel of his interest to receive the notification. You can send message to channel which will deliver message to all users who are subscribed to that channel. A channel can be created from AppHQ console. To do this follow the simple steps:

  • Login to AppHQ Management Console, Click on Unified Notification
  • Click on Push -> Click on Channels
  • Select your App -> Click on Add channel button

AddChannelFromConsole

Once channel is created you can ask user for subscription on the channel. Below is the code snippet for the same

//
// First Subscribe User to Channel
//
String channelName = "cricket channel";  
String userName = "Nick";  
pushNotificationService.SubscribeToChannel(channel,userName,this);
//
// Now send message on the Channel
//
String channelName = "cricket channel";  
String message = "Mumbai Indians won IPL 6";  
pushNotificationService.SendPushMessageToChannel(channelName,message,this); 
9. Scheduling Message to User

You can also schedule message to your app user on specified time from AppHQ console. To do this follow the simple steps:

  • Login to AppHQ Management Console, Click on Unified Notification
  • Click on Push -> Click on Users
  • Select your App -> select target user and click on manage
  • Click on Send button and type your message in pop up and pass your time to schedule the message.

SchedulePushMessageFromConsole

10. Scheduling message to Channel

Message scheduling on channel can be done in similar way. To do this follow the simple steps:

  • Login to AppHQ Management Console, Click on Unified Notification
  • Click on Push -> Click on Channels
  • Select your App -> select target channel and click on manage
  • Click on Send Push button and type your message in pop up and pass your time to schedule the message.

SchedulePushMessageFromConsole

11. Send Multilingual Push Notification

Once your device is registered for Push Notification you are ready to send multilingual(UTF-8) push message to your app user using following code snippet from any App42 SDK (Android/Java/WP etc)

String userName = "Nick";
String message = "Message which you have to send";
Dictionary<String, String> otherMetaHeaders = new Dictionary<String, String>();
otherMetaHeaders.Add("dataEncoding", "true");
pushNotificationService.SetOtherMetaHeaders(otherMetaHeaders);
pushNotificationService.SendPushMessageToUser(userName,message,new Callback());  
public class Callback : App42Callback  
{  
	 public void OnException(App42Exception exception)  
	  {  
		Console.WriteLine("Exception Message : " + exception);  
	  }  
	  public void OnSuccess(Object response)  
	  {  
		 PushNotification pushNotification = (PushNotification) response;     
		 String jsonResponse = pushNotification.ToString();  
	  }  
}  

For more details of Push Notification Documentation