Reader small image

You're reading from  Learning Microsoft Azure

Product typeBook
Published inOct 2014
PublisherPackt
ISBN-139781782173373
Edition1st Edition
Tools
Right arrow
Authors (2):
Geoff Webber Cross
Geoff Webber Cross
author image
Geoff Webber Cross

Geoff Webber-Cross has over 10 years' experience in the software industry, working in manufacturing, electronics, and other engineering disciplines. He has experience of building enterprise and smaller .NET systems on Azure and other platforms. He also has commercial and personal experience of developing Windows 8 and Windows Phone applications. He has authored Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8, Packt Publishing.
Read more about Geoff Webber Cross

Geoff Webber-Cross
Geoff Webber-Cross
author image
Geoff Webber-Cross

Geoff Webber-Cross has over 16 years' software development experience, working in a variety of sectors on Windows, web, and mobile applications. He has worked on XAML/MVVM applications since the days of Silverlight and Windows Phone 7 and has been building Xamarin apps commercially for a number of years. Geoff is also the author of two books for Packt: Learning Microsoft Azure and Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8.
Read more about Geoff Webber-Cross

View More author details
Right arrow

Chapter 11. Integrating a Mobile Application Using Mobile Services

In this chapter, we're going to build a Windows Phone application and an Azure mobile service for the sales business unit that will allow customers to view orders they've placed and receive notifications when the order status changes and when new products are added to the system. In the supply business unit, we'll create a Windows Store application and Azure mobile service for the warehouse staff to use on a tablet device in order to view which orders are waiting for dispatch while they are working without having to return to a central terminal. We'll be implementing the notification hub (from the Service Bus family of services) into the sales system so that when the order status changes and new products are created, customers will receive toast and tile push notifications to alert them.

Once we've finished, the sales system will have an architecture like this:

I also add another Order Processor Cloud service to the supply...

Introducing Azure mobile services


Azure mobile services is a great platform for mobile developers to quickly create backend services for their applications to store data and create custom APIs to interact with their own data or external resources via HTTP. Along with data and custom APIs, there is great support for push notifications, and there are push notification service APIs for all the major platforms. Mobile services also have fine-grained authorization control that allows different authorization levels to be applied to individual service methods and more recently, support for custom authorization providers.

Mobile services have benefits over other service types such as Web API, WCF, and services on other platforms because of the flexible authorization model, notifications' integration, and also excellent SDKs for taking care of authorization with built-in OAuth workflow and table and API-specific data access methods.

Azure mobile services can be used by pretty much any mobile platform...

Creating the customer Azure mobile service


We need to create a mobile service that matches customers to the existing customers in the sales system, allowing them to see their orders and receive notifications when an order status changes and receive news about things such as new product launches.

To retrieve the data, we can use a Windows Azure mobile services custom controller, which is pretty much the same as the Web API controllers we've already used, or remap the data from our own data schema to be consumed by data services, which implement an ITableData interface, which enforces a number of default table requirements using a tool such as AutoMapper (https://github.com/AutoMapper/AutoMapper). In our application, we don't have a large amount of interaction with the database; we're only retrieving orders, and so I've taken the approach of using a custom controller rather than mapping the schema to ITableData, which, in this case, is an unnecessary overhead. If we were creating a new database...

Exploring the mobile service sample project


The mobile service project has a similar structure to our MVC projects and more so the Web API project because it's built on the same technology. We have an App_Start folder with a WebApiConfig class, which takes care of initializing and configuring the application, and a Controllers folder with a TodoItemController sample class, which is a special type of API controller that is strongly bound to the EntityData type models, which have a number of default fields enforced by the ITableData interface:

public interface ITableData
{
    [JsonProperty(PropertyName = "__createdAt")]
    DateTimeOffset? CreatedAt { get; set; }
    [JsonProperty(PropertyName = "__deleted")]
    bool Deleted { get; set; }
    string Id { get; set; }
    [JsonProperty(PropertyName = "__updatedAt")]
    DateTimeOffset? UpdatedAt { get; set; }
    [JsonProperty(PropertyName = "__version")]
    [SuppressMessage("Microsoft.Performance", 
    byte[] Version { get; set; }
}

The project...

Creating a Windows Phone application


We'll now start building our Windows Phone application, which will be very basic in terms of UI but will demonstrate how to set up a push notifications channel, register with the notifications hub, and make authenticated requests to the mobile service. We'll create and set up the application in the following procedure:

  1. Right-click on the solution and go to Add | New project:

  2. Select Blank App (Windows Phone Silverlight) from the Store Apps tab and click on OK. In the next dialog, I've chosen Windows Phone 8.0 as the target OS version because we're not implementing any 8.1-specific features. Click on OK again to create the project.

  3. Install the Windows Azure Mobile Service NuGet package by entering the following command into the NuGet Package Manager Console:

    Install-Package WindowsAzure.MobileServices
    
  4. Install the WindowsAzure.Messaging.Managed NuGet package, which allows us to interact with the notifications hub by entering the following command into the NuGet...

Updating the order processor


We can update the order processor worker role to call the Notification/PostOrderUpdate action when an order status changes. We'll do this in the following short procedure:

  1. Install the mobile service NuGet package with the following command in the NuGet Package Manager Console:

    Install-Package WindowsAzure.MobileServices
    
  2. Add a mobileServiceUrl string setting to the role's settings with the URL of our local service for local and the publish service for the cloud.

  3. Add a mobileServiceKey string setting to the role's settings with the master key of our local service for local and the published service for the cloud.

  4. Add a MobileServiceClient variable, which is instantiated in the constructor with cloud configurations settings like this:

    private readonly MobileServiceClient _mobileService;
    
    public OrderProcessor()
    {
        var mobileServiceUrl = CloudConfigurationManager.GetSetting("mobileServiceUrl");
        var mobileServiceKey = CloudConfigurationManager.GetSetting("mobileServiceKey...

Updating the admin website


As with the order processor, we can do a small modification to the admin website to call the Notification/PostProductNews action when a new product is created, which will send push notifications to all customers. The procedure for this is pretty much the same, but here, I created a separate helper class to separate the logic from the controller:

private readonly MobileServiceClient _mobileService;

public Notifications()
{
    var mobileServiceUrl = ConfigurationManager.AppSettings["mobileServiceUrl"];
    var mobileServiceKey = ConfigurationManager.AppSettings["mobileServiceKey"];

    this._mobileService = new MobileServiceClient(mobileServiceUrl, mobileServiceKey);
}

public async Task NotifyPostProductNews(int productId)
{
    dynamic data = new ExpandoObject();
    data.productId = productId;

    await this._mobileService.InvokeApiAsync<object, dynamic>("Notification/PostProductNews", data);
}

This method can be called by the ProductController.Create...

Creating the supply mobile service


We've not touched the supply business domain yet, so we're going to create a mobile service and a Windows Store application that allows warehouse staff to view orders, which are ready to dispatch, print labels, and mark orders as Dispatched on their tablet devices.

Note

I've created a full set of supporting samples for the supply business domain, most of which aren't documented as we've not got space in the book, and we've mostly covered its material already; however, there are some interesting bits in the supply order processor, which writes orders to an order table in table storage and automatically generates barcode labels in the JPEG format and writes them to blob storage, so have a look at that!

We'll create the service and install the required NuGet packages in the following procedure:

  1. Right-click on the solution and go to Add | New project and select the Windows Azure Mobile Service template from the Cloud template section.

  2. Install the WindowsAzure.ServiceBus...

Creating the supply Windows Store application


We're going to add a Windows Store app to interact with the mobile service. I've selected the Split App (Windows) option, which has a group item page and a details page to get us started. We'll do this in the following procedure:

  1. Right-click on the solution and go to Add | New project and choose a Windows app template from the Store Apps templates:

  2. Install the WindowsAzure.MobileServices NuGet package by entering the following command in the NuGet Package Manager Console:

    Install-package WindowsAzure.MobileServices
    
  3. Install the MVVM Light NuGet package with the following command:

    Install-package MvvmLight
    
  4. Install the Microsoft.IdentityModel.Clients.ActiveDirectory NuGet package that is needed for Azure AD authentication:

    Install-package Microsoft.IdentityModel.Clients.ActiveDirectory
    
  5. Install the WindowsAzure.Storage NuGet package so that we can interact with TableEntity entities from the service:

    Install-package WindowsAzure.Storage
    
  6. Enable Enterprise...

Summary


We've had a really intense look at mobile services in this chapter; it's quite a big subject in its own right, so it's worth doing some more reading yourself, and definitely check out the Node.js backend to compare what it offers to the .NET backend we've looked at in this chapter.

As I've mentioned, there is a lot of code for the supply business domain that has been omitted from the book due to repetition of the topics we've covered and space in this book, but you should definitely have a look, particularly at the order processor worker role, as this has the other half of the table and blob storage for OrderEntity and barcode JPEG data.

We have completed the application code now, and we'll be finishing this book in the next chapter by looking at how to prepare our systems to go live.

Questions


  1. What benefits do Azure mobile services offer over other type of offer services?

  2. What is special about the administrative authorization level?

  3. Why might a TableController cause us problems with an existing database schema and what options do we have to help us?

  4. What base class should scheduled jobs implement and how are they called?

  5. How can we relate an OAuth provider authenticated user from a mobile service to a user created by an MVC website?

  6. What does the Enable unauthenticated push notifications under the windows phone notifications settings (mpns) setting in the mobile service's PUSH tab do?

  7. Which object contains the user credentials after a successful login from a MobileServiceClient instance?

  8. In the DataServiceBase class, why is the MobileServiceClient variable marked static?

  9. In a Windows Phone app, which capability needs enabling and where is it configured?

  10. When we call the NotificationHub.RegisterNativeAsync method, what does the tagExpression parameter do?

  11. Which NuGet package do...

Answers


  1. Flexible authentication model, push notifications and notifications hub integration, and client SDKs for all major mobile platforms.

  2. This is the highest level of authorization, which overrides all other levels and requires the mobile service master key, which should not be used in client applications.

  3. TableControllers are typed against the ITableData interface, which requires a number of default fields, which an existing table may not have. We can either map the existing entities to a new entity using something like AutoMapper, or use an API controller.

  4. ScheduledJob; this can be called with an HTTP POST request and configured to run on a schedule in the portal.

  5. Add models for the AspNetUser and AspNetUserLogin users to the DbContext with matching DbSet properties, and use these to relate the login provider ID and key from the user credentials to the values in the tables.

  6. This allows requests without an authentication certificate to make push notifications limited to 500 per day.

  7. The...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Microsoft Azure
Published in: Oct 2014Publisher: PacktISBN-13: 9781782173373
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (2)

author image
Geoff Webber Cross

Geoff Webber-Cross has over 10 years' experience in the software industry, working in manufacturing, electronics, and other engineering disciplines. He has experience of building enterprise and smaller .NET systems on Azure and other platforms. He also has commercial and personal experience of developing Windows 8 and Windows Phone applications. He has authored Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8, Packt Publishing.
Read more about Geoff Webber Cross

author image
Geoff Webber-Cross

Geoff Webber-Cross has over 16 years' software development experience, working in a variety of sectors on Windows, web, and mobile applications. He has worked on XAML/MVVM applications since the days of Silverlight and Windows Phone 7 and has been building Xamarin apps commercially for a number of years. Geoff is also the author of two books for Packt: Learning Microsoft Azure and Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8.
Read more about Geoff Webber-Cross