Carma UWP Integration Guide

Carma UWP Integration Guide.

Rev pA2.

 

Contents

About this document. 3

Change notes: 3

How Windows Notification Services (WNS) Works. 4

Integration. 5

Before you begin coding. 5

The app code. 5

Carma UI 5

UWP App. 6

Registering your app and receiving the credentials for your cloud service. 6

Configuring your UWP Application. 7

Write the Code. 7

Carma credentials. 7

Carma SDK. 8

Registration. 8

Receive Push. 10

Send transactional trigger. 13

Retrieving information about a contact. 13

Carma Account. 14

Setup App in Carma: 14

Compost Content. 14

Testing and troubleshooting. 15

Sending UWP Notifications with Carma. 16

Toast Templates. 16

Tile Templates. 16

Badge Template. 17

Raw Template. 17

 

 

 

About this document

This document describes how to integrate Carma with Universal Windows  Platform push notifications.

Change notes:

pA1                        first version

pA2      changed the URL and payload layout for device registration and example code.   Added   method for sending push

 

 

How Windows Notification Services (WNS) Works

The following diagram shows the complete data flow for sending a push notification. It involves these steps:

  1. Your app requests a push notification channel from the Universal Windows Platform.
  2. Windows asks WNS to create a notification channel. This channel is returned to the calling device in the form of a Uniform Resource Identifier (URI).
  3. The notification channel URI is returned by Windows to your app.
  4. Your app sends the URI to Carma. Carma will store the URI so that you can access the URI when you send notifications. The URI is an interface between your own app and Carma;
  5. When Carma has an update to send, it notifies WNS using the channel URI. This is done by issuing an HTTP POST request, including the notification payload, over Secure Sockets Layer (SSL). This step requires authentication.
  6. WNS receives the request and routes the notification to the appropriate device.

 

An overview of windows push notification can be found  here: http://developer.telerik.com/featured/windows-notifications-demystified/

 

 

Integration

The steps for integration are as follows:

Before you begin coding

  1. Make sure the app is registered with Microsoft Store and is given an SID and secret key.
  2. Make sure the app is registered in carma using the SID and the secret key.

The app code

  1. The app requests a URI from WNS
  2. The App sends this URI to carma along with the SID.
  3. The URI’s stored in carma and associated with the app

Carma UI

  1. A new Campaign is created as a push
  2. The campaign is connected to the registered App.
  3. The campaign is sent to WNS who will forward it to the registered devices.

 

 

UWP App

Before you begin, you will need to have an UWP app that you want to send push notifications to.

This push notifications tutorial assumes that Visual Studio 2015 is used as the IDE, with a target device Windows 10.

Registering your app and receiving the credentials for your cloud service

Before you can send notifications using WNS, your app must be registered with the Store Dashboard. This will provide you with credentials for your app that your cloud service will use in authenticating with WNS. These credentials consist of a Package Security Identifier (SID) and a secret key. Each app has its own set of credentials for its cloud service. These credentials cannot be used to send notifications to any other app.

To perform this registration, go to the Windows Dev Center and select Dashboard.

Create a new app and give it a unique name such as com.something.push.

You can also create this information from within visual studio by choosing

Project->Store->Associate App With Store…

To retrieve your SID and secret Key, visit the Live Services site. This requires logging in with the Microsoft account that opened your Dev Center account.

Scroll down to Application secret and store this value as Secret Key, it looks something like this:

blTLazxKrbR56234Ekz1Q47XLl+WDbN

Scroll down to Package SID and copy this value to SID. It will look like this:

ms-app://s-1-15-2-3559591886-3145364946-4169436704-2144837230-885026494-1372889922-3594474832

Finish the registration according to Microsoft’s guidelines. That process is not in the scope of this guide. For more details on how to register your app, please see How to authenticate with the Windows Notification Service (WNS).

 

 

 

Configuring your UWP Application

Open you applications .appmanifest file.

In the Capabilities tab, check the following boxes: Internet(Client), Internet (Client and Server), Private Networks ( Client and Server)

In the Declaration tab, add Background Task and check Push Notification and Timer under Properties

Write the Code

Carma credentials

In order to interact with Carma you need four pieces if information.

  1. serverUrl (The URL of the server where your account is, i.e. http://www5.carmamail.com/)
  2. customerId
  3. Username
  4. Password
  5. listId ( if you plan to populate an existing list instead of using the default list for the app)

You can request this information from your account manager or by sending an email to support@compost.se

 

 

Carma SDK.

There are a couple of convenience classes that you can download to start implementing Carma UWP push.

The Classes are:

  • Carma/Dtos/DeviceDto.cs Data Transfer Object for device data
  • Carma/Dtos/DeviceInfoDto.cs Data Transfer Object for deviceinfo data
  • Carma/Dtos/SendTriggerDto.cs Data Transfer Object for sending transactionals
  • Carma/AppData.cs This is where you enter the account specific data
  • Carma/RestClient.cs Methods for communication with Carma

You can download the classes here: https://drive.google.com/file/d/0B5FRn4gbIr5LLVVuY2NuUmZiOTg/view?usp=sharing

or send an email to support@compost.se  and they will supply you with them.

Registration

We can now begin coding.  The first thing we need to do is register with WNS to get a URI and provide that to our server.  This URI uniquely identifies an UWP device, and our server will use it to send messages to that specific device.  The code to get a channel is straightforward:

String channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

This token needs to be registered in Carma along with the SID and an originalid of you choosing. The originalid is an identifier or the user in your system. It could be an email address or a primary key of the user in your database. If you do not have an originalid for the current user in your app, it needs to be generated by your app.

NOTE! You can NOT use the channel as the originalId as this WILL change overtime.

You register by issuing a PUT request to:

https://<serverUrl>/rest/<customerid>/apps//pushdevices

serverUrl and customerId are supplied by Compost. AppId is the same as the SID you got from WNS

with a json payload containing at the minimum:

  • deviceToken
  • originalId

NOTE! Even if they are the same both values must be provided.

In this payload you can also add other information about the user that should be transferred to Carma. Below is the full list of available properties.

{

“listId”: 0,

“country”: “”,

“originalId”: “”,

“firstName”: “”,

“lastName”: “”,

“middleName”: “”,

“emailAddress”: “”,

“title”: “”,

“dateOfBirth”: “”,

“city”: “”,

“zipcode”: “”,

“sex”: “”,

“mobileNumber”: “”,

“optOutDate”: “”,

“dateOfInvalidation”: “”,

“optOutMobileDate”: “”,

“properties”: “Map[string,string]”,

“namedProperties”: “Map[string,string]”,

“deviceInfo”: [{

“devicetoken”:””,

“Manufacturer”: “”,

“osVersion”: “”,

“model”, “”

“country”: “”

}]

}

The resource uses Basic Auth for authentication and need you to set the Content-Type and Accept headers to “application/json”

The following convenience code that is defined in the RestClient.cs class can be used for the registration:

RestClient client = new RestClient();

String emailAddress = “an.address@gmail.com”;

String originalId = “abc123”;

 

//

// DeviceDto contains essential data that can be updated for a contact in carma.

//

var device = new DeviceDto() { emailAddress = emailAddress , originalId = originalId};

 

await client.UpdateUser(device);

 

If you want to add more information to a user you can just add them as properties.

 

RestClient client = new RestClient();

String food = “meat”;

String drink = “water”;

String firstName = “Lars”;

String emailAddress = ” an.address@gmail.com”;

String originalId = “abc123”;

 

//

// customer specific data is added using name value pairs.

//

Dictionary<string, string> listData = new Dictionary<string, string>{

{“drink”, drink},

{“food”, food}

};

//

// DeviceDto contains essential data that can be updated for a contact in carma.

//

var device = new DeviceDto() { properties = listData, firstName = firstName, emailAddress = emailAddress , originalId = originalId};

 

await client.UpdateUser(device);

 

Receive Push

The content of a windows notification depends on the notification type.

There are four types of notifications that can be sent;

Badge, Tile, Toast and Raw. The definition of the different Notifications types are outside the scope of this document.

The Toast type is the most common type of notification that is most like a push on iOS or Android.

Microsoft have a number of predefined Toast that all have a strict syntax they adhere to.

Below is an example of the payload of a Toast notification

<?xml version=”1.0″ standalone=”yes”?><toast launch=”http://www5.carmamail.com/mail/OBS?muid=67wp0002020DH0Pq0BwI1631593124″ duration=”long”><visual><binding template=”ToastText02″><text id=”1″>Text Line 1.</text><text id=”2″>Text Line 2.</text></binding></visual></toast>

A compost push toast message contains the following fields:

  • launch – contains a link that can be used in order to retrieve the rich content version of the push.
  • Binding – the Microsoft defined name of this Notification Type.

 

It’s important to remember that it’s up to the application developer to decide how these fields should be used.

Our UWP client is now registered with WNS, and our server can begin sending messages to devices running our client using the provided SID,secret key  and device channel URI.  Messages for our UWP application will be received by the App.xml.cs class.

If the app receives a push while inactive, the push will be a part of the Launch Arguments and can be retrieved with the following code in the OnLaunch method:

You should add a listener in the OnLaunched method

protected async override void OnLaunched(LaunchActivatedEventArgs e)

{

 

// CARMA SPECIFIC CODE *START*

//

 

string launchArgs = e.Arguments;

System.Diagnostics.Debug.WriteLine(string.Format(“App Launched params:{0}”, launchArgs));

if (launchArgs.Length > 0)

{

// Application was started from a notification.

// Use the notification content to read data from Carma.

RestClient client = new RestClient();

String notificationContent = launchArgs;

String dataFromServer = await                        client.ReadDataFromServer(notificationContent);

 

}

 

//

// CARMA SPECIFIC CODE *END*

//

try

{

//

// CARMA SPECIFIC CODE

//

RestClient client = new RestClient();

// update channel info in Carma

await client.Init();

client.PushNotificationReceived += OnPushNotification;

 

await client.UpdateUser(null);

 

}

catch (Exception ex)

{

System.Diagnostics.Debug.WriteLine(“ERROR, “, ex);

}

 

}

}

 

The method for consuming the push can be based on the following function:

 

private async void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)

{

RestClient restClient = new RestClient();

String notificationContent = String.Empty;

switch (e.NotificationType)

{

 

case PushNotificationType.Toast:

notificationContent = e.ToastNotification.Content.GetXml();

XmlDocument doc = new XmlDocument();

doc.LoadXml(notificationContent);

String url = doc.DocumentElement.GetAttribute(“launch”);

 

//If the data from carma is a standard html page, use this method. //This is normally the case

string myStyledHTML = await restClient.GetCustomData(url);

 

//If the data from carma is custom JSON that you have created, use //this method.

 

JsonObject jsonData = await restClient.getCustomJsonData(url);

 

//TODO insert what should happen with the received data.

//

break;

 

case PushNotificationType.Badge:

notificationContent = e.BadgeNotification.Content.GetXml();

break;

 

case PushNotificationType.Tile:

notificationContent = e.TileNotification.Content.GetXml();

break;

case PushNotificationType.Raw:

notificationContent = e.RawNotification.Content;

restClient.SendLocalNotification(notificationContent);

break;

}

}

 

 

Send transactional trigger

Instead of using the campaign functionality, you may also send push messages using Carma’s trigger functionality.

This is done by issuing a PUT request to:

/{appid}/pushdevices/{id}/triggers/{triggerid}/messages

 

https:///rest/<customerid>/apps//pushdevices//triggers//messages

with a json payload containing at the minimum:

  • originalId,

{

“originalId”:”abcabc123123″

}

 

 

NOTE! Even if the originalId and devicetoken are the same, both values must be provided.

This will send push notifications to all devices connected to the originalId.

If you are storing you contacts on a list other than the apps default list you must also add its id to the payload, i.e.

{

“originalId”:”abcabc123123″

“listId”:12345

}

If you want to send the push just to one specific devise you can add the token for the device to the payload.

{

“deviceInfo”:[{“devicetoken”: “abc123abc123kmlkmlkml_2”}],

“originalId”:”abcabc123123″

“listId”:12345

}

 

If you can retrieve all tokens for a device by using the method stated below.

Retrieving information about a contact

If you want to retrieve the information connected to a contact you can issue a GET request to

https:///rest/<customerid>/lists//contacts/

You will receive the same struct as when you register a device.  It will contain a list of all devices registered on the originalId. If you have imported information by other means i.e, via scheduledimport on the list, this data will also retrieved.

 

 

Carma Account

To send a push you will need an account in Carma, where you will have received the following information:

  • Username
  • Password
  • Server URL

Setup App in Carma:

Click on Account Setting in the left hand menu and then choose Push Apps under Manage

Click Create new and you will see the following dialog where you enter the information

To register your app in carma you will need the name SID of your app and the Client Secret that you got from Microsoft. The App Id will be the same as the SID.

Click Create and you are ready to start sending Push requests to you users.

The Rich content of the Campaign will be available to the push by calling the URL that is received in the url field in the notification.

Compost Content

The content of a push message is not sent in the push itself, but is located at server side where the url in message is pointing. Content is usually a page of html that is generated for the particular device, user by a template of the server side. It could however be JSON or other text-based formats as defined by template.

The most common way to handle content is to simply create a WebView and pointing it to the url, making it display the page. The developer could however choose to handle it in different ways. Examples would be opening the device browser instead by an intent, downloading the content and parsing it to extract information that is used in the application somehow or passing it to another application.

Testing and troubleshooting

Once you have done integration, perform the following tests.

  • Install the application on a new device
  • Notice that the number of recipients increases for each time you do this. If not, check that the id’s you supply are correct. Check also that the appid you gave when registering the application is the same as the package given in the top of your manifest.
  • If the list does grow, test a simple push while the application is running. If a notification does not show up after a few minutes, make sure that you have given the correct api-key when registering the app in Carma.
  • Once the above works correct, verify that the notifications show up when sending a push even though the application is not running.

 

 

 

 

Sending UWP Notifications with Carma.

Microsoft defines a number of predefined layouts for notifications.

When sending a push you can must decide which type you want to send and then add the correct JSON.

Toast Templates

Carma implements the following Toast templates:

·       ToastText01·       ToastText02·       ToastText03·       ToastText04·       ToastImageAndText01·       ToastImageAndText02·       ToastImageAndText03·       ToastImageAndText04

 

For information on the layouts, please see https://msdn.microsoft.com/sv-se/library/windows/apps/windows.ui.notifications.toasttemplatetype

If you are sending a Toast that has an image, this image is not sent in the push but needs to be a part of the receiving application.

Typically, you will point to an image in the Assets Library of your app.

 

Toasts can be displayed for either a short duration (7 seconds), which is the default, or a long duration (30 seconds). This is set by the optional duration field in the toast object.

For a Toast the JSON look like this:

 

{“type”:”TOAST”,

“toastNotification”:”ToastText02″,

“launch”:””,

“duration”:”long”,

“data”:[

{“type”:”TEXT”,”content”:”New message for you.”,”alt”:””},

{“type”:”TEXT”,”content”:”Hello, check this.”,”alt”:””}]

}

 

Tile Templates

At the moment Carma implements the following tile templates:

·       TileSquareBlock·       TileSquareImage·       TileSquarePeekImageAndText04·       TileWideText09·       TileWideImage·       TileWideImageAndText01·       TileWidePeekImageAndText01

 

For information on the layouts, please see https://msdn.microsoft.com/sv-se/library/windows/apps/windows.ui.notifications.tiletemplatetype

If you are sending a Toast that has an image, this image is not sent in the push but needs to be a part of the receiving application.

Typically, you will point to an image in the Assets Library of your app.

 

For a Tile the JSON look like this:

 

{“type”:”TILE”,

“tileNotification”:”TileSquareBlock”,

“data”:[

{“type”:”TEXT”,”content”:”Text 1″,”alt”:””},

{“type”:”TEXT”,”content”:”Text 2″,”alt”:””}]

}

 

Badge Template

There is only one type of Badge template and it takes an integer as parameter that decides what number should be shown with the badge.

For a Badge  the JSON look like this:

 

{“type”:”BADGE”,

“badgeNotification”:”Badge”,

“data”:[

{“type”:”TEXT”,”content”:”1″,”alt”:””}

}

 

Raw Template

A raw template can be used to send arbitrary data in a notification. It is up to the windows application to use the data as it sees fit.

For a Raw the JSON look like this:

 

{“type”:”RAW”,

“rawNotification”:”Raw”,

“data”:[

{“type”:”TEXT”,”content”:”some raw data”,”alt”:””}]

}