Azure App Service Mobile Apps

The following is from Azure Developer Training lab for AZ-203

About mobile apps in App Service

Azure App Service is a fully managed platform as a service (PaaS) offering for professional developers. The service brings a rich set of capabilities to web, mobile, and integration scenarios.

The Mobile Apps feature of Azure App Service gives enterprise developers and system integrators a mobile-application development platform that’s highly scalable and globally available.

Why Mobile Apps?

With the Mobile Apps feature, you can:

  • Build native and cross-platform apps: Whether you’re building native iOS, Android, and Windows apps or cross-platform Xamarin or Cordova (PhoneGap) apps, you can take advantage of App Service by   SDKs.
  • Connect to your enterprise systems: With the Mobile Apps feature, you can add corporate sign-in in minutes, and connect to your enterprise on-premises or cloud resources.
  • Build offline-ready apps with data sync: Make your mobile workforce more productive by building apps that work offline, and use Mobile Apps to sync data in the background when connectivity is present with any of your enterprise data sources or software as a service (SaaS) APIs.
  • Push notifications to millions in seconds: Engage your customers with instant push notifications on any device, personalized to their needs, and sent when the time is right.

Mobile Apps Features

The following features are important to cloud-enabled mobile development:

  • Authentication and authorization: Support for identity providers, including Azure Active Directory for enterprise authentication, plus social providers such as Facebook, Google, Twitter, and Microsoft accounts. Mobile Apps offers an OAuth 2.0 service for each provider.You can also integrate the SDK for the identity provider for provider-specific functionality.
  • Data access: Mobile Apps provides a mobile-friendly OData v3 datasource that’s linked to Azure SQL Database or an on-premises SQLserver. Because this service can be based on Entity Framework, you can easily integrate with other NoSQL and SQL data providers, includingAzure Table storage, MongoDB, Azure Cosmos DB, and SaaS API providers such as Office 365 and Salesforce.com.
  • Offline sync: The client SDKs make it easy to build robust and responsive mobile applications that operate with an offline dataset. You can sync this dataset automatically with the back-end data, including conflict-resolution support.
  • Push notifications: The client SDKs integrate seamlessly with the registration capabilities of Azure Notification Hubs, so you can send push notifications to millions of users simultaneously.
  • Client SDKs: There is a complete set of client SDKs that cover native development (iOS, Android, and Windows), cross-platform development (Xamarin.iOS and Xamarin.Android, Xamarin.Forms), and hybrid application development (Apache Cordova). Each client SDK is available with an MIT license and is open-source.

Using the Mobile App backend service in an app

This tutorial shows you how to add a cloud-based backend service to aUniversal Windows Platform (UWP) app by using an Azure mobile app backend. You will create both a new mobile app backend and a simple Todolist app that stores app data in Azure. The steps for creating a mobile app for any platform follow a similar pattern:

  1. Create a new Azure mobile app backend
  2. Configure the server project and connect to a database
  3. Deploy and run the app

Prerequisites

The following step-by-step instructions show you how to use the Mobile Apps Quickstart feature to create a mobile app backend for the Windows platform.If you want to try this on your own, you will need the following:

  • An active Azure account. If you don’t have an account, you can sign up for an Azure trial and get up to 10 free mobile apps that you can keep using even after your trial ends. For details, see Azure Free Trial.
  • Visual Studio Community 2015 or a later version.
Create a new Azure mobile backend
  1. Sign in to the Azure portal.
  2. Click Create a resource.
  3. In the search box, type Mobile Apps.
  4. In the results list, select Mobile Apps Quickstart, and then select Create.
  5. Choose a unique App name. This will also be part of the domain name for your App Service.
  6. Under Resource Group, select an existing resource group or create anew one (using the same name as your app).
  7. Click Create. Wait a few minutes for the service to be deployed successfully before proceeding. Watch the Notifications (bell) icon in the portal header for status updates.

Configure the server project

  1. Click the App Services button, select your Mobile Apps back end, select Quickstart, and then select your client platform (iOS, Android, Xamarin,Cordova, Windows (C#)).
  2. If a database connection is not configured, create one by doing thefollowing:a. Create a new SQL database and server.b. Wait until the data connection is successfully created.
  3. Under 2. Create a table API, select Node.js for Backend language.
  4. Accept the acknowledgment, and then select Create TodoItem table. This action creates a new to-do item table in your database.Note: Switching an existing back end to Node.js overwrites all contents. To create a .NET back end instead, see Work with the .NET back-end server SDK forMobile Apps.

 

Download and run the client project

Once you have configured your Mobile App backend, you can either create anew client app or modify an existing app to connect to Azure. In this section, you download a UWP app template project that is customized to connect to your Mobile App backend.

  1. Back in the Quick start blade for your Mobile App backend, click Create a new app > Download, then extract the compressed project files to your local computer.
  2. (Optional) Add the UWP app project to the same solution as the server project. This makes it easier to debug and test both the app and the backend in the same Visual Studio solution, if you choose to do so. To add a UWP app project to the solution, you must be using Visual Studio2015 or a later version.
  3. With the UWP app as the startup project, press the F5 key to deploy and run the app.
  4. In the app, type meaningful text, such as Complete the tutorial, in theInsert a TodoItem text box, and then click Save.

 

 

Enable Push Notifications

Overview of push notifications

Push notifications are delivered through platform-specific infrastructure scalled Platform Notification Systems (PNSes). They offer barebone push functionalities to deliver a message to a device with a provided handle, and have no common interface. To send a notification to all customers across the iOS, Android, and Windows versions of an app, the developer must work withApple Push Notification Service(APNS), Firebase Cloud Messaging(FCM),and Windows Notification Service(WNS).

At a high level, here is how push works:

  1. The client app decides it wants to receive notification. Hence, it contacts the corresponding PNS to retrieve its unique and temporary push handle. The handle type depends on the system (for example, WNS hasURIs while APNS has tokens).
  2. The client app stores this handle in the app back-end or provider.
  3. To send a push notification, the app back-end contacts the PNS using the handle to target a specific client app.
  4. The PNS forwards the notification to the device specified by the handle.

 

Adding push notifications to our sample project

This section of the course shows you how to enable push notifiations in your app. This builds on the instructions in the previous section covering how to create the mobile backend. The steps for enabling push notifications follow a similar pattern for whichever platform you are targeting.

  1. Configure a Notification Hub
  2. Register your app for push notifications
  3. Configure the back end to send push notifications
  4. Update the server to send push notifications
  5. Add push notifications to your app

If you do not use the downloaded quick start server project, you will need thepush notification extension package. See Work with the .NET backend serverSDK for Azure Mobile Apps for more information.

 

Configure a Notification Hub

The Mobile Apps feature of Azure App Service uses Azure Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.

  1. In the Azure portal, go to App Services, and then select your app backend. Under Settings, select Push.
  2. To add a notification hub resource to the app, select Connect. You caneither create a hub or connect to an existing one.

Now you have connected a notification hub to your Mobile Apps back-end project. Later you configure this notification hub to connect to a platform notification system (PNS) to push to devices.

 

Register your app for push notifications

You need to submit your app to the Microsoft Store, then configure your server project to integrate with Windows Notification Services (WNS) to  .

  1. In Visual Studio Solution Explorer, right-click the UWP app project, click Store > Associate App with the Store….
  2. In the wizard, click Next, sign in with your Microsoft account, type a name for your app in Reserve a new app name, then click Reserve.
  3. After the app registration is successfully created, select the new app name, click Next, and then click Associate. This adds the requiredMicrosoft Store registration information to the application manifest.
  4. Navigate to the Windows Dev Center, sign-in with your Microsoft account, click the new app registration in My apps, then expand Services> Push notifications.
  5. In the Push notifications page, click Live Services site under MicrosoftAzure Mobile Services.
  6. In the registration page, make a note of the value under Applicationsecrets and the Package SID, which you will next use to configure yourmobile app backend.

 

Important: The client secret and package SID are important security credentials. Do not share these values with anyone or distribute them with your app. The Application Id is used with the secret to configure MicrosoftAccount authentication.

 

Configure the backend to send push notifications

  1. In the Azure portal, select Browse All > App Services. Then select yourMobile Apps back end. Under Settings, select App Service Push. Then select your notification hub name.
  2. Go to Windows (WNS). Then enter the Security key (client secret) andPackage SID that you obtained from the Live Services site. Next, selectSave.

Your back end is now configured to use WNS to send push notifications.

 

Update the server to send push notifications

Use the procedure below that matches your backend project type—either .NET backend or Node.js backend.

.NET backend project

  1. In Visual Studio, right-click the server project and click Manage NuGetPackages, search for Microsoft.Azure.NotificationHubs, then clickInstall. This installs the Notification Hubs client library.
  2. Expand Controllers, open TodoItemController.cs, and add the following using statements:
    using System.Collections.Generic; using Microsoft.Azure.NotificationHubs; using Microsoft.Azure.Mobile.Server.Config;
  3. In the PostTodoItem method, add the following code after the call toInsertAsync:
    // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create the notification hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Define a WNS payload var windowsToastPayload = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" + item.Text + @"</text></binding></visual></toast>"; try { // Send the push notification. var result = await hub.SendWindowsNativeNotificationAsync(windowsToastPayload); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); }

    This code tells the notification hub to send a push notification after anew item is insertion.

  4. Republish the server project.

 

Node.js backend project

  1. If you haven’t already done so, download the quickstart project or elseuse the online editor in the Azure portal.
  2. Replace the existing code in the todoitem.js file with the following:
    var azureMobileApps = require('azure-mobile-apps'), promises = require('azure-mobile-apps/src/utilities/promises'), logger = require('azure-mobile-apps/src/logger'); var table = azureMobileApps.table(); table.insert(function (context) { // For more information about the Notification Hubs JavaScript SDK, // see http://aka.ms/nodejshubs logger.info('Running TodoItem.insert'); // Define the WNS payload that contains the new item Text. var payload = "<toast><visual><binding template=\ToastText01\><text id=\"1\">" + context.item.text + "</text></binding></visual></toast>"; // Execute the insert. The insert returns the results as a Promise, // Do the push as a post-execute action within the promise flow. return context.execute() .then(function (results) { // Only do the push if configured if (context.push) { // Send a WNS native toast notification. context.push.wns.sendToast(null, payload, function (error) { if (error) { logger.error('Error while sending push notification: ', error); } else { logger.info('Push notification sent successfully!'); } }); } // Don't forget to return the results from the context.execute() return results; }) .catch(function (error) { logger.error('Error while running context.execute: ', error); }); }); module.exports = table;

    This sends a WNS toast notification that contains the item.text when anew todo item is inserted.

  3. When editing the file on your local computer, republish the serverproject.

Add push notifications to your app

Next, your app must register for push notifications on start-up. When you have already enabled authentication, make sure that the user signs-in before trying to register for push notifications.

  1. Open the App.xaml.cs project file and add the following using statements:
    using System.Threading.Tasks; using Windows.Networking.PushNotifications;
  2. In the same file, add the following InitNotificationsAsync method definition to the App class:
    private async Task InitNotificationsAsync() { // Get a channel URI from WNS. var channel = await PushNotificationChannelManager .CreatePushNotificationChannelForApplicationAsync(); // Register the channel URI with Notification Hubs. await App.MobileService.GetPush().RegisterAsync(channel.Uri); }

    This code retrieves the ChannelURI for the app from WNS, and thenregisters that ChannelURI with your App Service Mobile App.

  3. At the top of the OnLaunched event handler in App.xaml.cs, add the async modifier to the method definition and add the following call to the new InitNotificationsAsync method, as in the following example:
    protected async override void OnLaunched(LaunchActivatedEventArgs e) { await InitNotificationsAsync(); // ... }

    This guarantees that the short-lived ChannelURI is registered each time the application is launched.

  4. Rebuild your UWP app project. Your app is now ready to receive toast notifications.

 

Enable Offline Sync

Overview of offline sync

Offline sync allows end users to interact with a mobile app – viewing, adding, or modifying data – even when there is no network connection. Changes a restored in a local database. Once the device is back online, these changes are synced with the remote backend.

What is a sync context?

A sync context is associated with a mobile client object (such asIMobileServiceClient or MSClient) and tracks changes that are made with sync tables. The sync context maintains an operation queue, which keeps an ordered list of CUD operations (Create, Update, Delete) that is later sent to the server.

A local store is associated with the sync context using an initialize method such asIMobileServicesSyncContext.InitializeAsync(local store)in the .NET client SDK.

 

How offline synchronization works

When using sync tables, your client code controls when local changes are synchronized with an Azure Mobile App backend. Nothing is sent to the backend until there is a call to push local changes. Similarly, the local store is populated with new data only when there is a call to pull data.

  • Push: Push is an operation on the sync context and sends all CUD changes since the last push. Note that it is not possible to send only an  individual table’s changes, because otherwise operations could be sent out of order. Push executes a series of REST calls to your Azure MobileApp backend, which in turn modifies your server database.
  • Pull: Pull is performed on a per-table basis and can be customized with a query to retrieve only a subset of the server data. The Azure Mobile client SDKs then insert the resulting data into the local store.
  • Implicit Pushes: If a pull is executed against a table that has pending local updates, the pull first executes a push() on the sync context. This push helps minimize conflicts between changes that are already queued and new data from the server.
  • Incremental Sync: the first parameter to the pull operation is a queryname that is used only on the client. If you use a non-null query name, the Azure Mobile SDK performs an incremental sync. Each time a pull operation returns a set of results, the latest updatedAt timestamp from that result set is stored in the SDK local system tables. Subsequent pull operations retrieve only records after that timestamp.To use incremental sync, your server must return meaningful updatedAtvalues and must also support sorting by this field. However, since theSDK adds its own sort on the updatedAt field, you cannot use a pull query that has its own orderBy clause.The query name can be any string you choose, but it must be unique for each logical query in your app. Otherwise, different pull operations could overwrite the same incremental sync timestamp and your queries can return incorrect results. If the query has a parameter, one way to create a unique queryname is to incorporate the parameter value. For instance, if you are filtering on userid, your query name could be as follows (in C#):

    await todoTable.PullAsync(“todoItems” + userid, syncTable.Where(u => u.UserId == userid));

    If you want to opt out of incremental sync, pass null as the query ID. Inthis case, all records are retrieved on every call to PullAsync, which is potentially inefficient.

  • Purging: You can clear the contents of the local store usingIMobileServiceSyncTable.PurgeAsync. Purging may be necessary if you have stale data in the client database, or if you wish to discard all pending changes.A purge clears a table from the local store.If there are operations awaiting synchronization with the server database, the purge throws an exception unless the force purge parameter is set.As an example of stale data on the client, suppose in the“todo list” example, Device1 only pulls items that are not completed. A todo item “Buy milk” is marked completed on the server by another device. However, Device1 still has the “Buy milk” todo item in local store because it is only pulling items that are not marked complete. A purge clears this stale item.

Next

The rest of this lesson shows you how to add offline support to a UniversalWindows Platform (UWP) app using an Azure Mobile App backend. The   enabling offline sync follow a similar pattern for whichever platform youare targeting.

  1. Ensure the client app supports offline features
  2. Ensure the app can disconnect from the backend
  3. Ensure the app can reconnect to your Mobile App backend
Requirements

The next part of this course builds on a UWP app project. If you want   along in your own project be sure to have:

Updating the client app to support offline features

Azure Mobile App offline features allow you to interact with a local database when you are in an offline scenario. To use these features in your app, you initialize a SyncContext to a local store. Then reference your table through the IMobileServiceSyncTable interface. SQLite is used as the local store on the device.

  1. Install the SQLite runtime for the Universal Windows Platform.
  2. In Visual Studio, open the NuGet package manager for the UWP app project that you completed in the Create a Windows app tutorial.   and install the Microsoft.Azure.Mobile.Client.SQLiteStore NuGet package.
  3. In Solution Explorer, right-click References > Add Reference… >Universal Windows > Extensions, then enable both SQLite forUniversal Windows Platform and Visual C++ 2015 Runtime forUniversal Windows Platform apps.
  4. Open the MainPage.xaml.cs file and uncomment the #defineOFFLINE_SYNC_ENABLED definition.
  5. In Visual Studio, press the F5 key to rebuild and run the client app.   works the same as it did before you enabled offline sync. However, the local database is now populated with data that can be used in an offline scenario.

Update the app to disconnect from the backend

In this section, you break the connection to your Mobile App backend to simulate an offline situation. When you add data items, your exception handler tells you that the app is in offline mode. In this state, new items added in the local store and will be synced to the mobile app backend when push   run in a connected state.

  1. Edit App.xaml.cs in the shared project. Comment out the initialization   MobileServiceClient and add the following line, which uses an invalid mobile app URL:

    public static MobileServiceClient MobileService = new MobileServiceClient(“https://your-service.azurewebsites.fail”);

    You can also demonstrate offline behavior by disabling wifi and cellular networks on the device or use airplane mode.

  2. Press F5 to build and run the app. Notice your sync failed on refresh when the app launched.
  3. Enter new items and notice that push fails with aCancelledByNetworkError status each time you click Save. However, the new todo items exist in the local store until they can be pushed to   app backend. In a production app, if you suppress these exceptions the client app behaves as if it’s still connected to the mobile app backend.
  4. Close the app and restart it to verify that the new items you created are persisted to the local store.
  5. (Optional) In Visual Studio, open Server Explorer. Navigate to your database in Azure->SQL Databases. Right-click your database and select Open in SQL Server Object Explorer. Now you can browse to your SQL database table and its contents. Verify that the data in   database has not changed.
  6. (Optional) Use a REST tool such as Fiddler or Postman to query your mobile backend, using a GET query in the form https://<your-mobile-app-backend-name>.azurewebsites.net/tables/TodoItem.

 

Update the app to reconnect to the backend

In this section, you reconnect the app to the mobile app backend. These changes simulate a network reconnection on the app.

When you first run the application, the OnNavigatedTo event handler calls InitLocalStoreAsync. This method in turn calls SyncAsync tosync your local store with the backend database. The app attempts to sync on startup.

  1. Open App.xaml.cs in the shared project, and uncomment your previous initialization of MobileServiceClient to use the correct the mobile app URL.
  2. Press the F5 key to rebuild and run the app. The app syncs your local changes with the Azure Mobile App backend using push and pull operations when the OnNavigatedTo event handler executes.
  3. (Optional) View the updated data using either SQL Server ObjectExplorer or a REST tool like Fiddler. Notice the data has been synchronized between the Azure Mobile App backend database and the local store.
  4. In the app, click the check box beside a few items to complete them in the local store.

UpdateCheckedTodoItem calls SyncAsync to sync each completed item with the Mobile App backend. SyncAsync calls both push and pull.However, whenever you execute a pull against a table that the client has made changes to, a push is always executed automatically. This behavior ensures all tables in the local store along with relationships remain consistent. This behavior may result in an unexpected push.

 

API summary

To support the offline features of mobile services, we used theIMobileServiceSyncTable interface and initializedMobileServiceClient.SyncContext with a local SQLite database.When offline, the normal CRUD operations for Mobile Apps work as if the app is still connected while the operations occur against the local store. The following methods are used to synchronize the local store with the server:

  • PushAsync: Because this method is a member ofIMobileServicesSyncContext, changes across all tables are pushed to the backend. Only records with local changes are sent to the server.
  • PullAsync: A pull is started from a IMobileServiceSyncTable.When there are tracked changes in the table, an implicit push is run to make sure that all tables in the local store along with relationships remain consistent. The pushOtherTables parameter controls whether other tables in the context are pushed in an implicit push. The query parameter takes an IMobileServiceTableQuery or OData querystring to filter the returned data. The queryId parameter is used to define incremental sync.
  • PurgeAsync: Your app should periodically call this method to purge stale data from the local store. Use the force parameter when you need to purge any changes that have not yet been synced.

 

Refereneces