leveraging azure notifications hubs

36
Push Notification Leveraging Azure Notification Hubs

Upload: christopher-miller

Post on 08-Jan-2017

174 views

Category:

Software


4 download

TRANSCRIPT

PowerPoint Presentation

Push NotificationsLeveraging Azure Notification Hubs

Vanity SlideChris is a Senior R&D Engineer for Tyler Technologies Currently working on mobile apps for the K-12 transportation market. He leads the Tech Valley .NET User Group in Albany, NY.

Overview of the registration process

Overview of the registration process

Overview of the registration process

Overview of the registration process

You can do this in two waysThe app can register with your service and with the hub separatelyThe app can register with your service and the service can register the user/device with the hub6

Overview of the notification process

Overview of the notification process

Overview of the notification process

Overview of the notification process

Apple and MicrosoftThe same workflow is used for iOS and Windows. The syntax varies slightly, but the same steps are used.

The push mechanism for Windows will depend on which platform you are targetting WNS for Wp 8.1 Silverlight or MPSN11

App registrationApp registers with Google Cloud Messaging (GCM) and received a Registration ID or token.App registers with Apple Push Notification Service (APNS) and receives a registration idApp registers with Microsoft Push Notification Service (MPNS) and receives a notification URI.They pretty much work the same way, we dont really care about the details.

App registrationApp registers the Registration ID with our Azure Notification Hub with the following data

Platform IDToken used by platform notification services to target the deviceTemplateThe message template with placeholder fieldsTagsComma separated list of string values

This step can also be done in the your service13

Sample Tag DefinitionsTypeFormatNotesPlatformAPNSBroadcast to just iOS devicesUserGUIDSpecific to the userTopicGUIDUser could subscribe to a topic like Yankees BaseballMyAppStringBroadcast to all

Additional tags can be added. Azure ORs them. We send a push request using a single tag.

14

Tag expressionsTag expressions can be used to target a set of registrations by using a Boolean expression on the tags.Tag expressions can contain all Boolean operators, such as AND (&&), OR (||), and NOT (!). They can also contain parentheses. Tag expressions are limited to 20 tags if they contain only ORs; otherwise they are limited to 6 tags.Sample: 16B24B4C45065AA5FE0167EA9C9E5C8619D8 && iosThis would send to all iOS devices registered to the school using that GUID

Dealing with expired registrationsAzure Notification Hub assigns each registration with a 90 day time to live (TTL) limit. After the TTL has expired, that registration will no longer work. This is designed to filter out device registrations that are no longer valid. The user may have disabled notifications, uninstalled the app, or no longer owns the device.We need to track the same TTL date and not send any push requests for expired registrations. You handle this with your back end code.Every time a user logs into the app, we renew the registration.

Resinstalling the app will generate a new device id on iOS16

Receiving the MessageiOS and Windows provide incoming toast message support at the OS level.Android apps requires a service to receive and process messages

For iOS and Windows, the OS handles bulk of the work.17

How it works in AndroidXamarin has a free component for iOS and Android called Azure Messaging.Azure Messaging can be installed from within Xamarin Studio or Visual Studio using Xamarins Component Store.Has methods for registering with APNS, GCM, and Azure.For Windows Store apps, just use the default API.

How it works in AndroidAzure Messaging component provides GcmBroadcastReceiverBase This BroadCastReceiver is registered with the OS to receive GCM messages and to be woken up briefly if the app is not running.Parses the GCM messageDisplays notificationsTo be woken up, the app must be compiled for release.

There is a descendant of the Android BroadCastReceiver class that comes from the Azure Messaging component. BroadCastReceiver is the base class for apps and services to receive broadcast messages. The class provided with this component is designed to receive

This BroadCastReceiver is registered with the OS to receive GCM messages and to be woken up briefly if the app is not running.If the app is in the foreground, it can display a Toast message and invokes an Android service that is part of app. That service requests a notification message from the OS.If the app was woken up by the OS, it just calls the service for the notification.To be woken up, the app must be compiled for release.

19

GCM Message formatGCM requires a specific JSON formatted format. A subset of that format is sent to the Notification Hub, it packages the rest.{"data":{"message":"Notification Hub test notification"}}Your code processes that packet. The common practice is to have a message field.Do not create the JSON string as inline text. Create classes and use JSON.Net to convert to JSON. This ensure that the text is properly encoded.

Azure Notification HubOne is all we need for Android and WindowsApple, in its infinite wisdom, requires one certificate to debug/test and another for release to the store.Each hub can store one Apple certificate. For iOS debugging, we use the sandbox hub. For builds sent to Testflight, the production certificate must be used.

How to send a push notificationSee http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-android-get-started/You install a nuget package and add a reference to Microsoft.ServiceBus.Notifications and then all you need is

How to send a push notificationor

Apple Push Notification Service (APNS)Apple requires two certificates, a sandbox cert for testing, and a production certificate for general release.Sandbox certs only work on up to 10 devicesPush Notifications only work on actual devices, not in the simulatoriOS devices use cellular data networks over Wi-Fi for push notifications when possibleSeparate Notification Hubs are required for sandbox and production

APNS CertificatesLogin in to the Developer PortalCreate App IDGenerate a Certificate Signing Request for development and for releaseAssign both CSRs to App ID and create certificatesSave the certs

Launch the Keychain Access appSelect Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate AuthorityEnter the information required and check the 'Saved to disk' option. Click ContinueSave the certificate request using the suggested name and click Save. Click Done in the next screen:Repeat for the production CSR

Generate a CSR

APNS Configuring the App IDEdit the App IdCreate the Dev and Production SSL CertsDownload the certs and load into KeychainExport P12 files with a passwordInstall P12 file into Azure Notification Hub

Refresh the profiles in Xcode and then restart Xamarin27

APNS256 byte limit for the entire message packetNo receipt confirmationEach app requires its own SSL certificateNot setting badge count as the app may not be running

APNSDevice tokens are based on device, app, and distribution certifcateTokens generated for one certificate (i.e. development) will not work with apps generated with a different certificate (i.e. App Store)

APNSWhen you request a UDID from Apple, a value is generated that is specific to your device and AppUninstall and reinstall the app and you will get a different UDIDIf you want a permanent UDID, create a GUID and store in the Keychain

APNS Picking the right HubUse the DEBUG compiler constant to select the sandbox hub, otherwise use the production hub.

This also applies to your backend service. It needs to use the appropriate hub as well.publicpartialclassAppDelegate:FormsApplicationDelegate,ILoginManager { privatestringSerial; privatestringLoginId; /* *APNSusesasandboxcertificatefordebuggingandaproductioncertificateforAppStoreandAdHocrelease *Eachnotificationhubcanusethepublickeyforeitherthesandboxortheproductioncert.WeusetheDEBUG *compiletimecontanttospecifywhichhubtouse */

#ifDEBUG conststringHUB_NAME="mystopsandbox"; conststringHUB_LISTEN_SECRET="LgOtX//jlMw/zNWmkAHZssZm/XddWUo+IamZi1v1RS4="; #else conststringHUB_NAME="mystopnotificationhub"; conststringHUB_LISTEN_SECRET="656Ns/udsz86M0+Cbc2pWTuhllB/KXcO0gaq1d7DxdM="; #endif

TemplatesBy registering the devices with templates, we can send to all platforms with a single call from the back end. Each device registers their native template with placeholder fields for the values to use. The back end service just needs to send the parameter values.This makes it easy to do localized notifications down the road.Templates are named, but are selected based on the parameters used.

APNS TemplateWe define a APNS template named alert with $(message) and $(title) parametersThe expire value is the number of days that the template is good for.Listtags=newList{Serial,"ios","tyler",AppSettings.LoginGuid};varn=newNSSet(tags.ToArray());

varalerts="{\"aps\":{\"alert\":\"$(message)\",\"title\":\"$(title)\"}}";

varexpire=DateTime.Now.AddDays(90).ToString(CultureInfo.CreateSpecificCulture("en-US"));

hub.RegisterTemplateAsync(deviceToken,"alerts",alerts,expire,n,err=> { if(err!=null) Console.WriteLine("Error:"+err.Description); else Console.WriteLine("Success");});

GCM TemplateFollows the same pattern as the APNS templatevaralerts="{\"data\":{\"message\":\"$(message)\",\"title\":\"$(title)\"}}";

hub.RegisterTemplate(registrationId,"alerts",alerts,tags.ToArray());

GCM ProvisioningGet App ID from https://console.developers.google.com/. You will need the Project NumberCreate Public key to use with the Azure HubEnable GCM

Tools Service Bus ExplorerMicrosofts Paolo Salvatori has written an open source tool called Service Bus Explorer. The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. The tool provides advanced features like import/export functionality or the ability to test messaging entities and relay services.

https://code.msdn.microsoft.com/windowsapps/Service-Bus-Explorer-f2abca5a