Microsoft’s Windows App Studio Beta: Connecting a Menu App to Azure Mobile Service

Scope

The purpose of this article is to connect the Menu App from Windows App Studio with Azure Mobile Service, using the .Net back end.

Introduction

Windows App Studio is a service that allows any person without programming skills to create applications for Windows Phone and Windows. In just 4 steps: have an idea, add content, choose the style and use the application. The service provides a set of templates to help the users to create various applications, theses templates are great starting points for specific uses that are more frequently used.

                     window apps studio
                     window apps tamplate

To understand all the steps for creating an app using App Studio see the article Creating Windows Phone and Window 8.1 applications using Microsoft App Studio. This article explains the Conto so Template and the Web Template.

Menu Template

Menu Template is a template provide by App Studio and it is used for the following purpose:

“Do you own a restaurant, or have a favorite place you go every week? Use this template to show your customers or your friends about the delicious meal they'll find there. With easy-to-navigate sections and pictures for starters, main courses and desserts.”

create app menu template

The template provides:

  • A menu for:
    • Starters
      Contains a list of all starters
    • Mains
      Contains a list of all mains
    • Desserts
      Contains a list of all desserts
    • Beverages
      Contains a list of all beverages
  • A list of special offers

When the template is created, the default data uses static resources.

static resources in edit data

If we click in “Edit data”, we will see the following screen:

new template is created

Windows App Studio allows us to export and import data, but each time we need to edit data, we need to publish the new version in the Store unless we select dynamic resources. For help in this process we will create a .Net Backend in Azure Mobile Service that allows us to manage the data that will be consumed by the Menu App.

See the default Menu App, for Windows Phone 8.1 and Windows 8.1 that was generated by:
Step 1: Add default Menu App generated by AppStudio.

Understanding the source code

The source code provided has a solution that contains the following projects:

  • AppStudio.Windows: project for Windows Store App
  • AppStudio.WindowsPhone: project for the Windows Phone App
  • AppStudio.Shared: shared project used for both targets (it allows the reuse of code)
  • AppStudio.Data: project that contains the model and data source

solution Explorer for create app 

In the AppStudio.Data project it is possible to generate the class diagrams to understand the model and the data sources used in the application. This will be useful later.

The model

The model contains all classes that represent the structure of the data used in the application.

create the Azure Mobile Services

Each class has more properties (DefaultTitle, DefaultSummary, DefaultImageUrl and DefaultContent), that uses the properties showed in the class diagram and these properties only help the automation used by App Studio, for this reason it was ignored.

The data sources

The data sources contains all classes that will provide the data that will fill the UI.

class model of data source

Each data source has a LoadDataAsync method that is called by each target to fill the data in the UI.

Code

See the changes made in the default Menu App, here:

Step 2: Add class diagrams and fixes issues related with nomenclature.

Note: It is possible to change any code in the solution, but it is not possible to upload those changes back to Windows App Studio. Any change in AppStudio should be merged with changes made in Visual Studio.

Requirements

To use Azure Mobile Services it's required to have an Azure Account and the Azure SDK should be installed.

Azure Account

Before starting the backend development it's required to create an Azure account in the Azure Website. For new users there is a trial version that can be used, see more about it here.

Azure Account

Azure SDK

Get the Azure SDK and install it, from Downloads.

download Azure SDK

How to create the Azure Mobile Service in Azure Portal

For the details of how to create an Azure Mobile Service in the Azure Portal and how to create the Visual Studio 2013 project, see the article:

How to create the MyMenuApp Azure Mobile Service.

How to create the Azure Mobile Services

In the topic, “Understanding the source code > the model” we saw the model used in the Menu App and it is important for the services.

To recap, the model has theses classes:

class model

Each class represents specific information inside of the app and the service should allow us to store data for each class (this is the insert operation) and of course support for getting all items, get item by id, update an item and delete an item.

Based in these classes, we will create the follow services:
  • MainSchemaController: the service for managing the MainSchemas
  • SpecialOffersSchemaController: the service for managing the SpecialOffersSchemas
  • DessertsSchemaController: the service for managingthe DessertsSchemas
  • StartersSchemaController: the service for managing the StartersSchemas
  • BeveragesSchemaController: the service for managing the BeveragesSchemas

Each service ends with the word “Controller” because this is a pattern from the WebApi, that is the base for Azure Mobile Services and starts with the name of the related object, normally called Dto. Each developer should be aware of this, because these names will be used internally and if it does not match with the kind of pattern it can cause some problems in consuming the services, in serialization, or when client apps request specific queries.

The data objects (Dtos) will be:

  • MainSchema
  • SpecialOffersSchema
  • DessertsSchema
  • StartersSchema
  • BeveragesSchema

Each one will have the same structure as in the client app and they will inherit from EntityData that is the class from Azure Mobile Service that represents the system properties and are useful for offline mode.

To simplify the sample, we will map the dtos to the database.

Other solutions could be, to have the Dtos mapped with the model. This article, Build a service using an existing SQL database with the Mobile Services .NET backend, shows an example that has Dtos and a model, that are mapped to each other and the model is related with the database.
 
Dtos

The first class created is a base class for the Dtos that contain shared properties.

The Dtobase class

Represents a base class for all Dtos and it inherits from EntityData.

  1. public class DtoBase : EntityData  
  2. {  
  3.     public string Title { getset; }   
  4.     public string Subtitle { getset; }   
  5.     public string Image { getset; }   
  6.     public string Description { getset; }  
  7. }  
The BeveragesSchema class
  1. public class BeveragesSchema : DtoBase { }  
The DessertsSchema class
  1. public class DessertsSchema : DtoBase { }  
The MainSchema class
  1. public class MainSchema : DtoBase { }  
The StartersSchema class
  1. public class StartersSchema : DtoBase { }  
The SpecialOffersSchema class

This class inherits from EntityData and not from the DtoBase because it does not share all properties like the others objects.
  1. public class SpecialOffersSchema : EntityData  
  2. {  
  3.      public string Dessert1 { getset; }   
  4.      public string Main1 { getset; }   
  5.      public string Starter1 { getset; }   
  6.      public string Title { getset; }   
  7.      public string Subtitle { getset; }  
  8. }  
Class Diagram

Here are the class diagrams:

SpecialOffersSchema class digram

Note: All Dtos must be created inside the DataObject folder because when we create the table controller this object will be searched for there.

Services

Each service will be an Azure Mobile Service Table Controller.

window Azure services

Each service should be defined as in the following:

add controller

The BeveragesSchemaController

Which the output will be something like:
  1. public class BeveragesSchemaController : TableController<BeveragesSchema>  
  2. {  
  3.     protected override void Initialize(HttpControllerContext controllerContext)  
  4.     {  
  5.         base.Initialize(controllerContext);  
  6.         MobileServiceContext context = new MobileServiceContext();  
  7.         DomainManager = new EntityDomainManager<BeveragesSchema>(context, Request, Services);  
  8.     }  
  9.   
  10.     // GET tables/BeveragesSchema1  
  11.     public IQueryable<BeveragesSchema> GetAllBeveragesSchema()  
  12.     {  
  13.         return Query();  
  14.     }  
  15.   
  16.     // GET tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959  
  17.     public SingleResult<BeveragesSchema> GetBeveragesSchema(string id)  
  18.     {  
  19.         return Lookup(id);  
  20.     }  
  21.   
  22.     // PATCH tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959  
  23.     public Task<BeveragesSchema> PatchBeveragesSchema(string id, Delta<BeveragesSchema> patch)  
  24.     {  
  25.         return UpdateAsync(id, patch);  
  26.     }  
  27.   
  28.     // POST tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959  
  29.     public async Task<IHttpActionResult> PostBeveragesSchema(BeveragesSchema item)  
  30.     {  
  31.         BeveragesSchema current = await InsertAsync(item);  
  32.         return CreatedAtRoute("Tables"new { id = current.Id }, current);  
  33.     }  
  34.   
  35.     // DELETE tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959  
  36.     public Task DeleteBeveragesSchema(string id)  
  37.     {  
  38.         return DeleteAsync(id);  
  39.     }  
  40.   
  41. }  
For the other services, the process is the same, only change the dto selected and the name of the controller.

Note: The service will be inside the Controllers folder.

Class diagram

controller of class diagram

After creating all the services, we will have something.

Validate data

Each service should validate the input data, to ensure that the following operation will not fail because the input is wrong. For example, suppose that the input object wasn´t sent in the right way, for this reason the serialization fails, it can be a request with n null input, that is not correct and it will throw an NullReferenceException in our service. Another case is when a required property is not filled and the service tries to save or edit it and then it throws a DbEntityValidationException.

Here is the code to insert a BeverageSchema that validates the data:
  1. public async Task<IHttpActionResult> PostBeveragesSchema(BeveragesSchema item)  
  2.       {  
  3.           if (item == null)  
  4.           {  
  5.               throw new ArgumentNullException("item");  
  6.           }  
  7.           if (string.IsNullOrEmpty(item.Title)  
  8.               || string.IsNullOrEmpty(item.Subtitle)  
  9.               || string.IsNullOrEmpty(item.Image)  
  10.               || string.IsNullOrEmpty(item.Description))  
  11.           {  
  12.               return BadRequest("There are properties that are not defined.");  
  13.           }  
  14.           var current = await InsertAsync(item);  
  15.           return CreatedAtRoute("Tables"new { id = current.Id }, current);  
  16.       }  
The same validation can be done in the other dtos.

The DomainManager

Each service has an Initialize method where it defines the DomainManager as in the following:

DomainManager =new EntityDomainManager<BeveragesSchema>(context, Request, Services);

This property is an IDomainManager and is used internally for all operations in the database, in this case it will be an EntityDomainManager of Beverages Schema.

The EntityDomainManager<T>

This class is an implementation of IDomainManager that contains the implementation for all operations required for the database, using the MobileServiceContext.

window Azure EntityDomainManager

The MobileServiceContext

This class represents the DbContext for the services that allow us to do the CRUD operations in the database the easy way. This class will be used by the EntityDomainManager.

The MobileServiceContext was changed because when each service was created, it was also automatically added to the following DataSets:
  1. public DbSet<Data.BeveragesSchema> BeveragesSchemas { getset; }   
  2. public DbSet<DataObjects.DessertsSchema> DessertsSchemas { getset; } public DbSet<DataObjects.MainSchema> MainSchemas { getset; }   
  3. public DbSet<DataObjects.SpecialOffersSchema> SpecialOffersSchemas { getset; }  
  4. public DbSet<DataObjects.StartersSchema> StartersSchemas { getset; }  
With this, we are mapping the Dto to the database.

To understand more about this concept that is related to the Entity Framework, see the documentation about it, DbContext Class.

The Database

There are various ways to create the database, it can be created manually in SQL Server Management Studio, in Visual Studio or can be created using Code First.

This article will use Code First. That means we create the model first and then create the database based in the model structure. This process happens when we do a deploy. As said earlier, our model is defined by the Dtos class.

When the project was created, we removed some code that was ignored and with it we deleted the code related with the Database Initializer, that uses the class DropCreateDatabaseIfModelChanges that is an implementation of IDatabaseInitializer that will DELETE, recreate and optionally re-seed the database only if the model has changed since the database was created.

database coding

If the model doesn't change we can use it.

Are we sure that the model will not change in the future?

Maybe this is not the best solution for creating the database. To create the database and prevent future changes in the model (in our case the dtos), we will use Entity Framework Migrations.

Note: There are others of IDatabaseInitializer that can be used, but the problem is the same, the data will be lost if the model changes.

Before we enable migration, we need to get the connection string to connect to the database and need to allow our IP to access the database.

Defining the connection string

The connection string must be defined in Web.config and can be a connection string from a local database, for local usage, or from the database created with the Azure Mobile Service.

The connection string from MyMenuApp_db database can be found in the Portal, by selecting the MyMenuApp Azure Mobile Service and then in Configure as in the following:

connection string for connect database

And then scroll to:

configure

In the project, go to the Web.Config file and paste there the connection string.

connection string in web config page

Note: Later, in the deployment process, this value is overridden with the connection string defined in the Azure Mobile Service.

Defining the allowed IP for the database

For localhost tests it is required to allow our IP to access the database. We need to go to the Portal, select the database MyMenuApp_db and then click in Dashboard as in the following:

my menuapps

Scroll down to find the following menu in the right:

quick glance

And then allow the current IP as in the following:

current ip status

Migration

To have migration support we need to start with Enable-Migration. To do this, open the Tools menu in Visual Studio and then open the Package Manager Console as in the following:

migration

Now, in the Package Manager Console enable migration and add migration as follows:

migration detail

The Migration folder was added to the project and it contains the configurations file and the migration V_0. This migration contains all information to create the database and the tables, it is used to revert the process if necessary.

Seed


In the Configuration file, it is possible to find the Seed method that fills the database with some initial data or when there is any change in the model. It can be useful to update data in the database.

In our case, we will use it to fill the database with the static data from the Menu App.

Each data source in the AppStudio.Data project has the _data field that contains it. Here are the changes made:

seed coding

Now we need to add the DbMigrator to the WebApiConfig.Register method as in the following:

  1. var migrator = new DbMigrator(new Configuration());  
  2. migrator.Update();  
 
Is this that will create the database or will update the database following the current model.

Be aware that the seed method is called each time this code runs!

See more about it in this article How to make data model changes to a .NET backend mobile service.

Running the Services

Now that the services are ready, we can run the services in localhost or in the server. For testing it could useful to use the localhost first.

Localhost


To run the services in localhost, press the key F5. The following page will be shown:

localhost page

Click on “Try it out” to see the documentation page.

API Documentation

This documentation is generated automatically, it allows us to know what is available and the type of requests and responses we can do. We can play a bit with this, by clicking on one option, let's see one case.

Get tables try this

Click on “try it out” and the following window should appear:

try it out in Aurze

This allows us to make a request to get all the special offers from the service. Attention, there are a limit of items we can get, the best practice is to request some items and will request more when they are needed (it is used to create pagination).

Click in the “send” and we will get the following response:

response fot get table

This data is the data defined in the Seed method.

Server

To deploy the services to the server, click on the project and open the context menu, then click on Publish as in the following:

services to the server

Then select Microsoft Azure Mobile Services to associate the project to the MyMenuApp Azure Mobile Service.

MyMenuApp Azure Mobile Service
                               mobile service

Then click on the Publish button and then it is possible to follow the deployment in Web Publish Activity.



Our default browser will open a window with the service.

window with the service

If we click on “try it out”, it requires a key to access the documentation, that key is provided in the Portal, by selecting the MyMenuApp Azure Mobile Service and then the bottom has the option for it.

manage key

By clicking in the Manage Keys we will get:

manage access key

How to see details about errors

When we run the service, we get this window:

see details about errors

That means there is a problem. To understand what happened we can use the Logs from the MyMenuApp to see the errors.

Go to the Portal, then select the MyMenuApp Azure Mobile Service and then click on Logs, as follows:

mymenuApp table

And then we get the list:

my menuapps list

Select the error and click at the bottom on the “details” button and we will see the error:

login entry detail

This error was made by adding an additional property in the model and wasn´t added the migration for update it in the database.

See more about this subject in this article Troubleshoot the Mobile Services .NET Backend.

How to do the remote debugging

When we run the code in localhost we can debug the services, but in some cases it can be useful to debug the code that is running in the server, it is called remote debugging.

In the MyMenuApp Azure Mobile Service seelct Configure and be sure you have this on:

remote debugging

Note: For how to use Visual Studio 2013 Update 2 or later, it is turned on automatically.
In Visual Studio, open the View menu and the click in Server Explorer that will open the window as in the following:

Azure server explorer

Then expand the Mobile Service and select the MyMenuApp service and click "Attach Debugger".

attach debugger

The default browser will open the service and we shouldn´t close it until the debugging is done!

Note: For it to work we should deploy to the server using Debug Mode, in Release Mode it will not work. See more about it in Runtime Debugging.

Set the breakpoint and do the request, then the breakpoint will be hit as in the following:

Break point

Note: The services should be published as in debug mode.

Code

See the code created for AppStudion.Menu.Backend, here:

Step 4: Changes the BackEnd project: add the Dtos, add Services, changes the MobileServiceContext and add support for migrations.

Manage Images

In Azure Mobile Service, it is a best practice to use Azure Blob Storage for saving the images used in the client apps. We only need to save, in the Azure SQL Database (MyMenuuApp_db), the image URL.

This article will not cover this topic. To see how to implement this feature see the following article Upload images to Azure Storage by using Mobile Services. That covers the topic for .Net Back End & Windows Store and .Net Back End & Windows Phone.

How to consume the Azure Mobile Services in Menu App

Now that we have the services running in the server with the default data, it is time to connect the Menu App with the MyMenuApp Azure Mobile services.

There are two ways to add the Azure Mobile Service Client: installing the Nuget Package or using a Connected Service.

Using Managed Nuget Pacakges

Select the AppStudio.Data project and then open the "Manage Nuget Packages..." as in the following:

manage Nuget Packages

Install the Windows Azure Mobile Services Nuget package as in the following:

install windows azure Mobile Services

It is necessary to install this package in each target (Windows 8.1 and Windows Phone 8.1 apps).

Using Connected Service

Click in the target project and with the mouse open the context menu, then click in “Add” and “Connect Service…”.

connected services

Then login in using your Azure account and you will see your Azure Mobile Services as in the following:

service manager

By clicking in the MyMenuApp Azure Mobile Service we will add the Nuget package for Azure Mobile Service as in the following:
  1. <package id="WindowsAzure.MobileServices" version="1.2.2" targetFramework="wpa81" />  
The MobileService<T>

Then create the MobileService<T> class in the DataSource folder in the AppStudio.Data project as in the following:
  1. // <summary>  
  2. /// Defines the Mobile Service wrapper.  
  3. /// </summary>  
  4. /// <typeparam name="T">The type of the DTO.</typeparam>  
  5. public sealed class MobileService<T>  
  6. {  
  7.     private static MobileServiceClient _appStudioBackEnd;  
  8.   
  9.     /// <summary>  
  10.     /// Gets the application studio back end.  
  11.     /// </summary>  
  12.     /// <value>The application studio back end.</value>  
  13.     private static MobileServiceClient AppStudioBackEnd  
  14.     {  
  15.         get  
  16.         {  
  17.             return _appStudioBackEnd ?? (_appStudioBackEnd = new MobileServiceClient("<the service url>""<the application key from Portal>"));  
  18.         }  
  19.     }  
  20.   
  21.     /// <summary>  
  22.     /// Initializes a new instance of the <see cref="MobileService{T}"/> class.  
  23.     /// </summary>  
  24.     public MobileService()  
  25.     {  
  26.         Table = AppStudioBackEnd.GetTable<T>();  
  27.     }  
  28.   
  29.     /// <summary>  
  30.     /// Gets or sets the table.  
  31.     /// </summary>  
  32.     /// <value>  
  33.     /// The table.  
  34.     /// </value>  
  35.     public IMobileServiceTable<T> Table { getset; }  
  36. }  
Then for each data source do something like:
  1. public async override Task<IEnumerable<SpecialOffersSchema>> LoadDataAsync()  
  2.         {              
  3.                 var mobileService = new MobileService<SpecialOffersSchema>();  
  4.                 return await mobileService.Table.ToListAsync();  
  5.               
  6.         }  
After this, run the Menu App.

app menu

Now the app has dynamic data that can be changed without changing the Menu App.

Code

See the code here:

Step 5: Changes the client app: add support for consuming MyMenuApp Azure Mobile Service.


Similar Articles