Вы находитесь на странице: 1из 152

Microsofts Windows AppStudio

by
Sara Silva

Azure Mobile Services | BackOffice App | Push Notification | Cortana


Menu App
Microsofts Windows AppStudio

Table of Contents

About the Author ......................................................................................................................... 5


About the Contributors ................................................................................................................ 6
About this eBook ......................................................................................................................... 8
Introduction ................................................................................................................................ 9
Chapter 1: Windows AppStudio Overview .................................................................................. 10
Contoso Ltd Template ....................................................................................................................... 11
Content ......................................................................................................................................... 12
Theme ........................................................................................................................................... 13
Tile ................................................................................................................................................. 14
Publish ........................................................................................................................................... 14
Finish ............................................................................................................................................. 15
Web App Template ........................................................................................................................... 18
Menu Template Overview ................................................................................................................ 19
Understanding the source code .................................................................................................... 20
The model...................................................................................................................................... 21
The data sources ........................................................................................................................... 22
Chapter 2: Connecting to Azure Mobile Service ........................................................................... 23
DTOs .................................................................................................................................................. 25
The DtoBase class.......................................................................................................................... 25
The BeveragesSchema class .......................................................................................................... 25
The DessertsSchema class............................................................................................................. 25
The MainSchema class .................................................................................................................. 25
The StartersSchema class.............................................................................................................. 25
The SpecialOffersSchema class ..................................................................................................... 25
The class diagram for the model................................................................................................... 26
Services ............................................................................................................................................. 27
The BeveragesSchemaController .................................................................................................. 28
Validating data .............................................................................................................................. 29
The DomainManager .................................................................................................................... 30
The EntityDomainManager<T> ..................................................................................................... 30
The MobileServiceContext ............................................................................................................ 30

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


1
Menu App
Microsofts Windows AppStudio

The Database ................................................................................................................................ 31


Migration....................................................................................................................................... 35
Running the Services ......................................................................................................................... 37
Localhost ....................................................................................................................................... 37
Server ............................................................................................................................................ 39
Errors ............................................................................................................................................. 42
Remote debugging ........................................................................................................................ 44
Manage Images ................................................................................................................................. 46
How to consume the Azure Mobile Services in Menu App .............................................................. 46
Using Managed Nuget Pacakges ................................................................................................... 46
Using Connected Service............................................................................................................... 47
The MobileService<T>................................................................................................................... 48
Chapter 3: Creating a BackOffice App ......................................................................................... 50
Creating the BackOffice App using Empty Template ........................................................................ 50
Changing the app's name .............................................................................................................. 51
Creating the menu ........................................................................................................................ 52
Adding collections ......................................................................................................................... 53
Collection using default columns .................................................................................................. 53
Collection using specific columns ................................................................................................. 55
Editing a collection ........................................................................................................................ 57
Editing Layout and Bindings .......................................................................................................... 58
Editing default data ....................................................................................................................... 59
Generating the BackOffice app ......................................................................................................... 60
Changing the source code generated ............................................................................................... 61
Running the app ............................................................................................................................ 62
Add support for edit data ............................................................................................................. 63
Running the App Now that the BackOffice supports editing the data and has a new look, let's
see how it looks. ........................................................................................................................... 75
Chapter 4: Adding support for Push Notification ......................................................................... 78
Send Push Notification ...................................................................................................................... 79
Defining the messages .................................................................................................................. 79
Changing controllers ..................................................................................................................... 81
Receive Push Notification ................................................................................................................. 83
Push Notification Wizard .............................................................................................................. 83
Debugging Push Notifications ........................................................................................................... 87

2 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Using Visual Studio........................................................................................................................ 88


Using the Debug from Notification Hubs in Azure Portal ............................................................. 91
Testing real Push Notification using BackOffice ............................................................................... 92
Insert notification.......................................................................................................................... 92
Update notification ....................................................................................................................... 94
Using Tags ......................................................................................................................................... 96
Using Templates................................................................................................................................ 97
Chapter 5: Integrating with Cortana ........................................................................................... 98
Integrating Cortana ........................................................................................................................... 98
The VCD file ................................................................................................................................... 98
The InstallVoiceCommandsAsync method .................................................................................... 99
The OnActivated method ............................................................................................................ 100
Chapter 6: Publish the Menu App in the Store .......................................................................... 107
Test the app .................................................................................................................................... 107
Take the screenshots ...................................................................................................................... 108
Associate app with the Store and generate packages .................................................................... 109
In Windows AppStudio................................................................................................................ 109
In Visual Studio............................................................................................................................ 113
Running Windows App Certification Kit.......................................................................................... 116
The artwork ..................................................................................................................................... 118
Uploading packages .................................................................................................................... 118
Appendix ................................................................................................................................. 122
Appendix 1: How to Create the Azure Mobile Service in Azure Portal ........................................... 122
Creating the Azure Mobile Service ............................................................................................. 122
How to create the Azure Mobile Service project for Visual Studio 2013 ................................... 127
Nuget Package ............................................................................................................................ 129
Appendix 2: How merge different source code generated by AppStudio ...................................... 130
Creating a demo application ....................................................................................................... 130
Creating a source code repository .............................................................................................. 131
Creating changes ......................................................................................................................... 135
Conclusion ................................................................................................................................... 139
Appendix 3: Class Diagram: An Easy Way to Understand Code ..................................................... 140
Creating a class diagram ............................................................................................................. 141
Expanding classes........................................................................................................................ 143
The Class Details.......................................................................................................................... 143

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


3
Menu App
Microsofts Windows AppStudio

Understanding various icons....................................................................................................... 144


Show Base Class .......................................................................................................................... 145
Hide compartment ...................................................................................................................... 146
Apply Associations ...................................................................................................................... 147
The final class diagram ................................................................................................................ 150

4 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

About the Author

Written by Sara Silva [Microsoft MVP | Telerik Developer Expert |C#


Corner MVP | MCPD]

Sara Silva studied mathematics in University of Coimbra, but since she finished
her degree she is working in software development using Microsoft
technologies, since 2009 is Microsoft Certified Professional Developer.

Nowadays, she is a Windows, Xamarin and Azure Developer in Portugal, with


experience in the development of projects within the operational planning of
public transport, logistics, payments and multimedia.

She was awarded

Microsoft Most Valuable Professional (MVP) (2013 & 2014 in Visual C# and 2015 in .Net)
Telerik Developer Expert 2015
C# Corner Most Valuable Professional (MVP) 2014
Nokia Developer Champion 2013

Other awards

Nokia Developer Wiki Contributor of the Month for March, November 2013 and August 2014

TechNet Wiki Longest Article Award May, September 2014

TechNet Wiki Windows Phone and Windows Store Apps Technical Guru May, June, July,
August, September, October 2014

TechNet Wiki Microsoft Azure Technical Guru July, September, October, December 2014

TechNet Wiki Visual C# Technical Guru August, October, December 2014

TechNet Wiki Miscellaneous Technical Guru August, October 2014

TechNet Wiki WPF Technical Guru October, November, December 2014

Curah! 2014 Award Top 10 featured curators

C# Corner Top 10 Author 2014

You can follow Sara at www.saramgsilva.com and on twitter @saramgsilva.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


5
Menu App
Microsofts Windows AppStudio

About the Contributors

Bryan Tomlinson - Sr. Product Marketing Manager at Microsoft

Bryan Tomlinson is a proud member of the Windows Apps & Store Team focusing
on developer success. Bryan is the product lead for Windows App Studio and has
been with the product from wireframes to now more than 2.5 million users. Bryan
also manages Microsoft employee developer program, which has more than
20,000 members and has spawned great hits like 4th and Mayor, Taptitude, and
Wordament. He also ran 2013's Windows Phone Next App Star campaign, which
awarded one lucky winner (out of 9,167 competing apps) a chance to have their app's live tile featured
on a primetime TV ad!

Jon Levesque Support Lead at Microsoft

A tech nerd and creative who lives in Seattle. He is a SME on Windows App
Studio and also the team support lead. Jon loves App Studio, the Green Bay
Packers and hanging with his kids.

Paulo Morgado Microsoft MVP & MVP Mentor

Paulo Morgado has a bachelor degree in Electronics and


Telecommunications (Digital Systems) by the Instituto Superior de
Engenharia de Lisboa and a degree of licentiate in Informatics Engineering by
the Faculdade de Cincias da Universidade Nova de Lisboa and MCSD for
Microsoft .NET and MCTS for .NET Framework 2.0 Windows Applications and
.NET Framework 2.0 ASP.NET Applications.

Paulo contributes in the Microsoft English and Portuguese forums answering questions about
software development, with special focus on the .NET Framework. He is Microsoft MVP for more than
10 years. Follow him at twitter @paulomorgado.

6 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Alessandro Del Sole Microsoft MVP

Alessandro Del Sole has been Microsoft .NET MVP since 2008. He authored many
books about .NET and Visual Basic, he regularly speaks at Italian and international
conferences, and published many apps for Windows 8 and Windows Phone. He
lives in Italy and he loves Alfa Romeo cars. You can reach him on Twitter at
@progalex

Jos Rui Silva - MSc Student of Micro and Nanotechnologies Engineering

Jos is a young dreamer with aspirations on the Quantum Physics and


nanotechnologies fields. He is MSc Student and currently the CEO of the junior
enterprise of its college (iNOVAfuture) and tries to help other students to make
their ideas real

Yavor Georgiev - Program Manager at Hulu

Yavor was Program Manager working on Windows Azure Mobile Services.


Previously he drove the Silverlight web services stack. You can find him on
Twitter @theYavor and on his blog http://hashtagfail.com.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


7
Menu App
Microsofts Windows AppStudio

About this eBook


This EBook is the result of a challenge, to integrate Azure Mobile Service with Windows
AppStudio Applications from the Windows AppStudio Team, which resulted in a series of articles.
Thus, this EBook will be a compilation of these articles and include few updates from new releases
provided by Windows AppStudio.

To support the eBook is possible to get the source code from the repository, in GitHub,
https://github.com/AppStudioSamples/Menu, and in each chapter is possible to find the reference to
the related source code.

In the chapters is provided notes, tips, references, etc. which will be represented by an icon
to help understand the information type. The following images with respective legend will describe
these icons:

Reference to source code

Reference to external or complementary resource

Reference to appendix

A note or a tip

8 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Introduction
Microsoft released Windows Phone AppStudio Beta in 2013, which is a service that allows any
person without programming skills to create applications, for Windows Phone, in just 4 steps: have an
idea, add content, choose the style and use the application. In April 2014, a new version of this service
was released alongside the beta version of Windows AppStudio, which in addition to the Windows
Phone applications, allows the creation of Windows 8.1 applications (based in Universal Applications).

In this eBook, at the 1st Chapter, we will see the main steps to create a Windows AppStudio
application, using the templates: Contoso Ltd Template, Menu Template and Web template. The
application generated by the Menu Template will be our focus and we will analyse its model and data,
and it will be used in the following chapters.

At the 2nd Chapter, you will learn how to develop a .Net Backend from Azure Mobile Service
and how it can be integrated in the Menu App, using the Azure Mobile Service SDK for client
applications. To support this chapter is provided an appendix (Appendix 1) where you can learn how
to create the Azure Mobile Service in the Azure Portal and to create an Azure Mobile Service project
in Visual Studio.

In Chapter 3, we will see a solution to create a BackOffice application, using Windows


AppStudio, to manage the data from the Backend that is consumed later by the Menu App.

At the 4th Chapter, you will learn how to add support to Push Notification using the Azure
Notification Hubs, which is integrated with Azure Mobile Services. This feature is provided out-of-box
by Azure Mobile Service SDK and you will learn how the SDK for it.

Cortana is one of the main features provided by Windows Phone 8.1, which bring rich
interaction between the user and the application, and we will see how to integrate it with the
application, in the Chapter 5.

Lastly, in the Chapter 6, you will see the main points to submit the Menu Application in the
Store, where will be provided complementary reference to help in the process.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


9
Menu App
Microsofts Windows AppStudio

Chapter 1: Windows AppStudio Overview


Windows AppStudio provides integration with the social network Facebook, Twitter, Flickr and
Instagram, has capability to import data from excel or csv file, etc. and more recently has support to
Touch Develop.

The service can be accessed from appstudio.windows.com.To start with this service, the user is
required to have an Outlook.com account, or in case the user doesn't have an account, any Microsoft
Id will work. For accounts that does not fit with this, the email account can be associated with a
Microsoft Id and for it the user should use the link http://bit.ly/1gywtmO or in the login page, click on
Sign up. The first time we do the login, the website will show a screen to allow the AppStudio to access
our account, which can be changed later if we wish to. After this, we need to accept the terms of use
and we need to define the user for the email account we are using.

After sign in, we only need to click the button Start new project, to start a new project:

Figure 1 Start new project

App Studio provides a set of templates to help the users create applications. Theses templates are
application demos for a specific context that are more often used.

10 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 2 The different templates provided by Windows AppStudio

Noteworthy is that all the templates are C # / XAML applications and are available for both Windows
Phone 8.1 and Windows 8.1. When we select a template of type "Empty App" we are creating an
application from scratch. This template is often used when the other templates do not meet the needs
of the user or for more advanced users who already have some experience with App Studio.

The user will set all kinds of content, styles and will need to use all your creativity to build a "great
app". In the case of the "Web App Template" the user will also create the application from scratch,
but in this case is given a base URL that will be the starting point of the application and have access to
some buttons on "AppBar", this template is ideal for a website that suit mobile devices. On the other
hand, other templates allow a quick guide in the application we are building and we only need to
change the data and customize the application.

Contoso Ltd Template

After we select the template Contonso Ltd, a screen will be shown where we can have a first look at
the app. This is a simple simulation of the app for Windows Phone 8.1 and Windows 8.1, which does
not allow navigation to the details pages. The follow screen give us an idea of the application without
installing it:

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


11
Menu App
Microsofts Windows AppStudio

Figure 3 Creating Contoso Ltd Application

Content

Figure 4 The Content separator

The first separator, the Content, shows the application name and logo (left, at the top) and shows
all definitions for the content of the app, which, in this case, has five sections:

About us is an HTML section

Catalogue is a dynamic collection section

Team is a dynamic collection section

News is a Bing section

Contact us is a menu section that has menu actions

There's a limit of up to six sections. After each section is created we can edit, delete or move the
section position with the goal to define the best order for it.

12 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

For each section we can select one of the following options:

RSS: A list of sets of information based on an RSS feed that you enter when creating the data
source;

HTML: A single page of static text that you enter;

YouTube: A list of videos with titles and descriptions based on a YouTube channel or search
that you enter when creating the data source;

Flickr: A list of images and their corresponding data based on a Flickr UserId or search that
you enter when creating the data source;

Bing: A list of news;

Facebook: A Facebook feed from a public Facebook page;

Instagram: A Instragram feed based in a tag;

Twitter: A twitter feed based in an user or in a hastag;

Menu: Allows creation of a menu action to be used in other apps (for example: using an
address for Here Maps, using a phone number to make a call phone and others)

Collection: A list of items with columns of characteristics. The collection can be static or
dynamic and if the collection is dynamic then the data can be imported or exported for a CSV
file;

TouchDevelop: a "touch-friendly" programming language for writing code directly on a


device;

App Studio already has a comprehensive list of data sources, allowing the user to create compelling
apps. However, these data sources are based on RSS feeds that have a limited number of items and
some presentation limitations.

Theme
In this separator, we can define the
background image or the background
color, define the text color and the
application bar color. There are three
options: custom style (using a
background image), dark style and a
light style. The Select button allows
definition of the style and then we
need to save the configuration.

Figure 5 The Theme separator

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


13
Menu App
Microsofts Windows AppStudio

Tile
In the Tiles, we can define tiles for
the application and we can select
one type from the three available
types: Flip Template, Cycle
Template and Icon Template. In this
case was selected the Cycle
Template and the respective
images.

Figure 6 The Tiles separator

In the Splash & Lock separator, we


define the images for a splash screen
and for the lock screen, for both apps.
This page doesn't specify the size of
the images but when we try to upload
it, it will be shown at the allowed size
if our images dont fit those values.

Figure 7 The splash & lock separator


Publish
In this separator the language for the
app is defined (for now it is only
possible to select one). It is possible to
define the title and the description
and we can define them if the app has
an About page or even ads (but it
requires development in Visual
Studio). Before the finalize step it is
possible to associate the app with the
store, that requires a reserved name
in the tore Dashboard.

Figure 8 The Publish Separator

14 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

After all the configuration we can finalize the app by clicking the Finish button.

Finish

On this screen you can see the


applications for each target
platform (not being able to
navigate) and it is possible to
generate the application to get the
application packages for
installation on each device and
then get the source code.

Figure 9 Finish the application

Clicking on the "Generate" button we get a screen where we can choose which application we want
to generate.

Figure 10 Generating the application

After this step, we can get the application packages that allow testing of the application in our devices,
or we can get the source code and then test the application in the simulator or in a device using Visual
Studio (but that requires a developer account). It is possible to install the application package directly
in the device using the QRCode provided and is possible to share, in social network, the URL for the
application.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


15
Menu App
Microsofts Windows AppStudio

Figure 11 Output

To install the Windows 8.1 application is possible through PowerShell, using Admin privileges, as
following:

Figure 12 Installing the Windows 8.1 Application using PowerShell

Download the source code and opening it in Visual Studio, we will get the following structure:

With the source code, each application can be extended in order to add new features such as:

Add more resource strings (localization)

Add ads configuration

Change the user interface

Connect to Backend

Add support to Push Notifications

Integrate with Cortana

Integrate with analytics provider

Amongst others

16 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 13 Solution with the source code

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


17
Menu App
Microsofts Windows AppStudio

Web App Template

Web App Template are now available for both target, Windows Phone 8.1 and Windows 8.1, and it is
an application based in a website provide by URL.

Figure 14 Creating a Web Application

After create the Web App Template we will see the following page:

Figure 15 Defining the web app

As we can see, the content of this app is only a reference for a URL, which is a website that supports
mobile devices. For example, this template uses the m.microsoft.com URL, but we can change it for
use any another URL, like: booking.com, m.sapo.pt, m.vodafone.pt, amongst other references.

The definition for Theme, Tile, Publish and Finish are the same as we saw in Contoso Ltd template.

18 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Menu Template Overview

Menu Template is a template provide by Windows AppStudio 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.

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

Figure 16 Creating the menu app

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

Figure 17 Menu's data structure

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


19
Menu App
Microsofts Windows AppStudio

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

Figure 18 The static data source

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, which was
generated: Step 1: Add default Menu App generated by AppStudio (bit.ly/MenuApp-Step1)

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

20 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 19 The solution

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.

See the Appendix 3 Class Diagram: An easy way to understand code which will provide
additional information about class diagrams.

The model

The model, defined in AppStudio.Data, contains all classes that represent the structure of the data
used in the application.

Figure 20 The model

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


21
Menu App
Microsofts Windows AppStudio

Each class has more properties (DefaultTitle, DefaultSummary, DefaultImageUrl and DefaultContent).
Which uses the properties showed in the class diagram and them are used in the automation created
by Windows 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

Figure 21 The class diagram

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

See the changes made in the default Menu App: Step 2: Add class diagrams and fixes
issues related with nomenclature (bit.ly/MenuApp-Step2)

It is possible to change 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. See the Appendix 2 Appendix II: How merge different source code generated by
AppStudio which will provide some tips to merge the code source.

22 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Chapter 2: Connecting to Azure Mobile


Service
To use Azure Mobile Services it's required to have an Azure Account and the Azure SDK should be
installed. Before starting the backend development it's required to create an Azure account in
azure.microsoft.com. For new users there is a trial version that can be used, see more about
it http://azure.microsoft.com/en-us/pricing/free-trial/.

Figure 23 Azure Portal and Downloads

Get the Azure SDK and install it, from

azure.microsoft.com/en-us/downloads.
Figure 22 Azure Portal and downloads

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 Appendix 1 Appendix I: How to Create the Azure
Mobile Service in Azure Portal which will provide the step by step to create the MyMenuApp Azure
Mobile Service.

In the last chapter, in Menu Template Overview, was analysed the model that define the structure for
the data used in the Menu App and it is very important for the services. 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.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


23
Menu App
Microsofts Windows AppStudio

Figure 2 The model

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 managing the 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 (asp.net/web-
api). WebApi is the base for Azure Mobile Services and the controller name starts with the name of
the related object, normally called DTO, and end with the word controller. 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 even 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, using Entity Framework.

24 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Other solutions could be, to have the DTOs mapped with the model. The 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 { get; set; }
4. public string Subtitle { get; set; }
5. public string Image { get; set; }
6. public string Description { get; set; }
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 { get; set; }
4. public string Main1 { get; set; }
5. public string Starter1 { get; set; }
6. public string Title { get; set; }
7. public string Subtitle { get; set; }
8. }

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


25
Menu App
Microsofts Windows AppStudio

The class diagram for the model

The class diagram is defined as following:

Figure 3 The class diagram with class form the model

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

26 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Services
Each service will be an Azure Mobile Service Table Controller and can be created as following:

Figure 4 Creating a table controller

Each service should be defined as in the following:

Figure 5 Defining the table controller

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


27
Menu App
Microsofts Windows AppStudio

The BeveragesSchemaController

Which will generate the class

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<BeveragesSch
ema> 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. }

For the other services, the process is the same, only change the DTO selected and the name of the
controller and all services should be create inside the Controllers folder.

28 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

After create the services is possible to create the class diagram for the services class, as following:

Figure 624 Class diagram with service's class

Validating 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 wasnt 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
a 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.

The code to insert a BeverageSchema that validates the data, can be defined as following:

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. }

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


29
Menu App
Microsofts Windows AppStudio

The same validation can be done in the other DTOs.

The DomainManager

Each service has an Initialize method, which defines the DomainManager as following:

1. 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.

Figure 7 The 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 { get; set; }


2. public DbSet<DataObjects.DessertsSchema> DessertsSchemas { get; set; } public DbSet
<DataObjects.MainSchema> MainSchemas { get; set; }
3. public DbSet<DataObjects.SpecialOffersSchema> SpecialOffersSchemas { get; set; }
4. public DbSet<DataObjects.StartersSchema> StartersSchemas { get; set; }

With this, we are mapping the DTO to the database.

30 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

To understand more about it, which is related to the Entity Framework, see the documentation
about it, the 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. We 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 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 lass 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.

Figure 8 WebConfig and the MobileServiceInitializer class

If the model doesn't change we can use it, but Are we sure that the model will not change in the
future?

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


31
Menu App
Microsofts Windows AppStudio

To create the database and prevent future changes in the model (in our case the DTOs), we will
use Entity Framework Migrations.

There are others 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, which can be found in the Azure Portal by selecting the
MyMenuApp Azure Mobile Service and then in Configure as in the following:

Figure 9 Database settings

Scroll to Connection strings to get the value, which by default is hidden:

Figure 1025 The connection strings for the MyMenuApp Azure Mobile Service

32 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

In the project, go to the Web.Config file and paste there the connection string from the Azure Portal,
as following:

Figure 11 The connection string

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

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

Figure 262 Selecting dashboard

Scroll down to find the following menu in the right.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


33
Menu App
Microsofts Windows AppStudio

Figure 27 Manage allowed IP addresses

And then allow the current IP, as following:

Figure 28 Allow to the current IP address

34 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Migration

To add 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 following:

Figure 15 Open the Package Manager Console

Now, in the Package Manager Console, we need to enable migration and add migration, as following:

Figure 29 Enable Migration and add the migration V_0

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.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


35
Menu App
Microsofts Windows AppStudio

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

Figure 30 The configuration class

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

1. var migrator = new DbMigrator(new Configuration());


2. migrator.Update();

This way, the database will be created if it is needed or will be updated based in the current model
and the migration provided.

Be aware that the seed method is called each time this code runs and consequently clone data
can be added to the database. See more about this subject in the article How to make data model
changes to a .NET backend mobile service.

36 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

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:

Figure 18 The mobile service is up and running

Click on Try it out to see the


documentation page, which 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.

Figure 31 API Documentation

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


37
Menu App
Microsofts Windows AppStudio

Selecting one service, we will see a new page with a response as example, in this case as JSON,

Click on try it out


and fill the form

Figure 32 Try it out

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, best practice is to request some items and it will request more when they
are needed (it is used to create pagination). Click in the send and we will get the response.

38 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 21 The response

The data, in body, 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 following in Figure 22 and select the publish target as in Figure 23:

Figure 22 Publishing the service

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


39
Menu App
Microsofts Windows AppStudio

Figure 33 Selecting a publish target

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

Figure 24 Authentication

40 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

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

Figure 25 The Web Publish Activity window

Our default browser will open a 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 Azure Portal, by selecting the
MyMenuApp Azure Mobile Service and then in
the bottom has the option for it.

Figure 26 The service is up and running and require a key to see the API Documentation

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


41
Menu App
Microsofts Windows AppStudio

Figure 34 Manage access keys

Errors

When we run the service and we got the following window, which means there are problems. To
understand what happened we can use the Logs from the MyMenuApp to see the errors.

Figure 28 The service is unhealthy

42 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

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

Figure 35 The logs from the MyMenuApp Azure Mobile Service

Figure 30 The list of logs

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

Figure 36 Log entry details

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


43
Menu App
Microsofts Windows AppStudio

In this case, the error was made by adding an additional property in the model and wasnt added the
migration for update it in the database.

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

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 select Configure and be sure you have this on:

Figure 37 Enable remote debugging

For those who use Visual Studio 2013 Update 2 or later, it is turned on automatically.

44 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

In Visual Studio, open the View menu and the click in Server
Explorer that will open the window as following:

Then expand the Mobile Service and select the MyMenuApp


service and click "Attach Debugger". The default browser will
open the service and we shouldnt close it until the debugging
is done!

Figure 38 Attach Debugger for Remote Debugging

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, this way, the breakpoint will be hit as in the following:

Figure 39 The breakpoint was hit

See the code created for AppStudion.Menu.Backend Step 4: Changes the BackEnd project:

add the Dtos, add Services, changes the MobileServiceContext and add support for migrations.
(bit.ly/MenuApp-Step4).

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


45
Menu App
Microsofts Windows AppStudio

Manage Images

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

To see how to implement this feature see the 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:

Figure 34 Manage Nuget Packages

46 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

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

Figure 35 Installing 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

Select the target project and with the mouse open the context menu, then click in Add and
Connect Service

Figure 36 Add Connected Service

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


47
Menu App
Microsofts Windows AppStudio

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

Figure 37 Select the MyMenuApp Azure Mobile Service

By clicking in the MyMenuApp Azure Mobile Service we will add the Nuget package for Azure Mobile
Service, as following:

1. <package id="WindowsAzure.MobileServices" version="1.2.2" targetFramework="wpa81" /


2. >

The MobileService<T>

After it, create the MobileService<T> class in the DataSource folder from the AppStudio.Data
project, as 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 MobileServiceClien
t("<the service url>", "<the application key from Portal>"));
18. }
19. }
20.

48 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio
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 { get; set; }
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 and the following screen will be showed, for the Windows 8.1
application:

Figure 38 The Windows 8.1 Application

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

See the code in Step 5: Changes the client app: add support for consuming MyMenuApp

Azure Mobile Service. (bit.ly/MenuApp-Step5)

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


49
Menu App
Microsofts Windows AppStudio

Chapter 3: Creating a BackOffice App


The MyMenuApp Azure Mobile Service is defined and the Menu App consumes the data from the
service, now we will create the BackOffice App to change that data. For help in creating the BackOffice
App, we will use the Empty Template from AppStudio to create the starting point of this app, which
will contain:

A Start menu with the following choices: Starters, Mains, Desserts, Beverages and Special
offers
Clicking in each menu item will show a page with list of the items
Clicking in one item in the list will show a page to edit the item

Creating the BackOffice App using Empty Template


Go to the Windows AppStudio, do the login and then click in Start new project.

Figure 140 Start new project

In the next screen, click in the Empty App Template:

Figure 2 Windows AppStudio Templates

Like the name indicates, this app is empty app and we will define all the structure for the BackOffice.

50 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

The following figure will show the start point for a project:

Figure 3 The Content

Changing the app's name

Start by changing the name to BackOffice, in the App Title field at the top, as following:

Figure 41 Changing the name

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


51
Menu App
Microsofts Windows AppStudio

Creating the menu

The first page of the app will have a menu; for that, click in the Menu option and then fill in the
name of the menu.

Figure 5 Creating a menu

Click in the arrow in the menu created, to expand it.

Figure 42 The menu created

With this we will have more options available. To create the menu we want, we will use the
collection option, because we want to show a list of items.

52 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Adding collections

Click in the collection menu to create the first menu item, as following:

Figure 7 Choosing a collection

Collection using default columns

Define the name of the collection and click in the option Add default columns:

Figure 43 Defining the menu's name

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


53
Menu App
Microsofts Windows AppStudio

That will create the following structure:

Figure 44 Data configuration

Here we can define if we want dynamic or static data, that it is not important in our case, because we
will use the data from the Azure Mobile Service, as we did in the Menu App. After creating each
collection, it is recommended to save the definitions, using the button Save in the right.

Figure 45 Saving

Do the same process for Mains, Desserts and Beverages.

54 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Collection using specific columns

For Special Offers we need to add the columns manually, because it has a structure different from
the default, for that click in Create new as following:

Figure 461 Create new

It will create a row as in the following:

Figure 12 Defining data

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


55
Menu App
Microsofts Windows AppStudio

For each field insert the respective information: field's name, type and if it is multiline. At the end we
will have something like:

Figure 47 The data structure

Each field name should start with upper case because this way the respective property will well
defined, i.e., using C# Guidelines.

After all collections are defined, we will have the following definition:

Figure 48 The menu

56 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

These collection can be ordered, deleted and edited but they cannot be more than six. In the code it
is possible to add more or create another menu and add the missed collections. In source code change
it to have only one section.

Editing a collection

It is possible to edit the Starters by clicking in Edit Item, that will show the following screen:

Figure 15 Editing Starters layout

For each collection we need to do the following:

Define the Layout and Bindings for the windows with the list of items
Define the Layout and Bindings and Page Extras for the details of the item
Edit the data to add one dummy starter

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


57
Menu App
Microsofts Windows AppStudio

Editing Layout and Bindings

We can choose what we want, for the sample we will define the following:

Figure 16 Defining the main page layout

And for the detail page, we will define:

Figure 17 Defining tthe detais page layout

58 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Editing default data

We will now edit the default data, by clicking in the Data separator and then in Edit Data, as
following:

Figure 18 Edit data

Click in Create new and fill in the item with dummy values as following:

Figure 19 Insert starters

Here, it is not important what we will fill in, it only allows us to see data until we change the BackOffice
to consume the Azure Mobile Service. Insert a similar dummy data for the others collection.

At this moment, we have a starting point for the BackOffice App, it is possible to define the theme,
the tiles, the published info, but this article will not cover it. To see in more depth how to define each
one, see the topic Theme Chapter 1: Introduction.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


59
Menu App
Microsofts Windows AppStudio

Generating the BackOffice app

Now you can click in the Finish button to generate the BackOffice App, and the following screen
will be shown:

Figure 20 Finish the app

Click in the Generate button to generate the source code.

Figure 21 Generate universal app

60 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Click in the link to download the source code, as following:

Figure 22 Download source code

See the code in Step 6: Add default BackOffice App generated by AppStudio

(bit.ly/MenuApp-Step6)

Changing the source code generated


Now we have a starting point for the BackOffice, we will change the code to support editing the data
consumed by the Azure Mobile Service. To add the MyMenuApp Azure Mobile Service to the
BackOffice App, see the Chapter 2, the changes in BackOffice are the same.

The default columns added to the ImageUrl in each collection and each DTO from the service
uses the name Image. There are two options to fix this difference: rename the property ImageUrl
for each collection and in the UI or using JSON attributes for the property ImageUrl that will define
the name as Image.

In the Azure Mobile Services we added the static data from the Menu App, for this reason when we
run the BackOffice App using the Azure Mobile Service it will not show the images, because the
BackOffice App doesnt have these images. To solve it for now, do a copy and paste of these images
(it will be temporary!).

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


61
Menu App
Microsofts Windows AppStudio

Running the app

Running the app we will get the following screens.

The main view


The main view is the start page when the app launches. In this case, it will be MainPage.xaml.

Figure 49 The backoffices menu

The collection view

The collection view will be the page that shows a list of objects. In this case, it will be
BeveragesPage.xaml, DessertsPage.xaml, Main1Page.xaml, SpecialOffersPage.xaml and
StartersPage.xaml.

Figure 50 The beverages

62 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

The item view

The item view will be the page that shows a specific item, in this case, it will be
BeveragesDetailPage.xaml, DessertsDetailPage.xaml, Main1DetailPage.xaml,
SpecialOffersDetailPage.xaml and StartersDetailPage.xaml.

Figure 25 The beverage 1

The others collection has similar views. For now the BackOffice app is only in read mode similar to
the Menu App.

Add support for edit data

Here are the main changes we need to do:

Change the item view to edit the data


Add an AppBarButton to Add a new item in the collection view
Add two AppBarButton to Save and Delete the current item in the item view

We will only focus on Windows 8.1 App, for the Windows Phone 8.1 the changes are similar and
in some cases the changes are shared.

Changing the UI (XAML)

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


63
Menu App
Microsofts Windows AppStudio

The following describes changing the data templates.

To add the support to edit the data, we need to change the item view. We should change the
following views (that can be found in the DataTemplate folder):

Figure 26 The data templates

Each one contains the DataTemplates used in each page. To find which template should be changed,
open the BeveragesDetailPage.xaml, the page for seeing a selected Beverage. We will find the FlipView
that contains the a ItemTemplate defined, called Beverages1DetailDetail.

Figure 51 Selecting the content template

64 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

With the cursor under the string Beverages1DetailDetail press F12 and the BeveragesViews.xaml
will be opened, with focus in:

1. <DataTemplate x:Key="Beverages1DetailDetail">

Change this template to something like:

1. <DataTemplate x:Key="Beverages1DetailDetail">
2. <StackPanel Margin="120,0,0,0">
3. <TextBlock Text="Title:"
4. Style="{StaticResource ItemHeaderTextSnapped}" />
5. <TextBox Grid.Row="0" Margin="0,20,0,0" Grid.Column="1"
6. Text="{Binding Title, Mode=TwoWay}" Width="400" HorizontalAlig
nment="Left"/>
7. <TextBlock Text="Subtitle:" Margin="0,20,0,0"
8. Style="{StaticResource ItemHeaderTextSnapped}" />
9. <TextBox Grid.Row="0" Grid.Column="1"
10. Text="{Binding Subtitle, Mode=TwoWay}" Margin="0,20,0,0" Widt
h="400" HorizontalAlignment="Left"/>
11. <TextBlock Text="Image:" Margin="0,20,0,0"
12. Style="{StaticResource ItemHeaderTextSnapped}" />
13. <TextBox Grid.Row="0" Grid.Column="1" Margin="0,20,0,0"
14. Text="{Binding Image, Mode=TwoWay}" Width="400" HorizontalAlig
nment="Left"/>
15. <Image Grid.RowSpan="2"
16. Source="{Binding Image}" Margin="0,20,0,0"
17. Width="200" Height="200"
18. HorizontalAlignment="Left" Stretch="UniformToFill" />
19. <TextBlock Text="Description:" Margin="0,20,0,0"
20. Style="{StaticResource ItemHeaderTextSnapped}" />
21. <TextBox Grid.Row="1" Grid.Column="1"
22. Margin="0,20,0,0" ScrollViewer.HorizontalScrollBarVisibility="
Auto"
23. ScrollViewer.VerticalScrollBarVisibility="Auto"
24. AcceptsReturn="true" HorizontalAlignment="Left"
25. Height="200" MaxHeight="200" Width="800" MaxWidth="800"
26. Text="{Binding Description, Mode=TwoWay}" />
27. </StackPanel>
28. </DataTemplate>

It will result in something like:

Figure 52 Editing the Beverage 1

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


65
Menu App
Microsofts Windows AppStudio

Do the same changes for Starters, Mains and Desserts. For Special Offers change the data template
for something like:

1. <DataTemplate x:Key="SpecialOffers1DetailDetail">
2. <StackPanel Margin="120,0,0,0">
3. <TextBlock Text="Title:"
4. Style="{StaticResource ItemHeaderTextSnapped}" />
5. <TextBox Grid.Row="0" Margin="0,20,0,0" Grid.Column="1"
6. Text="{Binding Title, Mode=TwoWay}" Width="400" HorizontalAlig
nment="Left"/>
7.
8. <TextBlock Text="Subtitle:" Margin="0,20,0,0"
9. Style="{StaticResource ItemHeaderTextSnapped}" />
10. <TextBox Grid.Row="0" Grid.Column="1"
11. Text="{Binding Subtitle, Mode=TwoWay}" Margin="0,20,0,0" Widt
h="400" HorizontalAlignment="Left"/>
12.
13.
14. <TextBlock Text="Starter1:" Margin="0,20,0,0"
15. Style="{StaticResource ItemHeaderTextSnapped}" />
16. <TextBox Grid.Row="0" Grid.Column="1"
17. Text="{Binding Starter1, Mode=TwoWay}" Margin="0,20,0,0" Widt
h="400" HorizontalAlignment="Left"/>
18.
19. <TextBlock Text="Main1:" Margin="0,20,0,0"
20. Style="{StaticResource ItemHeaderTextSnapped}" />
21. <TextBox Grid.Row="0" Grid.Column="1"
22. Text="{Binding Main1, Mode=TwoWay}" Margin="0,20,0,0" Width="
400" HorizontalAlignment="Left"/>
23. <TextBlock Text="Dessert1:" Margin="0,20,0,0"
24. Style="{StaticResource ItemHeaderTextSnapped}" />
25. <TextBox Grid.Row="0" Grid.Column="1"
26. Text="{Binding Dessert1, Mode=TwoWay}" Margin="0,20,0,0" Widt
h="400" HorizontalAlignment="Left"/>
27. </StackPanel>
28. </DataTemplate>

The result will be something like:

Figure 29 Editing a Special Offers

At this moment, all the data can be edited. Now we need to add options to persist it.

66 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Adding the AppBarButtons

To allow doing the operations Add, Save and Delete it is necessary to add an AppBarButton for
each operation. In the BeveragesDetailPage.xaml add the following app bar:

1. <Page.BottomAppBar>
2. <CommandBar Background="{StaticResource AppBarBackground}">
3. <AppBarButton DataContext="{Binding BeveragesModel}"
4. x:Uid="SaveButton"
5. Command="{Binding SaveCommand}">
6. <AppBarButton.Icon>
7. <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Save.png"/>
8. </AppBarButton.Icon>
9. </AppBarButton>
10. <AppBarButton DataContext="{Binding BeveragesModel}"
11. x:Uid="DeleteButton"
12. Command="{Binding DeleteCommand}">
13. <AppBarButton.Icon>
14. <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Delete.png"/>
15. </AppBarButton.Icon>
16. </AppBarButton>
17. </CommandBar>
18. </Page.BottomAppBar>

That will add the Save and Delete AppBarButton. This XAML can be added to the others object's
pages. To add the Add AppBarButton, open the BeveragesPage.xaml and added the following
XAML:

1. <Page.BottomAppBar>
2. <CommandBar Background="{StaticResource AppBarBackground}">
3. <AppBarButton x:Uid="AddButton"
4. Command="{Binding AddCommand}"
5. DataContext="{Binding BeveragesModel}">
6. <AppBarButton.Icon>
7. <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Add.png"/>
8. </AppBarButton.Icon>
9. </AppBarButton>
10. <AppBarButton x:Uid="RefreshButton" DataContext="{Binding BeveragesMode
l}" Visibility="{Binding RefreshVisibility}"
11. Command="{Binding RefreshCommand}">
12. <AppBarButton.Icon>
13. <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Refresh.png"/>
14. </AppBarButton.Icon>
15. </AppBarButton>
16. </CommandBar>
17. </Page.BottomAppBar>

Do the same for the others object's pages.

For now it is missing the commands for each AppBarButton: AddCommand, SaveCommand and
DeleteCommand.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


67
Menu App
Microsofts Windows AppStudio

The AppStudio apps uses a pattern called Model-View-ViewModel (MVVM), for this reason
the AppBarButton is using the Command property and not the Click event. To understand more
about this pattern, see the following article Use the Model-View-ViewModel (MVVM) pattern.

Changing the code behind (C#)

Go to the ViewModelBase.cs file in the Shared project.

Figure 30 The ViewModelBase

Scroll to the ViewModelBase<T> class and add the following commands:

1. public ICommand AddCommand


2. {
3. get { return new DelegateCommand(AddItem); }
4. }
5.
6. public ICommand DeleteCommand
7. {
8. get { return new DelegateCommand(DeleteItem); }
9. }
10.
11. public ICommand SaveCommand
12. {
13. get { return new DelegateCommand(SaveItem); }
14. }

68 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

After it, add the missed methods:

1. public abstract bool CanSave();


2.
3. public abstract void AddItemAsync();
4.
5. private async void DeleteItemAsync ()
6. {
7. // todo
8. }
9.
10. private async void SaveItemAsync ()
11. {
12. // todo
13. }

The methods CanSave and AddItemAsync will be implemented in the view model for each object,
more specifically the view models BeveragesViewModel, DessertsViewModel, Main1ViewModel,
SpecialOffersViewModel and StartersViewModel. Because it needs to know each object will be
added.

The DeleteItemAsync and SaveItemAsync can be implemented in the ViewModelBase<T> class


because they can be generic.

The DeleteItemAsync method

For the DeleteItemAsync method, we need to show a message to the user to confirm the operation,
then the item will be deleted and then the item will be removed from the Items list and will raise
notifications to update the UI.

The implementation will be something like:

1. private async void DeleteItemAsync()


2. {
3. ProgressBarVisibility = Visibility.Visible;
4. var currentItem = GetCurrentItem();
5.
6. var messageDialog = new MessageDialog(currentItem.DefaultTitle, "Are you sure
you want to delete this item?");
7. messageDialog.Commands.Add(new UICommand("Yes"));
8. messageDialog.Commands.Add(new UICommand("No"));
9. var result = await messageDialog.ShowAsync();
10. if (result.Label == "Yes")
11. {
12. await DataSource.DeleteAsync(currentItem);
13. Items.Remove(currentItem);
14. OnPropertyChanged("PreviewItems");
15. OnPropertyChanged("Items");
16. OnPropertyChanged("HasMoreItems");
17. }
18.
19. ProgressBarVisibility = Visibility.Collapsed;
20. }

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


69
Menu App
Microsofts Windows AppStudio

This will require changes in the DataSourceBase<T> class as in the following:

Figure 53 The DataSourceBase<T>

Where we will add the abstract methods for DeleteAsync and SaveAsync. These methods will be
implemented in all specific data sources, for example in BeveragesDataSource we will do something
like:

1. public override async Task DeleteAsync(BeveragesSchema currentItem)


2. {
3. await _mobileService.Table.DeleteAsync(currentItem);
4. await UpdateCacheAsync();
5. }

This code applies to the other data sources: DessertsDataSource, MainDataSource,


SpecialOffersDataSource and StartersDataSource.

The SaveItemAsync method

For the SaveItemAsync method, we will update the data and then will show a message to the user to
confirm the operation was done and then the UI will be updated.

1. private async void SaveItem()


2. {
3. if (!CanSave())
4. {
5. var cannotSaveMessageDialog = new MessageDialog("You must fill all data
.", "Attention!");
6. cannotSaveMessageDialog.Commands.Add(new UICommand("Ok"));
7. await cannotSaveMessageDialog.ShowAsync();
8. return;
9. }
10. ProgressBarVisibility = Visibility.Visible;
11. var currentItem = GetCurrentItem();
12. var messageDialog = new MessageDialog(currentItem.DefaultTitle, "The it
em was saved!");

70 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio
13. messageDialog.Commands.Add(new UICommand("Ok"));
14. await DataSource.SaveAsync(currentItem);
15. await messageDialog.ShowAsync();
16. OnPropertyChanged("Items");
17. OnPropertyChanged("PreviewItems");
18. OnPropertyChanged("HasMoreItems");
19. ProgressBarVisibility = Visibility.Collapsed;
20. }

This code applies to the others data sources: DessertsDataSource, MainDataSource,


SpecialOffersDataSource and StartersDataSource.

When an item is saved, it can be new or can be an existing one, for this reason a IsNew property
was created for each object that allows understanding if we will do an Insert or an Update

The UpdateCacheAsync method

The UpdateCacheAsync is a method used to update the cache for each collection, this code was
provided by AppStudio, when we generated the app, only was applied a refactoring in the
LoadDataAsync method for reuse of the code.

1. public async Task<DateTime> LoadDataAsync(ObservableCollection<T> viewItems, bool f


orceRefresh)
2. {
3. DateTime timeStamp = DateTime.Now;
4.
5. if (HasStaticData)
6. {
7. viewItems.AddRangeUnique(await LoadDataAsync());
8. }
9. else
10. {
11. var dataInCache = await AppCache.GetItemsAsync<T>(CacheKey);
12. if (dataInCache != null)
13. {
14. timeStamp = dataInCache.TimeStamp;
15.
16. viewItems.AddRangeUnique(dataInCache.Items);
17. }
18.
19. if (NetworkInterface.GetIsNetworkAvailable() && DataNeedToBeUpdated(for
ceRefresh, dataInCache))
20. {
21. var freshData = await UpdateCacheAsync();
22.
23. viewItems.AddRangeUnique(freshData.Items);
24. timeStamp = freshData.TimeStamp;
25. }
26. }
27. return timeStamp;
28. }

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


71
Menu App
Microsofts Windows AppStudio

And then we will have:

1. nternal async Task<DataSourceContent<T>> UpdateCacheAsync()


2. {
3. var freshData = new DataSourceContent<T>()
4. {
5. TimeStamp = DateTime.Now,
6. Items = await LoadDataAsync()
7. };
8.
9. await AppCache.AddItemsAsync(CacheKey, freshData);
10. return freshData;
11. }

Each data source must not be static, for it use the property HasStaticData.
The AddItemAsync method

For the AddItemAsync method, the implementation must be done in BeveragesViewModel,


DessertsViewModel, Main1ViewModel, SpecialOffersViewModel and StartersViewModel.

For example, in BeveragesViewModel we will create a BeveragesSchema that is new and it will be
added to the Items list, then the app will navigate to the item view to allow to edit this new object.

The implementation will be something like:

1. public override void AddItemAsync()


2. {
3. ProgressBarVisibility = Visibility.Visible;
4.
5. ProgressBarVisibility = Visibility.Visible;
6. var newItem = new BeveragesSchema();
7. newItem.IsNew = true;
8. Items.Add(newItem);
9. NavigationServices.NavigateToPage("BeveragesDetail", newItem);
10. OnPropertyChanged("PreviewItems");
11. OnPropertyChanged("HasMoreItems");
12.
13. ProgressBarVisibility = Visibility.Collapsed;
14. ProgressBarVisibility = Visibility.Collapsed;
15. }

And in BeveragesDetailPage.xaml.cs in OnNavigateTo change the code to receive the parameter sent
in the AddItemAsync method as in the following:

1. protected async override void OnNavigatedTo(NavigationEventArgs e)


2. {
3. _dataTransferManager = DataTransferManager.GetForCurrentView();
4. _dataTransferManager.DataRequested += OnDataRequested;
5.
6. _navigationHelper.OnNavigatedTo(e);
7.
8. await BeveragesModel.LoadItemsAsync();

72 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio
9. if (e.Parameter is BeveragesSchema)
10. {
11. BeveragesModel.Items.Add(e.Parameter as BeveragesSchema);
12. }
13. BeveragesModel.SelectItem(e.Parameter);
14.
15. if (BeveragesModel != null)
16. {
17. BeveragesModel.ViewType = ViewTypes.Detail;
18. }
19. DataContext = this;
20. }

For the other objects the process is similar.

The CanSave method

The CanSave method will determine if an item can be saved or not, since it uses some validations.

The implementation, for Beverages, Starters and Mains, will be something like:

1. public override bool CanSave()


2. {
3. return !string.IsNullOrEmpty(SelectedItem.Title) &&
4. !string.IsNullOrEmpty(SelectedItem.Subtitle) &&
5. !string.IsNullOrEmpty(SelectedItem.Image) &&
6. !string.IsNullOrEmpty(SelectedItem.Description);
7. }

The Special Offers will be something like:

1. public override bool CanSave()


2. {
3. return !string.IsNullOrEmpty(SelectedItem.Title) &&
4. !string.IsNullOrEmpty(SelectedItem.Subtitle) &&
5. !string.IsNullOrEmpty(SelectedItem.Starter1) &&
6. !string.IsNullOrEmpty(SelectedItem.Main1) &&
7. !string.IsNullOrEmpty(SelectedItem.Dessert1);
8. }

At this moment, the BackOffice App has support for editing the data received from the Azure Mobile
Service and can persist it.

Changing the theme and assets

In the Windows AppStudio we could change the theme and the assets for the BackOffice app, but is
possible do the same in the code. For the BackOffice App we will add the same theme and assets from
the Menu App. For it, go to the Assets folder for Windows 8.1 app and copy and paste the images
related with logos.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


73
Menu App
Microsofts Windows AppStudio

Figure 32 The assets

To change the theme, go to the Style folder in the Windows 8.1 app, open the file AppStyles.xaml and
replace the following styles:

Figure 54 The styles

74 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Running the App

Now that the BackOffice supports editing the data and has a new look, let's see how it looks.

Figure 55 The BackOffice's menu

The main view

The main view will be the start page; in this case, it will be the MainPage.xaml.

The collection view

Figure 35 Editing the Beverage 3

The collection view will be the pages that show a list of objects; in this case, are: BeveragesPage.xaml,
DessertsPage.xaml, Main1Page.xaml, SpecialOffersPage.xaml and StartersPage.xaml

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


75
Menu App
Microsofts Windows AppStudio

The item view

The item view the pages that show a specific item; in this case, it will be: BeveragesDetailPage.xaml,
DessertsDetailPage.xaml, Main1DetailPage.xaml, SpecialOffersDetailPage.xaml and
StartersDetailPage.xaml.

To an existing item:

Figure 36 Editing an existing item

To a new item:

Figure 37 Creating a new item

To have the app bar opened each time for each navigation to the collection view or the item view we
should add the following definition to the OnNavigationTo for each page:

1. BottomAppBar.IsOpen = true;
2. BottomAppBar.IsSticky = true;

76 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

See the source code for the BackOffice App, here: Step 7: Changes the BackOffice app: add
support for edit data from Azure Mobile Service and add new theme and assets. (bit.ly/MenuApp-
Step7)

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


77
Menu App
Microsofts Windows AppStudio

Chapter 4: Adding support for Push


Notification
Push Notifications have become an integral part of any modern application, since they increase user
engagement for consumer apps and the utility of enterprise apps.

To add support for Push Notification:

The MyMenuApp Azure Mobile Service will send the Push Notifications
The Menu App will receive the Push Notifications

The process of adding Push Notification to a Menu App using Azure Mobile Service can be so easy that
we dont need to understand all the process behind it. But it is important to understand at least:

The Windows Phone 8.1 and Windows 8.1 apps uses the Windows Push Notification Services
(WNS). This service enables third-party developers to send toast, tile, badge and raw updates
from their own cloud service. This provides a mechanism to deliver new updates to your users
in a power-efficient and dependable way.
Azure Mobile Service is integrated with Notification Hubs and when the MyMenuApp Azure
Mobile Service was created, in the Azure Portal, was created the MyMenuAppHub-ns
Notification Hub.

An Azure Notification Hubs provide an easy-to-use infrastructure that enables you to send
mobile Push Notifications from any backend (in the cloud or on-premises) to any mobile
platform. Notification Hubs Overview.

A Menu app does not require user authentication, for this reason all notifications sent will be received
by all users.

For applications that use authentication, the process is a little different, because the User X
will not receive the notification for User Y and vice-versa. A good example are the notifications in
Facebook.

78 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Send Push Notification

To send Push Notification, the AppStudio.Menu.BackEnd must be changed and we should use the
Service.Push.SendAsync method to send the notifications.

In table controllers, we have the Service property that contains a Push property that allows us to send
the notification, here are the options for it:

Figure 56 SendAsync method

The notification payload is one of WindowsPushMessage, ApplePushMessage, or


TemplatePushMessage.

In the MyMenuApp Azure Mobile Service, we will notify the user when an object is inserted or
updated. For it, in each controller we will change the Post and Patch methods.

Defining the messages

To avoid repeated code we create the PushHelper static class that will have the definition for the
message we want to send, which implementation is:

1. public static class PushHelper


2. {
3. /// <summary>
4. /// Gets the windows push message for toast text01.
5. /// </summary>
6. /// <param name="typeOfOperation">The type of operation.</param>
7. /// <param name="content">The content.</param>
8. /// <returns>The IPushMessage.</returns>
9. public static IPushMessage GetWindowsPushMessageForToastText01(string typeOfOper
ation, string content)
10. {
11. var payload = new XElement("toast",
12. new XElement("visual",
13. new XElement("binding",
14. new XAttribute("template", "ToastText01"),
15. new XElement("text",
16. new XAttribute("id", "1"), message)))).ToString
(SaveOptions.DisableFormatting);
17. return new WindowsPushMessage
18. {
19. XmlPayload = payload
20. };
21. }
22.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


79
Menu App
Microsofts Windows AppStudio

23. /// <summary>


24. /// The get windows push message for toast image and text 03.
25. /// </summary>
26. /// <param name="typeOfOperation">
27. /// The type of operation.
28. /// </param>
29. /// <param name="title">
30. /// The title.
31. /// </param>
32. /// <param name="subtitle">
33. /// The subtitle.
34. /// </param>
35. /// <param name="image">
36. /// The image.
37. /// </param>
38. /// <returns>
39. /// The <see cref="IPushMessage"/>.
40. /// </returns>
41. public static IPushMessage GetWindowsPushMessageForToastImageAndText03(string ty
peOfOperation, string title, string subtitle, string image)
42. {
43. var payload = new XElement("toast",
44. new XElement("visual",
45. new XElement("binding",
46. new XAttribute("template", "ToastImageAndText03"),
47. new XElement("image", new XAttribute("id", "1"),
48. new XAttribute("src", image),
49. new XAttribute("alt", "image1")),
50. new XElement("text", new XAttribute("id", "1"), string.Concat(
typeOfOperation, " ", title),
51. new XElement("text", new XAttribute("id", "2"), subtitle)
52. ))).ToString(SaveOptions.DisableFormatting);
53.
54. return new WindowsPushMessage
55. {
56. XmlPayload = payload
57. };
58. }
59. }

The typeOfOperation will be Insert or Update and the content will be the Title, Subtitle and
Image from the object. And the template for Toast notification was used, more specifically the
ToastText01 and ToastImageAndText03 but could be another template. See the toast template
catalog in this article. The toast template catalog (Windows Runtime apps), the Tile template catalog
in this article. The tile template catalog (Windows Runtime apps) and the badge option in this article
Badge overview (Windows Runtime apps).

80 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Changing controllers

The controllers BeveragesSchemaController, DessertsSchemaController, MainSchemaController and


StartersSchemaController will use the Windows Push Message for ToastImageAndText03 template
and the controller SpecialOffersSchemaController will use the Windows Push Message for
ToastText01.

Using GetWindowsPushMessageForToastImageAndText03

For example, the complete implementation for the Insert method in the BeveragesSchemaController
can be

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. await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastIm
ageAndText03("Insert:", current.Title, current.Subtitle, current.Image));
16. return CreatedAtRoute("Tables", new { id = current.Id }, current);
17. }

And the complete implementation for the Update method, in the BeveragesSchemaController, is for
example:

1. public async Task<BeveragesSchema> PatchBeveragesSchema(string id, Delta<BeveragesS


chema> patch)
2. {
3. if (string.IsNullOrEmpty(id))
4. {
5. throw new ArgumentNullException("id");
6. }
7. if (patch == null)
8. {
9. throw new ArgumentNullException("patch");
10. }
11. var dto = await UpdateAsync(id, patch);
12. await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastIm
ageAndText03("Update:", dto.Title, dto.Subtitle, dto.Image));
13. return dto;
14. }

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


81
Menu App
Microsofts Windows AppStudio

Using GetWindowsPushMessageForToastText01

The complete implementation for the Insert method, in the SpecialOffersSchemaController, can be:

1. public async Task<IHttpActionResult> PostSpecialOffersSchema(SpecialOffersSchema it


em)
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.Starter1)
10. || string.IsNullOrEmpty(item.Main1)
11. || string.IsNullOrEmpty(item.Dessert1))
12. {
13. return BadRequest("There are properties that are not defined.");
14. }
15. var current = await InsertAsync(item);
16. await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToas
tText01("Insert:", current.Title));
17. return CreatedAtRoute("Tables", new { id = current.Id }, current);
18. }

And the complete implementation for the Update method, in the SpecialOffersSchemaController, is
for example:

1. public async Task<SpecialOffersSchema> PatchSpecialOffersSchema(string id, Delta<Sp


ecialOffersSchema> patch)
2. {
3. if (string.IsNullOrEmpty(id))
4. {
5. throw new ArgumentNullException("id");
6. }
7. if (patch == null)
8. {
9. throw new ArgumentNullException("patch");
10. }
11. var dto = await UpdateAsync(id, patch);
12. await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText
01("Update:", dto.Title));
13. return dto;
14. }

At the end we should publish the services to the server.

See the source code for the change made in AppStudio.Menu.BackEnd: Step 8: Changes
the AppStudio.Menu.BackEnd app: add the PushHelper and add support for send notification after
an insert or update. (bit.ly/MenuApp-Step8)

82 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Receive Push Notification


The Menu App will receive the notification, for it the app must be:

Associated to the Store


Each time the app launch, the app must register the device using the Azure Mobile Service
client
The Azure Mobile Service should learn the CLIENT SECRET and PACKAGE SID from the Menu
App

There are two ways to do it, automatically and manually. In this article we will use the
automatically way because it simplifies the process, to see how to define it manually see the
article Get started with Push Notifications in Mobile Services.

Push Notification Wizard

Select the Windows 8.1 project and open the context menu, then click in Add and then click in
Push Notification

Figure 57 Add push notification support

With it we will see a Wizard that will add Push Notification support based on the MyMenuApp Azure
Mobile Service and this wizard will inform us about the changes it will do.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


83
Menu App
Microsofts Windows AppStudio

Step 1: Before you begin

Figure 3 Wizard: Before you begin

Step 2: Sign in to the Windows Store

Figure 58 Wizard: Sign in to the Windows Store

84 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Step 3: Select an app name

Figure 59 Wizard Select an app name

In this screen you can reserve an app name if it does not yet exist.

Step 4: Select a service

Figure 60 Wizard Select a service

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


85
Menu App
Microsofts Windows AppStudio

Step 5: Summary of pending changes

Figure 7 Wizard Summary of pending changes

Now the wizard finishes and we will see two separators in Visual Studio, the read me file is:

Figure 61 Web page with additional information

86 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

The MyMenuAppPush class:

Figure 9 The MyMenuAppPush

At this moment, the Menu App for Windows 8.1 supports Push Notification and we should install
this version on the device.

The same process should be done for the Menu App for Windows Phone 8.1.

Debugging Push Notifications

Like we mentioned early, Azure Mobile Service is associated with Notification Hubs, for this reason it
is possible to test the Menu App, to see if the app is receiving Push Notifications. This test is
independent of the implementation in the backend and it will allow sending a dummy message to see
if all is okay.

There are the following two ways to test it:

Using Visual Studio


Using the Debug from Notification Hubs in Azure Portal

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


87
Menu App
Microsofts Windows AppStudio

Using Visual Studio

In Visual Studio, open the Server Explorer.

Figure 62 Server Explorer

Then expand the Azure item and expand the Notification Hubs item, click in MyMenuAppHub-ns, open
the context menu and click in Diagnose.

Figure 63 Diagnose

88 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

With it, a window in Visual Studio will be opened, where it is possible to define the message and the
type of the message that we want to send. In our case the type of the message must be a Windows
(WNS) and we will choose a Toast.

Figure 12 Selecting Toast notification

After this selection the message will be filled using a default message for Toast. Here is the message
we will send:

Figure 64 Defining the message

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


89
Menu App
Microsofts Windows AppStudio

Pressing the button Send we will receive the Toast notification and it is possible to see the message
results.

Figure 14 The result

The test Toast notification for Windows Phone 8.1 will be something like:

Figure 65 The push notification received

90 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

With this test we can conclude that the Menu App is okay and the registration to receive Push
Notification is working.

Using the Debug from Notification Hubs in Azure Portal

Go to the Azure Portal, select MyMenuAppHub-ns Notification Hub. In the Debug separator we will
have a similar screen from the Visual Studio, where we can send the messages.

Here is a test sample, like we did in Visual Studio:

Figure 66 Debugging using Azure Portal

After sending the message we will receive the notification and will see the results at the bottom.

Figure 17 The result

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


91
Menu App
Microsofts Windows AppStudio

Testing real Push Notification using BackOffice


Now we have tested the Menu App to receive notification and the Backend was changed, we can use
the BackOffice App to change the data and consequently send the Push Notifications.

Insert notification

In the BackOffice app we will insert a new object and we will receive a notification.

Windows 8.1

Using ToastText01 and Insert a Special Offer:

Figure 18 Push notification based in ToastText01

Using ToastImageAndText03 and Insert a Beverage:

Figure 19 Push notification based in ToastImageAndText03

92 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Windows Phone 8.1

Using ToastText01 and Insert a Special Offer:

Figure 20 Push notification based in ToastText01 to insert an item

Using ToastImageAndText03 and Insert a Beverage:

Figure 67 Push notification based in ToastImageAndText03 to insert an item

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


93
Menu App
Microsofts Windows AppStudio

Update notification
In the BackOffice app we will update an existing object and we will receive a notification.

Windows 8.1

Using ToastText01 and Update a Special Offer:

Figure 68 Push notification based in ToastText01 to update an item

Using ToastImageAndText03 and Update a Beverage.

Figure 69 Push notification based in ToastImageAndText03 to update an item

94 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Windows Phone 8.1


Using ToastText01 and Update a Special Offer.

Figure 704 Push notification based in ToastText01 to update an item

Using ToastImageAndText03 and Update a Beverage:

Figure 71 Push notification based in ToastImageAndText03 to update an item

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


95
Menu App
Microsofts Windows AppStudio

Using Tags

At this moment, all users will receive notification for all starts, mains, beverages, desserts and
special offer. For how they specify that they want to create an option, here the user can subscribe to
what they want to receive, tags is the solution.

Tag expressions enable to target specific sets of devices, or more specifically registrations, when
sending a Push Notification through Notification Hubs.

Suppose that we only want to receive notifications for starters, we need:

In Menu App: Unregister all notification (if necessary!), using:

1. await App.MyMenuAppClient.GetPush().UnregisterNativeAsync();

In Menu App: register the device for the tag starters

2. var tags = new List<string> { "starters" };


3. await App.MyMenuAppClient.GetPush().RegisterNativeAsync(channel.Uri, tags);

In the BackEnd: send the message for the specific tag using:

4. await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01
("Update:", dto.Title), "starters");

To send a message for various languages, we can use tags like en_starters or pt_starters and in
the Backend each message will be sent like we saw before, with the difference that the message is in
English or in Portuguese, depending on the tag used.

See more about using Tags in Routing and Tag Expressions.

96 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Using Templates

In the BackEnd the PushHelper class was created that uses a specific template, the ToastText01 and
it was defined in BackEnd. But it is possible to register the device for a specific template and then the
BackEnd can send the template message.

In a Menu App we have these options:

Figure 26 Register Template

And in BackEnd we will define a TemplatePushMessage to use in the Service.Push.SendAsync method.

See more about templates in this article about Templates .

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


97
Menu App
Microsofts Windows AppStudio

Chapter 5: Integrating with Cortana


One of the interesting features in Windows Phone 8.1 is Cortana. Cortana is an intelligent personal
assistant, that will help users in basic tasks, like call to a friend, schedule an appointment and others
tasks.

Cortana is not available in all languages, for this reason some non-English users have changed their
devices to support it. For see more about how to have Cortana in our Windows Phone 8.1 devices see
the following article.

Integrating Cortana

In this chapter, you will learn how to integrate Cortana in a Windows Phone Application. Cortana will
use Voice Commands for interacting with the apps, these voice commands are pre-installed in the
apps so Cortana knows how to launch each app.

The first step to integrate Cortana, in the Menu App, is to define the Voice Command Definition (VCD)
file, which represents an XML file with the commands that Cortana will recognize and will match with
the app.

For the Menu App we will define Menu as the name for talking with the Menu App and define the
following two commands:

Show Command: that will allow you to choose which menu we want to see: Beverages,
Starters, Mains, Desserts and Special Offers.

Natural Language Command: that will allow to recognize an expression like I am hungry, I
want to eat and I want to drink.

In this sample, the VCD is defined for English (en-US) but more languages could be added.

The VCD file

Here is the VCD file:

1. <?xml version="1.0" encoding="utf-8"?>


2.
3. <!-- Be sure to use the new v1.1 namespace to utilize the new PhraseTopic feature -
->
4. <VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.1">
5. <!-- The CommandSet Name is used to programmatically access the CommandSet -->
6. <CommandSet xml:lang="en-us" Name="englishCommands">
7. <!-
- The CommandPrefix provides an alternative to your full app name for invocation --
>
8. <CommandPrefix>Menu</CommandPrefix>

98 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio
9. <!-- The CommandSet Example appears in the global help alongside your app name --
>
10. <Example> I am hungry </Example>
11.
12. <Command Name="ShowCommand">
13. <Example> Show Mains </Example>
14. <ListenFor> Show {dictatedShowTerms} </ListenFor>
15. <Feedback> Showing in Menu ... </Feedback>
16. <Navigate Target="MainPage.xaml" />
17. </Command>
18.
19. <Command Name="NaturalLanguageCommand">
20. <Example> I want to eat </Example>
21. <ListenFor> {naturalLanguage} </ListenFor>
22. <Feedback> Starting Menu ... </Feedback>
23. <Navigate Target="MainPage.xaml" />
24. </Command>
25.
26.
27. <PhraseTopic Label="dictatedShowTerms" Scenario="Search">
28. <Subject> Starters </Subject>
29. <Subject> Mains </Subject>
30. <Subject> Desserts </Subject>
31. <Subject> Beverages </Subject>
32. <Subject> Special Offers </Subject>
33. </PhraseTopic>
34.
35. <PhraseTopic Label="naturalLanguage" Scenario="Natural Language">
36. <Subject> I want to eat </Subject>
37. <Subject> I want to drink </Subject>
38. <Subject> I am hungry </Subject>
39. </PhraseTopic>
40. </CommandSet>
41. </VoiceCommands>

In the manifest file, check for the capability for Microphone.

The InstallVoiceCommandsAsync method

Now we define the commands, we need to install it in the app each time the app starts.

1. private async Task InstallVoiceCommandsAsync()


2. {
3. var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("m
s-appx:///Cortana.xml"));
4. await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(storageFile)
;
5. }

And then call it in the OnNavigationTo from the MainPage:

1. protected override async void OnNavigatedTo(NavigationEventArgs e)


2. {
3. _dataTransferManager = DataTransferManager.GetForCurrentView();
4. _dataTransferManager.DataRequested += OnDataRequested;
5. _navigationHelper.OnNavigatedTo(e);
6. await MainViewModel.LoadDataAsync();

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


99
Menu App
Microsofts Windows AppStudio

7. if (e.NavigationMode == NavigationMode.New)
8. {
9. await InstallVoiceCommandsAsync();
10. }
11. }

The OnActivated method

We then need to define what the app will be done each time it receives a voice command from
Cortana. When Cortana recognizes a command the Menu App will send the data to the Menu App
and the OnActivated method in App.xaml.cs will be called.

Here is the complete code for the OnActivated method:

1. protected override void OnActivated(IActivatedEventArgs args)


2. {
3. base.OnActivated(args);
4.
5. if (args.Kind == ActivationKind.VoiceCommand)
6. {
7. var commandArgs = args as VoiceCommandActivatedEventArgs;
8.

9. if (commandArgs != null)
10. {
11. SpeechRecognitionResult speechRecognitionResult = commandArgs.Res
ult;
12.
13. var voiceCommandName = speechRecognitionResult.RulePath[0];
14. var textSpoken = speechRecognitionResult.Text;
15.
16. switch (voiceCommandName)
17. {
18. case "ShowCommand":
19. if (textSpoken.ToLower().Contains("starters"))
20. {
21. RootFrame.Navigate(typeof (StartersPage));
22. }
23. if (textSpoken.ToLower().Contains("mains"))
24. {
25. RootFrame.Navigate(typeof(Main1Page));
26. }
27. if (textSpoken.ToLower().Contains("desserts"))
28. {
29. RootFrame.Navigate(typeof(DessertsPage));
30. }
31. if (textSpoken.ToLower().Contains("beverages"))
32. {
33. RootFrame.Navigate(typeof(BeveragesPage));
34. }
35. if (textSpoken.ToLower().Contains("special") || textSpoken.
ToLower().Contains("offer"))
36. {
37. RootFrame.Navigate(typeof(MainPage), "SpecialOffers")
;
38. }
39. break;
40.

41. case "NaturalLanguageCommand":

100 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio
42. if (textSpoken.ToLower().Contains("eat") ||textSpoken.ToLow
er().Contains("hungry"))
43. {
44. RootFrame.Navigate(typeof(Main1Page));
45. }
46.
47. if (textSpoken.ToLower().Contains("drink"))
48. {
49. RootFrame.Navigate(typeof (BeveragesPage));
50. }
51. if (textSpoken.ToLower().Contains("special"))
52. {
53. RootFrame.Navigate(typeof (MainPage), "SpecialOffers"
);
54. }
55. break;
56. }
57. }
58. }
59.

60. Window.Current.Activate();
61. }

Each possible voice command defined in VCD must be handled so the results shown to the user wont
be weird.

Using Cortana
Before we talk with Cortana, we need to run the Menu App in the device, because we need to install
the VCD. After it, we can start Cortana.

Figure 72 Running Cortana

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


101
Menu App
Microsofts Windows AppStudio

Click in see more to see what we can say, as we can see in following figures:

Figure 73 Applications that support Cortana

Each app will show some examples to help users using Cortana. Clicking the Menu App it will show the
samples defined In the VCD file:

Figure 3 Examples

102 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Lets play with Cortana, and for example, lets say: Saying Menu I am hungry.

Figure 74 Saying "Menu I am hungry"

The result is:

Figure 75 Showing mains

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


103
Menu App
Microsofts Windows AppStudio

Saying Menu I want to drink:

Figure 76 Saying "Menu I want to drink"

The result is

Figure 77 Showing beverages

104 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Saying Menu Show offers:

Figure 78 Saying "Menu show offers"

The result is

Figure 9 The special offers

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


105
Menu App
Microsofts Windows AppStudio

See the code in Step 9: How to integrate Cortana with Menu App (bit.ly/MenuApp-Step9)

106 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Chapter 6: Publish the Menu App in the


Store
In this chapter, we will see the last step before the application is available in the Store. Publishing the
application is not only to taking a package and adding it to the store, there is a procedure we need to
complete to make sure it will pass the certification process.

In general, the main procedure we must do is:

Test the app in the simulator or in a real device


Analyze all requirements for submitting an app to the Store
Analyze the common issues in Store certification
Fix any issue found in the preceding steps
Take screenshots for submission to the store
Associate the app with the Store
Generate the packages
Validate the package with Windows App Certification Kit
Create the required artwork (logo and others images, if needed)
Submit the package in Dev Center
Fill in all the data about the app, like description and keywords and define the category and
age rating
Add up to 8 screenshots

Test the app


After the application is created each developer should test the application in the simulator or in real
devices, in some cases it is good to test the app in various devices with various characteristics (but
that is not required!).

The following articles will help to run the app in the simulator or in devices:

About deploying and running apps in Windows Phone Emulator


About deploying and running apps on a Windows Phone device
Deploying and running an app in Visual Studio
Deploying an app with the Application Deployment tool
Troubleshooting app deployment to your phone

For Windows AppStudio apps it is recommended to see the following video for help in the sideloading
process: Generating, Sideloading and Publishing Windows App Studio 8.1 apps for Tablets and PCs.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


107
Menu App
Microsofts Windows AppStudio

Sometimes it isn't easy to test our application or we dont know what to test, a simple and good test
is to provide the package to our friends or beta testers so they can provide a feedback about the app,
normally they see issues that the developer does not see. But before that, it is recommended that
each developer does the basic tests provided in the following article: Testing apps for Windows Phone
8.

In the article testing apps for Windows Phone 8, we can find the App certification requirements for
Windows Phone that is very important! If our app does not respect these requirements then the
application will fail the certification and we should make the updates required by the requirements.
To see the last changes read the article the App certification requirements change history for Windows
Phone and finally we could read the Top Windows Phone app certification failures and how to avoid
them. For Windows apps, you should read the App certification requirements for the Windows Store
and the common certification failures.

Each issue we discover from the tests should be fixed and a new version should be created to apply
new tests. After the app looks great you can skip to the next step.

Take the screenshots


The next step is to take the screenshots that are required and the screenshots will be shown to the
user and we only can upload up to 8 screenshots. To take the screenshots we can use the simulator,
because it has a great feature for it, we only need to deploy the app in the simulator as in the following:

Figure 79 Take screenshots

When we click in the Capture button, the screenshot is taken and the image is saved in a folder we
defined.

108 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Associate app with the Store and generate packages


We can associate the app with the store and for that there are two ways: associate it in Windows
AppStudio or associate it in Visual Studio.

In Windows AppStudio

The last step before generating the app (in Windows AppStudio) is Publish, where the user can
define the app title, the app description, the language and allows them to connect the app with the
store. The following screen shows the Publish separator:

Figure 2 Store Association

In the Publish separator (that we saw above), click in Associate App with the Store, it will show the
following form:

Figure 80 Associate App with the Store

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


109
Menu App
Microsofts Windows AppStudio

To fill in this form, we should open the Dashboard in Windows Phone Dev Center or in Windows Dev
Center to get the information about our account (Publisher GUID, Publisher name).

Figure 81 Choose your dashboard

And in the Dashboard we will find the Account option.

Figure 82 Options

The information about the Menu App (App identity and App display name) is obtained after we
create the application in the dashboard by clicking in Submit App.

110 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 6 Dashboard

Then we will have:

Figure 83 App Info

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


111
Menu App
Microsofts Windows AppStudio

At the end, we will have:

Figure 84 Update publish information

After save all, it's time to generate the app. Click on Finish and then Generate. Now we need to choose
Publish Packages, to create the packages for the Store.

Figure 9 Generate app

112 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

At the end we can download the packages for the store, as we can see in Figure 10.

Figure 85 Download packages

In Visual Studio

To modify the app in Visual Studio or get the source code in Windows AppStudio, it is possible to
connect the app with the Store, by doing:

Figure 11 Associate App with the Store

And then need to follow the wizard:

Figure 12 Associate your app with the store

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


113
Menu App
Microsofts Windows AppStudio

At the end we will have an XML file with the store information, like the following:

Figure 13 Store information file

It is then possible to generate the packages, as in the following:

Figure 86 Create app packages

And we will get another wizard where we can choose if the package will be for the Store and at the
end we can set the package version, the output folder and others.

114 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 87 Select and configure packages

In this case, the packages are created for submission to store and the last panel will show the output
path for the package and an option to run the Windows App Certification Kit.

Figure 88 Packages creation completed

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


115
Menu App
Microsofts Windows AppStudio

Running Windows App Certification Kit


If we click Launch Windows App Certification Kit then we will see the following wizard:

Figure 17 Windows App Certification Kit

116 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Windows App
Certification Kit
is an automatic
process to verify
if the app is
okay and it
allows selecting
which test we
want to run. In
general, we
should select all.

Figure 18 Result

At the end, it will show the result, if it passed or not and provide a report with more details. See the
complete report here: MenuApp-WindowsAppCertificationKit-Report. If the app does not pass these
tests, we should not submit the app to the store until the issues reported in the report are fixed.

An app that passed in this test can fail in other tests that this test does not test, but if the app
does not pass in these tests then it will not pass in the store either. To get more information about
it, see the article: Using the Windows App Certification Kit.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


117
Menu App
Microsofts Windows AppStudio

The artwork

Before going to the Dev Center to submit the app, we should prepare all the artwork. The screenshots
are taken, the app title icon with 300x300 should be created and if necessary create the background
image with 1000 x 800, square icon with 358 x 358 and wide icon with 358 x 173.

It is recommended to see this App submission checklist that helps to prepare and organize all the
required info.

Uploading packages

Now it is time to upload the package and fill in the required data (description, keywords,).

Figure 19 Submit app

118 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Choose the option 2, click Add new and then choose the package.

Figure 89 Choosing the package

It will be uploaded and we will be shown the package name, version and package details.

Figure 21 Packages

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


119
Menu App
Microsofts Windows AppStudio

A form for description, keywords and the options for adding the artwork:

Figure 22 Fill description and artwork

This form needs to be defined for each language supported. And if for some reason you get
any issue when uploading the packages, see the article: Resolving package upload errors.

At this moment all the data was filled in and the app can be submitted to the certification process. If
there is a question about the certification process and the various stages, we can find detailed
info here.

In some cases, it can be useful to add some notes to the testers (from the certification process). To
see how we should do it see the article: Providing info to certification testers.

120 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Now the sky is the limit and our app can be one of the top apps.

Figure 23 Application in the Store

To promote your app, see more about that in the article How to market and promote your
apps on Windows Phone and Windows 8.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


121
Menu App
Microsofts Windows AppStudio

Appendix
Appendix 1: How to Create the Azure Mobile Service in Azure
Portal

This appendix has the goal to show how to create an Azure Mobile Service in the Azure Portal,
providing tips in the process.

Creating the Azure Mobile Service

To create an Azure Mobile Service go to the Azure Portal, at manage.windowsazure.com, do the login
and click on + New at the bottom, as following:

Figure 90 Creating a "New" in Azure Portal

Use the following procedure:

Figure 2 Creating an Azure Mobile Service

122 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

The mobile service settings

A popup will be opened, where we should defined all about the Azure Mobile Service, as following:

Figure 391 Defining the Azure Mobile Service

In this case we selected a free database with 20 MB, be sure it is enough. Each Azure account
can only have one free database.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


123
Menu App
Microsofts Windows AppStudio

The database settings

In the Figure 4, we define all the settings for the database:

Figure 92 Defining the database

At the end of this process we created the Azure Mobile Services and others related items, this mean,
in Azure Account, it was created:

An Azure Mobile Service (MyMenuApp)

The Notification Hub (MyMenuAppHub-ns)

The Database (MyMenuApp_db

124 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

MyMenuApp Azure Mobile Service

To see the Azure Mobile Service created we need to follow the procedure showed in Figure 5:

Figure 5 Selecting the MyMenuApp

MyMenuAppHub-ns Notification Hub

Each Azure Mobile Service automatically creates a Notification Hub and the start point to
Notification Hub, related to the Azure Mobile Service created, is showed in Figure 6:

Figure 6 The MyMenuAppHub-ns notification hub

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


125
Menu App
Microsofts Windows AppStudio

MyMenuuApp_db database

To see the database page, related with the Azure Mobile Service created, we need to follow the
procedure showed in Figure 7:

Figure 7 The MyMenuApp_db database

By default the database created is an Azure SQL Database, but the Azure Mobile Service supports
the MongoDb (www.mongodb.org) database (Non-SQL database). For see more about this subject, see
the following article Creating MongoDB-backed tables in Azure Mobile Services with .NET backend.

Azure SQL Databases has differences from SQL Server Databases, but in general the main features
are supported.

126 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

How to create the Azure Mobile Service project for Visual Studio 2013

There are two ways to create the Azure Mobile Service project:

Creating the project in Visual Studio, using Web or Could Template for Mobile Azure Service

Download the project from the Azure Portal, which is generated in MyMenuApp - Azure
Mobile Service web page.

Creating the project in Visual Studio

Open the Visual Studio 2013 and create a new Web project, as seen below.

And then select the Azure Mobile


Service template.

Figure 8 Creating the project

Figure 9 Selecting the template

It is possible to define the project for Host in the cloud, but for now it will be ignored. Later the
project will be associated with the MyMenuApp Azure Mobile Service.

When the project is created it gives us some default classes for the To-do list sample, but it will be
removed and ignored. At this moment, the project is completely empty, and it only has:

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


127
Menu App
Microsofts Windows AppStudio

WebApiConfig: Defines some configuration for the


WebApi

MobileServiceContext: Is the DbContext for the


services

Global.asax: This will called when the project is


deployed

WebConfig: The configuration for the project will be


in this file

Figure 93 The Azure Mobile Service Project

See the source code related with this appendix: Step 3: Add the base project for
AppStudio.Menu.BackEnd. (bit.ly/MenuApp-Step3)

Download the project from the Azure Portal

To download the project from the Azure Portal, go to the Azure Portal, and select the MyMenuApp
mobile service, as following:

Figure 94 MyMenuApp service

128 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Click in CREATE A NEW WINDOWS STORE APP (we could select other target):

Figure 12 Generating the Azure Mobile Service project

The Windows AppStudio give us the Menu App source code, for this reason can be more easy to create
a new project in Visual Studio, to the Azure Mobile Service, like we saw in the last topic Creating the
project in Visual Studio.

Nuget Package

The Azure Mobile Service project, for .Net backend, by default uses Entity Framework and the main
Nuget package used in this kind of project is

Microsoft Azure Mobile Services .NET Backend Entity Framework Extension


(bit.ly/WindowsAzureMobileServicesBackend)

Installing this Nuget package will install all related Nuget, for this reason is better to install / remove
the packages using it.

If the project shows errors related to references, it's possible to remove this Nuget package
and then install it again to restore the references, in some cases it is required to close the project
and open it again, to load all references added.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


129
Menu App
Microsofts Windows AppStudio

Appendix 2: How merge different source code generated by


AppStudio

When a Windows App Studio application is generated it is possible to get the source code to change it
in Visual Studio, and then run the application in the emulator or in any Windows 8.1/Windows Phone
8.1 device. But if the application is changed in the Windows App Studio website, then the source code
is changed and the new source code needs to be merged. Windows App Studio does not support the
re-upload of the source code that has been changed or

In this appendix you will show a solution to merge the different source code using a tool called Source
Tree , which provides a graphical interface for manage source repositories.

Creating a demo application

Suppose we will create an application in Windows App Studio Website, lets choose the Empty App
template and lets generate the application without make changes. To help in the process, lets set
the build version to 1.0.0.0, as following:

Figure 1 Defining build version

We need to download the source


the code, from the Source Code,
to the local PC.

Figure 95 Download the source code

130 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 96 Source code in local folder

Creating a source code repository

Download the application Source Tree (www.sourcetreeapp.com), which allow to create source
control repositories based in GIT, and install it. At the end, open it, as following:

Click in Clone/New and choose


Create new repository, define the
destination path and the Name and
click Create.

Figure 97 Source Tree opened

Figure 98 Create new repository

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


131
Menu App
Microsofts Windows AppStudio

Click in Open in Explorer and when the folder is opened, move the application generated to this
folder, as following:

Figure 99 Source code in a local folder

Figure 100 Folder moved to Source Tree

The .git folder is a hidden folder that cannot be deleted, it is required for track the changes.

132 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Returning to the Source Tree application, we will have

Figure 8 Unstaged files

Which means, in Unstaged files are all files added to the folder, that can be passed to the Staged
file for then apply a commit (to save the current version). Passing all files to Staged files the
aspect will be something like in Figure 9:

Figure 101 Staged files

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


133
Menu App
Microsofts Windows AppStudio

Now, it is possible to save this version of the source code by doing a commit, as following:

Figure 102 Doing a commit

For each version is important to add a comment, as following

Figure 103 Writing a comment

When we click in the Commit button the application will have a look as following in Figure 12:

134 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 104 The commit

Creating changes

Now, lets open the source code in Visual Studio to change the source code, for example, the
Application Name and the Application Title in App.xaml, as following:

Figure 105 Changing source code

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


135
Menu App
Microsofts Windows AppStudio

Lets define it as MyAppStudioSample in both resources and then in Source Tree, we will see the
differences, as following:

Figure 106 The Unstaged files

In the right, we can see the changes made, in red is the old values and in green the new values, which
we will commit like we did in the first version, and the result will be something as following:

Figure 107 The commit is done

Now, in Windows App Studio lets apply some changes, for example:

- Add a new application title: Microsoft Band News


- Add the Facebook feed using the page https://www.facebook.com/MicrosoftBand

136 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 108 Doing changes in Windows AppStudio WebSite

After this change, we can generate a new source code from the application, defining it as version
2.0.0.0 (for more information about set different version see the Semantic Versioning).

Figure 109 Generating a new version

After the new version is generated it is needed to override the source code in the Sample folder. In
Source Tree its now possible to see the differences between the versions

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


137
Menu App
Microsofts Windows AppStudio

Figure 110 Unstaged Files

In the Unstaged files the yellow circle will say that the file was change and the blue circle will say
the file is new. Selecting a file is possible to see the differences, which the green row means the new
version and the red one is the last version.

For example, the changes made in the Application Title can be find in App.xaml file, as following:

Figure 111 Differences between versions

In the right is possible to accept the change or revert it, to help on it is possible to use the buttons
Stage hunk to accept and Discard hunk to discard the changes

Figure 112 Discard hunk

138 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Or selecting the line is possible accept or reject each line, as following

Figure 113 Selecting row

In this way, each change can be tracked, file by file or even line by line, depending only the
requirements.

Conclusion

In conclusion, using a tool like Source Tree is possible to merge source code from Windows
App Studio in an easy way without knowledge about source controls.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


139
Menu App
Microsofts Windows AppStudio

Appendix 3: Class Diagram: An Easy Way to Understand Code

According to the MSDN,

Class diagrams help you understand the class structure of projects others have written (or that you
wrote a long time ago). You can use them to customize, share and present project information with
others.

In this appendix, we will see how class diagram can be used to understand the code provided or even
our own code. To help, we will use the sample Field Engineer from MSDN Samples
(bit.ly/FieldEngineerSample) and we will be focused on the model classes as an example.

After opening the Field Engineer Sample in Visual Studio, we will find a folder with the name Model.

Figure 114 Field Engineer Sample

This sample does not have so many classes that can be great because it can be easy to understand the
model. Maybe many developers will start opening all the files to see the code, but why not create a
class diagram?

140 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Creating a class diagram

Select the Model folder and then open the context menu, after it click in Add and then click in Class
Diagram, as following:

Figure 2 Creating a Class Diagram

Then, define the class diagrams name, as following:

Figure 115 Defining the name

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


141
Menu App
Microsofts Windows AppStudio

Click in OK and the class diagram file will be added to the project and will be opened.

Figure 116 The Class Diagram

Now we can select all the files in the Model folder and drag and drop them to the class designer area,
which the result will be something as following:

Figure 117 The selected classes in the class diagram

142 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Expanding classes

To expand, click in the arrow in the top, as in the following:

Figure 118 Expanding the class

The Class Details

If we open the context menu under the shape we can select the Class Details, as following:

Figure 7 Selecting Class Details

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


143
Menu App
Microsofts Windows AppStudio

The result will be something like as following:

Figure 119 The Class Details

This way, this user interface will allow to see more details about the classes and it is possible to
create/edit/delete/hide each property, method, event without coding.

Understanding various icons

After expanding all the shapes, we will find that some shapes show the Fields, Properties and Methods
(and can show events, nested classes and so on). Featuring the MobileServiceContext class, as
following:

We can conclude:

The connectionStringName is private and is a const field

All properties are public

The method MobileServiceContext, that is the constructor, is


public and the method OnModelCreating is private

How is possible to conclude it?


Figure 9 The MobileServiceContext

144 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Each icon means something, for example the symbol * in each item means it is private. The best way
to understand the differences between each icon is to create a sample with each possible case.

To understand all icon the good way is to create a fake class for this
purpose. The class will have one field, property and method for
each modifier: private, public, internal and protected and will
have a public event.

Figure 10 MyClass class

Show Base Class

When we select the shape and open the context menu we have options that allow showing/hiding
various details.

Figure 1201 Show Base Class

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


145
Menu App
Microsofts Windows AppStudio

After expanding the shape for MyBaseClass we will see the base class MyBaseClass and the MyClass.

At this moment, we can ask:

To show the diagram, what is the most important information that should be shown in the diagram?

It depends on what each developer likes or wants to see, but in general we can define it as a pattern.
We should show only public properties, methods and events and hide all others (in some cases it can
be useful to show everything defined as internal or protected).

Hide compartment

Selecting the shape and then the item we want to hide, we can Hide Compartment by using the
context menu, as following:

Figure 121 Hide comportment

The option Show all members will revert it, but in some cases it is better to use the Class Details to
revert it, because we can have other items hidden that we want to keep hidden. When a shape hides
some item it will show the icon which means it, here is an example:

146 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Figure 122 Filter

Apply Associations

Returning to the Field Engineer Sample and choosing the class JobHistory, Job and Customer we will
find that each one has a relationship with each other, let's highlight it using a red and orange rectangle,
as following:

Figure 123 The model

Let's see how to show the association for properties and for collections.

Show as Association

For properties that the data type is another class we can select the property in the shape and in the
context menu we should select the option Show as Association.

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


147
Menu App
Microsofts Windows AppStudio

Figure 15 Show as Association

Show as a Collection Association

For properties that are collections/lists we can choose the option Show as Collection Association, as
following:

Figure 124 Show as Collection Association

148 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

And the result will be something like:

Figure 125 Show the relationship

The number of arrows will define it as a property or a collection, but using a good name can be enough
to see the differences.

Show as Property
By selecting in the arrow it is possible to revert it, using the option Show as property.

Figure 126 Show as property

typeof (saramgsilva) www.saramgsilva.com @saramgsilva


149
Menu App
Microsofts Windows AppStudio

The final class diagram

After defining all the arrows for all the associations and organizing the shapes we will have something
as in the following:

Figure 127 The final diagram

For this diagram, we can understand that the model has the five classes and
the MobileServiceContext is defined by these classes. The relationship among the classes is clear (for
example).

A job knows its job histories and each job history refers to a job

A job knows which customer is associated and a customer can have more than one job

A similar determination can be done for Equipment and Equipment Specifications.

It is possible to create arrows for the MobileServiceContext's properties but that will only make
some noise and it is not important in this case to see these associations.

Each developer should customize the class diagram and there are no fixed rules for it. With this kind
f diagram it is very simple to understand the model and in some cases find mistakes like wrong
names, wrong relationships or even missed features.

150 typeof (saramgsilva) www.saramgsilva.com @saramgsilva


Menu App
Microsofts Windows AppStudio

Microsofts Windows AppStudio Menu is the


perfect guide to create and extend a Menu App from
Microsofts Windows AppStudio.

You will learn how to:


Create an application in Windows AppStudio
Create a BackOffice App to manage the data
Connect the Menu App to an Azure Mobile Service
Add support to Push Notifications
Integrate with Cortana

With lots of images, code snippets and source code on


each important step, this eBook will provide all you
need to create fantastic applications.

Sara Silva is a Microsoft MVP focused on Windows,


Azure and Xamarin development. Follow her on Twitter
@saramgsilva.

www.saramgsilva.com
typeof (saramgsilva) www.saramgsilva.com @saramgsilva
151

Вам также может понравиться