How to integrate Cortana in the Menu App

Scope

This article aims to integrate Cortana in the Menu App.

Introduction

One of the interesting feature in Windows Phone 8.1 is Cortana. Cortana is an intelligent personal assistant, which 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 changed their devices for support it. For see more about how to have Cortana in our Windows Phone 8.1 devices see the following article.

Integrating Cortana

Cortana will use Voice Commands for interact with the apps, these voice commands are pre-installed in the apps for Cortana knows how to launch each app.

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

For Menu App we will define “Menu” as the name for talk with the Menu App and will define two commands:

  • Show Command – that will allow to choose which menu we want to see: Beverages, Starters, Mains, Desserts and Special Offers;
  • Natural Language Command – that will allow to recognize 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 could be added more languages.

 

The VCD file

 

Here are the VCD file:

<?xml version="1.0" encoding="utf-8"?>
 
<!-- Be sure to use the new v1.1 namespace to utilize the new PhraseTopic feature -->
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.1">
    <!-- The CommandSet Name is used to programmatically access the CommandSet -->
    <CommandSet xml:lang="en-us" Name="englishCommands">
        <!-- The CommandPrefix provides an alternative to your full app name for invocation -->
        <CommandPrefix>Menu</CommandPrefix>
        <!-- The CommandSet Example appears in the global help alongside your app name -->
        <Example> I am hungry </Example>
 
        <Command Name="ShowCommand">
          <Example> Show Mains </Example>
          <ListenFor> Show {dictatedShowTerms} </ListenFor>
          <Feedback> Showing in Menu ... </Feedback>
          <Navigate Target="MainPage.xaml" />
        </Command>
      
        <Command Name="NaturalLanguageCommand">
            <Example> I want to eat </Example>
            <ListenFor> {naturalLanguage} </ListenFor>
            <Feedback> Starting Menu ... </Feedback>
            <Navigate Target="MainPage.xaml" />
        </Command>
 
     
        <PhraseTopic Label="dictatedShowTerms" Scenario="Search">
          <Subject> Starters </Subject>
          <Subject> Mains </Subject>
          <Subject> Desserts </Subject>
          <Subject> Beverages </Subject>
          <Subject> Special Offers </Subject>
        </PhraseTopic> 
 
        <PhraseTopic Label="naturalLanguage" Scenario="Natural Language">
            <Subject> I want to eat </Subject>
            <Subject> I want to drink </Subject>
            <Subject> I am hungry </Subject>
         </PhraseTopic>
    </CommandSet>
</VoiceCommands>

Note: In manifest file, should be check the capability for Microphone.

 

The InstallVoiceCommandsAsync method

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

Create the method

private async Task InstallVoiceCommandsAsync()
{
          var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Cortana.xml"));
          await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(storageFile);
}

And then call it in the OnNavigationTo from the MainPage:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
         _dataTransferManager = DataTransferManager.GetForCurrentView();
         _dataTransferManager.DataRequested += OnDataRequested;
         _navigationHelper.OnNavigatedTo(e);
         await MainViewModel.LoadDataAsync();
         if (e.NavigationMode == NavigationMode.New)
         {
             await InstallVoiceCommandsAsync();
         }
}

 

The OnActivated method

 

After it, we need to define what the app will do each time it receive a voice command from Cortana. Cortana when recognize a command for the Menu App will send the data to the Menu App, and the OnActivated method in App.xaml.cs will be called.

Here are the complete code for OnActivated method:

protected override void OnActivated(IActivatedEventArgs args)
       {
           base.OnActivated(args);
         
           if (args.Kind == ActivationKind.VoiceCommand)
           {
               var commandArgs = args as VoiceCommandActivatedEventArgs;
               if (commandArgs != null)
               {
                   SpeechRecognitionResult speechRecognitionResult = commandArgs.Result;
 
                   var voiceCommandName = speechRecognitionResult.RulePath[0];
                   var textSpoken = speechRecognitionResult.Text;
                   
                   switch (voiceCommandName)
                   {
                       case "ShowCommand":
                           if (textSpoken.ToLower().Contains("starters"))
                           {
                               RootFrame.Navigate(typeof (StartersPage));
                           }
                           if (textSpoken.ToLower().Contains("mains"))
                           {
                               RootFrame.Navigate(typeof(Main1Page));
                           }
                           if (textSpoken.ToLower().Contains("desserts"))
                           {
                               RootFrame.Navigate(typeof(DessertsPage));
                           }
                           if (textSpoken.ToLower().Contains("beverages"))
                           {
                               RootFrame.Navigate(typeof(BeveragesPage));
                           }
                           if (textSpoken.ToLower().Contains("special") || 
                               textSpoken.ToLower().Contains("offer"))
                           {
                               RootFrame.Navigate(typeof(MainPage), "SpecialOffers");
                           }
                           break;
                       case "NaturalLanguageCommand":
                           if (textSpoken.ToLower().Contains("eat") ||
                               textSpoken.ToLower().Contains("hungry"))
                           {
                               RootFrame.Navigate(typeof(Main1Page));
                           }
 
                           if (textSpoken.ToLower().Contains("drink"))
                           {
                                RootFrame.Navigate(typeof (BeveragesPage));
                           }
                           if (textSpoken.ToLower().Contains("special"))
                           {
                               RootFrame.Navigate(typeof (MainPage), "SpecialOffers");
                           }
                           break;
                   }
               }
           }
           Window.Current.Activate();
       }

Each possible voice command defined in VCD must be handled for the results showed to the user don´t 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


And the click in “see more”, for see what we can say


 

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:


 

Playing with Cortana, we will see the following:

Saying “Menu I am hungry”




 

And then


Saying “Menu I want to drink”

 



 


Saying “Menu Show offers”



 


Code

See the code for this sample in

Step 9: How to integrate Cortana with Menu App

 

See also

[PT] Revista PROGRAMAR – 46ª Edição

Revista PROGRAMAR – Edição 46 – Setembro de 2014


(clica para download)

Nesta edição trazemos até si como tema de capa o artigo Paralelização de Aplicações com OpenMP, de Rui Gonçalves. Adicionalmente, poderá ainda encontrar nesta edição os seguintes artigos:

Continuamos também a premiar os autores dos três melhores artigos, dado o sucesso nas edições anteriores. E os leitores devem dar a sua opinião para que possamos premiar correctamente. Para isso vote em http://tinyurl.com/ProgramarED46-V.

Microsoft’s Windows AppStudio: Add support for Push Notification

Scope

This article has the goal to add suport for Push Notification in the Menu App.

Before start, see the last two articles

Introduction

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

     For add support to push notification

  • The MyMenuApp Azure Mobile Service will send the push notifications
  • The Menu App will receive the push notifications

 

The process, for add push notification to the Menu App using Azure Mobile Service, can be so easy that we don´t need to understand all process be hide. But is important to know 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.

 

Menu app not requires user authentication, for this reason all notification sent will be received by all users.

Note: Applications that uses 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.

 

Send Push Notification

 

For send push notification, the AppStudio.Menu.BackEnd must be changed and we should use the Service.Push.SendAsync method for send the notifications.

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

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

 

For avoid repeated code was created the PushHelper static class, that will have the definition for the message we want to send.

The implementation will be something like

public static class PushHelper
   {
       /// <summary>
       /// Gets the windows push message for toast text01.
       /// </summary>
       /// <param name="typeOfOperation">The type of operation.</param>
       /// <param name="content">The content.</param>
       /// <returns>The IPushMessage.</returns>
       public static IPushMessage GetWindowsPushMessageForToastText01(string typeOfOperation, string content)
       {
           var payload = new StringBuilder();
           payload.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>");
           payload.Append(@"<toast><visual><binding template=""ToastText01"">");
           payload.Append(@"<text id=""1"">");
           payload.Append(typeOfOperation);
           payload.Append(content);
           payload.Append(@"</text>");
           payload.Append(@"</binding></visual></toast>");
           return new WindowsPushMessage
           {
               XmlPayload = payload.ToString()
           };
       }
 
       /// <summary>
       /// The get windows push message for toast image and text 03.
       /// </summary>
       /// <param name="typeOfOperation">
       /// The type of operation.
       /// </param>
       /// <param name="title">
       /// The title.
       /// </param>
       /// <param name="subtitle">
       /// The subtitle.
       /// </param>
       /// <param name="image">
       /// The image.
       /// </param>
       /// <returns>
       /// The <see cref="IPushMessage"/>.
       /// </returns>
       public static IPushMessage GetWindowsPushMessageForToastImageAndText03(string typeOfOperation, string title, string subtitle, string image)
       {
           var payload = new StringBuilder();
           payload.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>");
           payload.Append(@"<toast><visual><binding template=""ToastImageAndText03"">");
           payload.Append(@"<image id=""1"" src=""");
           payload.Append(image);
           payload.Append(@""" alt=""image1"" />");
           payload.Append(@"<text id=""1"">");
           payload.Append(typeOfOperation);
           payload.Append(title);
           payload.Append(@"</text>");
           payload.Append(@"<text id=""2"">");
           payload.Append(subtitle);
           payload.Append(@"</text>");
           payload.Append(@"</binding></visual></toast>");
           return new WindowsPushMessage
           {
               XmlPayload = payload.ToString()
           };
       }

 

The typeOfOperation will be “Insert” or “Update” and the content will be the “Title”, “Subtitle” and “Image” from the object. And was used the template for Toast notification, more specific 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).

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 Insert method in the BeveragesSchemaController will be something like

public async Task<IHttpActionResult> PostBeveragesSchema(BeveragesSchema item)
       {
           if (item == null)
           {
               throw new ArgumentNullException("item");
           }
           if (string.IsNullOrEmpty(item.Title)
               || string.IsNullOrEmpty(item.Subtitle)
               || string.IsNullOrEmpty(item.Image)
               || string.IsNullOrEmpty(item.Description))
           {
               return BadRequest("There are properties that are not defined.");
           }
           var current = await InsertAsync(item);
           await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastImageAndText03("Insert:", current.Title, current.Subtitle, current.Image));
           return CreatedAtRoute("Tables", new { id = current.Id }, current);
       }

 And the complete implementation for Update method in the BeveragesSchemaController will be something like

public async Task<BeveragesSchema> PatchBeveragesSchema(string id, Delta<BeveragesSchema> patch)
       {
           if (string.IsNullOrEmpty(id))
           {
               throw new ArgumentNullException("id");
           }
           if (patch == null)
           {
               throw new ArgumentNullException("patch");
           }
           var dto = await UpdateAsync(id, patch);
           await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastImageAndText03("Update:", dto.Title, dto.Subtitle, dto.Image));
           return dto;
       }

 

Using GetWindowsPushMessageForToastText01

 

 The complete implementation for Insert method in the SpecialOffersSchemaController will be something like

public async Task<IHttpActionResult> PostSpecialOffersSchema(SpecialOffersSchema item)
      {
          if (item == null)
          {
              throw new ArgumentNullException("item");
          }
          if (string.IsNullOrEmpty(item.Title)
              || string.IsNullOrEmpty(item.Subtitle)
              || string.IsNullOrEmpty(item.Starter1)
              || string.IsNullOrEmpty(item.Main1)
              || string.IsNullOrEmpty(item.Dessert1))
          {
              return BadRequest("There are properties that are not defined.");
          }
          var current = await InsertAsync(item);
              await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01("Insert:", current.Title));
          return CreatedAtRoute("Tables", new { id = current.Id }, current);
      }

And the complete implementation for Update method in the SpecialOffersSchemaController will be something like

public async Task<SpecialOffersSchema> PatchSpecialOffersSchema(string id, Delta<SpecialOffersSchema> patch)
     {
         if (string.IsNullOrEmpty(id))
         {
             throw new ArgumentNullException("id");
         }
         if (patch == null)
         {
             throw new ArgumentNullException("patch");
         }
         var dto = await UpdateAsync(id, patch);
         await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01("Update:", dto.Title));
         return dto;
     }

 

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

 

Code

 

See the source code for the change made in AppStudio.Menu.BackEnd, here

Step 8: Changes the AppStudio.Menu.BackEnd app: add the PushHelper and add support for send notification after an insert or update.

 

 

Receive Push Notification

 

The Menu App will receive 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 know the CLIENT SECRET and PACKAGE SID from the Menu App

There are two ways for do it, “automatically” and “manually”. In this article we will use the “automatically” way because it simplify the process, for 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…”

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

1º Step: Before you begin

 

2º Step: Sign in to the Windows Store

 

 

3º Step: Select an app name

 

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

4º Step: Select a service

 

5º Step: Summary of pending changes

 

Now the wizard finish, we will see two separator in visual studio, the read me file is

And the MyMenuAppPush class is

 

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 is possible to test the Menu App, for see if the app is receiving push notifications. This test is independent of the implementation in the backend and it allow to send dummy message for see if all is ok.

 There are two ways for test it

Using Visual Studio

 

In Visual Studio, open the 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”

With it, will be opened a window in Visual Studio, where 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

After this selection the message will be filled using a default message for Toast.

Here is the message we will send

Pressing the button “Send” we will receive the Toast notification and is possible to see the message result

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

With this test we can conclude that Menu App is ok and the registration for 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

 

 

After send the message we will receive the notification and will see the result at the bottom

 

 

Testing real Push Notification using BackOffice

 

Now we tested the Menu App for receive notification and the BackEnd was changed, we can use the BackOffice App for 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 & Insert a Special Offer

 

Using ToastImageAndText03 & Insert a Beverage

Windows Phone 8.1

Using ToastText01 & Insert a Special Offer

Using ToastImageAndText03 & Insert a Beverage

Update notification

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

Windows 8.1

 

Using ToastText01 & Update a Special Offer

Using ToastImageAndText03 & Update a Beverage

 

Windows Phone 8.1

 

Using ToastText01 & Update a Special Offer

Using ToastImageAndText03 & Update a Beverage

Using Tags

 

At this moment, all users will receive notification for all starts, mains, beverages, desserts and special offer. For how that wants to create an option here the user can subscribe 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
await App.MyMenuAppClient.GetPush().UnregisterNativeAsync();
  • In Menu App – register the device for the tag “starters”
var tags = new List<string> { "starters" };
await App.MyMenuAppClient.GetPush().RegisterNativeAsync(channel.Uri, tags);
  • In BackEnd – send the message for the specific tag using
await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01("Update:", dto.Title), "starters");

For send message for different 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 the tag used.

See more about using Tags, in Routing and Tag Expressions.

 

Using Templates

 

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

In Menu App we have this options

And in BackEnd we will define a TemplatePushMessage for use in the Service.Push.SendAsync method. See more about templates in this article Templates.

Intel’s® RealSense™ App Challenge 2014

Intel’s® RealSense™ App Challenge 2014 is a worldwide Developer challenge which has
evolved from the 2013 Perceptual Computing Challenges. Using the most recent 2014 Software Development Kit (SDK)
and Intel’s new 3D gesture camera, participants will be challenged to envision new ways that this technology can be
implemented into computing experiences on Desktops, Laptops and Tablets. Developers in over 30 different countries will compete
against one another for nearly $1,000,000 (USD) in cash and prizes as well as cutting edge computing software and hardware.

The Schedule? (All dates subject to change)
Ideation Phase 7/28/14 – 10/1/14
Ideation Judging 10/02/14 – 10/22/14
SDPs Shipped 10/24/14 – 11/13/14
Development Phase 11/14/14 – 01/20/15
Early Submission Deadline 12/19/14
Development Judging 1/21/15 – 2/18/15

What are the Prizes?

Over $1,000,000 (USD) in total prizes is being offered for the entire challenge.

Pioneer Track Prizes
  • Grand Prize: (1) $25,000. One overall winner chosen from the first place winners of each category will win an additional cash prize.
  • First Place: (5) $25,000. The top scoring demo in each category will win a $25,000 cash prize
  • Second Place: (10) $10,000. Two demos from each of the 5 categories will receive a $10,000 cash prize
  • Early Submission: (25) $1,000. The top scoring demos, submitted prior to the Early submission deadline, across all 5 categories will each receive a cash prize of $1,000
  • Haswell NUC: (250). The top 250 scoring demos from Phase 1, across all 5 categories, will receive a Haswell NUC device valued at approximately $557. This device is not required to compete in Phase 2, but the winning Pioneers may do so if they wish.

See more:

The website: https://realsenseappchallenge.intel.com
The FAQ https://realsenseappchallenge.intel.com/inter/faq/

Microsoft’s Windows AppStudio: Creating a BackOffice App for Menu App

Scope

This article aims to create a BackOffice App for the Menu App created by Windows AppStudio in the article

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

How to create a BackOffice App

The MyMenuApp Azure Mobile Service was defined and the Menu App consumes the data from the service, now we will create the BackOffice App for change that data.

For help in creating the BackOffice App, we will use the Empty Template from Windows AppStudio for create the start point of this app, that will contain

  • A start menu with the following chooses: 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 for 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”

In the next screen, click in Empty App Template

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

Here is the start point

Changing the app’s name

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

Creating the menu

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

Click in the arrow in the menu created, for expand it

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

Adding collections

Click in the collection menu for create the first menu item

Collection using default columns

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

That will create the following structure

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, like we did in Menu App.

After create each collection is recommended to save the definitions, using the button “Save” in the right.

Do the same process for Mains, Desserts and Beverages.

Collection using specific columns

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

It will create a row as following

For each field insert the respective information: field’s name, type and if is multiline.

At the end we will have something like it

Note: Each field name should start with upper case.

After all collection are defined, we will have the following definition

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

Editing a collection

Is possible to edit the Starters by clicking in “Edit Item”, that will show the follow screen

For each collection we need to do the following:

  • Define the Layout & Bindings for the windows with the list of items
  • Define the Layout & Bindings & Page Extras for the detail of the item
  • Edit the data for add one dummy starter

Editing Layout & Bindings

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

And for the detail page

Editing default data

Now, we will edit the default data, by clicking in “Data” separator and then in “Edit Data”

Click in “Create new” and fill the item with dummy values like following

Here, is not important what we will fill, it only allow 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 start point for the BackOffice App, is possible to define the theme, the tiles, the publish info, but this article will not cover it. For see in more depth how to define each one, see the article Creating Windows Phone and Window 8.1 applications using Microsoft App Studio.

 Generating the BackOffice app

Now we will click in “Finnish” button for generate the BackOffice App

The following screen will be showed

Click in “Generate” button for generate the source code

For generate the app for Windows 8.1 and Windows Phone 8.1 we should click in that option, that will be a Universal App, like the Menu App.

Click in the link for download the source code

Code

See the source code for the BackOffice App, here

Step 6: Add default BackOffice App generated by AppStudio

 

Changing the source code generated

Now we have a start point for the BackOffice, we will change the code for support editing the data consumed by the Azure Mobile Service

For add the MyMenuApp Azure Mobile Service to the BackOffice App, see the topic How to consume the Azure Mobile Services in Menu App . The changes in BackOffice are the same.

Note:

  1. The default columns added the “ImageUrl” in each collection, and each dto from the service uses the name “Image“. There are two option for 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 Service we added the static data from 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 don´t have these images. For solve it for now, do a copy & paste of these images (it will be temporary!)

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 launch, in this case, will be MainPage.xaml.

The collection view

The collection view will be the page that show a list of objects, in this case, will be

BeveragesPage.xaml, DessertsPage.xaml, Main1Page.xaml, SpecialOffersPage.xaml and StartersPage.xaml.

The item view

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

The others collection has a 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 for edit data
  • Add an AppBarButton for “Add” a new item in the collection view
  • Add two AppBarButton for “Save” & “Delete” the current item in the item view

    Note: We will only focus in 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)

 

Changing the data templates

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

Each one contains the DataTemplates used in each page.

For find which template should be changed open the BeveragesDetailPage.xaml, that it the page for see a selected Beverage. We will find the FlipView that contains the a ItemTemplate defined, called Beverages1DetailDetail

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

<DataTemplate x:Key="Beverages1DetailDetail">

Change this template for something like

<DataTemplate x:Key="Beverages1DetailDetail">
        <StackPanel Margin="120,0,0,0">
            <TextBlock Text="Title:" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Margin="0,20,0,0"  Grid.Column="1" 
                     Text="{Binding Title, Mode=TwoWay}" Width="400" HorizontalAlignment="Left"/>
            <TextBlock Text="Subtitle:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" 
                     Text="{Binding Subtitle, Mode=TwoWay}" Margin="0,20,0,0"  Width="400" HorizontalAlignment="Left"/>
            <TextBlock Text="Image:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" Margin="0,20,0,0"  
                     Text="{Binding Image, Mode=TwoWay}" Width="400" HorizontalAlignment="Left"/>
            <Image Grid.RowSpan="2" 
                   Source="{Binding Image}" Margin="0,20,0,0" 
                   Width="200" Height="200"
                   HorizontalAlignment="Left" Stretch="UniformToFill" />
            <TextBlock Text="Description:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="1" Grid.Column="1" 
                     Margin="0,20,0,0" ScrollViewer.HorizontalScrollBarVisibility="Auto"
                     ScrollViewer.VerticalScrollBarVisibility="Auto"
                     AcceptsReturn="true" HorizontalAlignment="Left"
                     Height="200" MaxHeight="200" Width="800" MaxWidth="800"
                     Text="{Binding Description, Mode=TwoWay}" />
        </StackPanel>
    </DataTemplate>

It will result in something like it

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

<DataTemplate x:Key="SpecialOffers1DetailDetail">
        <StackPanel Margin="120,0,0,0">
            <TextBlock Text="Title:" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Margin="0,20,0,0"  Grid.Column="1" 
                     Text="{Binding Title, Mode=TwoWay}" Width="400" HorizontalAlignment="Left"/>
           
            <TextBlock Text="Subtitle:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" 
                     Text="{Binding Subtitle, Mode=TwoWay}" Margin="0,20,0,0"  Width="400" HorizontalAlignment="Left"/>
 
 
            <TextBlock Text="Starter1:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" 
                     Text="{Binding Starter1, Mode=TwoWay}" Margin="0,20,0,0"  Width="400" HorizontalAlignment="Left"/>
 
            <TextBlock Text="Main1:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" 
                     Text="{Binding Main1, Mode=TwoWay}" Margin="0,20,0,0"  Width="400" HorizontalAlignment="Left"/>
             <TextBlock Text="Dessert1:" Margin="0,20,0,0" 
                     Style="{StaticResource ItemHeaderTextSnapped}" />
            <TextBox Grid.Row="0" Grid.Column="1" 
                     Text="{Binding Dessert1, Mode=TwoWay}" Margin="0,20,0,0"  Width="400" HorizontalAlignment="Left"/>
        </StackPanel>
    </DataTemplate>

The result will be something like

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

Adding the AppBarButtons

For allow to do the operations “Add”, “Save” and “Delete” is needed to add an AppBarButton for each operation.

In the BeveragesDetailPage.xaml add the following app bar

<Page.BottomAppBar>
    <CommandBar Background="{StaticResource AppBarBackground}">
      <AppBarButton DataContext="{Binding BeveragesModel}" 
                    x:Uid="SaveButton" 
                    Command="{Binding SaveCommand}">
        <AppBarButton.Icon>
          <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Save.png"/>
        </AppBarButton.Icon>
      </AppBarButton>
            <AppBarButton DataContext="{Binding BeveragesModel}" 
                    x:Uid="DeleteButton" 
                    Command="{Binding DeleteCommand}">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Delete.png"/>
                </AppBarButton.Icon>
            </AppBarButton>
        </CommandBar>
  </Page.BottomAppBar>

That will add the “Save” and “Delete” AppBarButton. This XAML can be added to the others object’s pages.

For add the “Add” AppBarButton, open the BeveragesPage.xaml and added the following XAML

<Page.BottomAppBar>
    <CommandBar Background="{StaticResource AppBarBackground}">
            <AppBarButton x:Uid="AddButton" 
                         Command="{Binding AddCommand}"
                        DataContext="{Binding BeveragesModel}">
                <AppBarButton.Icon>
                    <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Add.png"/>
                </AppBarButton.Icon>
            </AppBarButton>
            <AppBarButton x:Uid="RefreshButton" DataContext="{Binding BeveragesModel}" Visibility="{Binding RefreshVisibility}"
                  Command="{Binding RefreshCommand}">
        <AppBarButton.Icon>
          <BitmapIcon UriSource="ms-appx:///Assets/AppBar/Refresh.png"/>
        </AppBarButton.Icon>
      </AppBarButton>
    </CommandBar>
  </Page.BottomAppBar>

Do the same for the others object’s pages.

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

Notes:

Changing the code be hide (C#)

Go to ViewModelBase.cs file in the Shared project

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

public ICommand AddCommand
{
    get { return new DelegateCommand(AddItem); }
}
 
public ICommand DeleteCommand
{
    get { return new DelegateCommand(DeleteItem); }
}
 
public ICommand SaveCommand
{
    get { return new DelegateCommand(SaveItem); }
}

After it, add the missed methods

public abstract bool CanSave();
       
 public abstract void AddItemAsync();
       
private async void DeleteItemAsync ()
{
     // todo
}      

private async void SaveItemAsync ()
{
    // todo
}

The methods CanSave and AddItemAsync will be implemented in the view model for each object, more specific 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 ViewModelBase<T> class because they can be generic.

The DeleteItemAsync method

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

The implementation will be something like it

private async void DeleteItemAsync()
       {
           ProgressBarVisibility = Visibility.Visible;
           var currentItem = GetCurrentItem();
 
           var messageDialog = new MessageDialog(currentItem.DefaultTitle, "Are you sure you want to delete this item?");
           messageDialog.Commands.Add(new UICommand("Yes"));
           messageDialog.Commands.Add(new UICommand("No"));
           var result = await messageDialog.ShowAsync();
           if (result.Label == "Yes")
           {
               await DataSource.DeleteAsync(currentItem);
               Items.Remove(currentItem);
               OnPropertyChanged("PreviewItems");
               OnPropertyChanged("Items");
               OnPropertyChanged("HasMoreItems");
           }
        
           ProgressBarVisibility = Visibility.Collapsed;
       }

This will require a changes in DataSourceBase<T> class

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

public override async Task DeleteAsync(BeveragesSchema currentItem)
{
    await _mobileService.Table.DeleteAsync(currentItem);
    await UpdateCacheAsync();
}

This code applies to the others 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 for confirm the operation was done and then the UI will be updated.

private async void SaveItem()
       {
           if (!CanSave())
           {
               var cannotSaveMessageDialog = new MessageDialog("You must fill all data.", "Attention!");
               cannotSaveMessageDialog.Commands.Add(new UICommand("Ok"));
               await cannotSaveMessageDialog.ShowAsync();
               return;
           }
           ProgressBarVisibility = Visibility.Visible;
           var currentItem = GetCurrentItem();
           var messageDialog = new MessageDialog(currentItem.DefaultTitle, "The item was saved!");
           messageDialog.Commands.Add(new UICommand("Ok"));
           await DataSource.SaveAsync(currentItem);
           await messageDialog.ShowAsync();
           OnPropertyChanged("Items");
           OnPropertyChanged("PreviewItems");
           OnPropertyChanged("HasMoreItems");
           ProgressBarVisibility = Visibility.Collapsed;
       }

In  BeveragesDataSource we will do something like

public override async Task SaveAsync(BeveragesSchema currentItem)
       {
           BeveragesSchema item = null;
           if (currentItem.IsNew)
           {
               await _mobileService.Table.InsertAsync(currentItem);
           }
           else
           {
               await _mobileService.Table.UpdateAsync(currentItem);
           }
           currentItem.IsNew = false;
          await UpdateCache();
       }

This code applies to the others data sources: DessertsDataSource, MainDataSource, SpecialOffersDataSource and StartersDataSource.

Note: When an item is saved, the item can be new or can be an existing item, for this reason was created a IsNew property for each object that allow to understand if we will do an Insert or an Update.

The UpdateCacheAsync method

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

public async Task<DateTime> LoadDataAsync(ObservableCollection<T> viewItems, bool forceRefresh)
{
    DateTime timeStamp = DateTime.Now;
 
    if (HasStaticData)
    {
        viewItems.AddRangeUnique(await LoadDataAsync());
    }
    else
    {
        var dataInCache = await AppCache.GetItemsAsync<T>(CacheKey);
        if (dataInCache != null)
        {
            timeStamp = dataInCache.TimeStamp;
 
            viewItems.AddRangeUnique(dataInCache.Items);
        }
 
        if (NetworkInterface.GetIsNetworkAvailable() && DataNeedToBeUpdated(forceRefresh, dataInCache))
        {
            var freshData = await UpdateCacheAsync();
 
            viewItems.AddRangeUnique(freshData.Items);
            timeStamp = freshData.TimeStamp;
        }
    }
    return timeStamp;
}

And then we will have

internal async Task<DataSourceContent<T>> UpdateCacheAsync()
{
    var freshData = new DataSourceContent<T>()
    {
        TimeStamp = DateTime.Now,
        Items = await LoadDataAsync()
    };
 
    await AppCache.AddItemsAsync(CacheKey, freshData);
    return freshData;
}

Note: Each data source must be not 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 for allow to edit this new object.

The implementation will be something like

public override void AddItemAsync()
        {
            ProgressBarVisibility = Visibility.Visible;
 
            ProgressBarVisibility = Visibility.Visible;
            var newItem = new BeveragesSchema();
            newItem.IsNew = true;
            Items.Add(newItem);
            NavigationServices.NavigateToPage("BeveragesDetail", newItem);
            OnPropertyChanged("PreviewItems");
            OnPropertyChanged("HasMoreItems");
 
            ProgressBarVisibility = Visibility.Collapsed;
            ProgressBarVisibility = Visibility.Collapsed;
        }

And in BeveragesDetailPage.xaml.cs in OnNavigateTo change the code for receive the parameter sent in AddItemAsync method

protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        _dataTransferManager = DataTransferManager.GetForCurrentView();
        _dataTransferManager.DataRequested += OnDataRequested;
 
        _navigationHelper.OnNavigatedTo(e);
 
        await BeveragesModel.LoadItemsAsync();
        if (e.Parameter is BeveragesSchema)
        {
            BeveragesModel.Items.Add(e.Parameter as BeveragesSchema);
        }
        BeveragesModel.SelectItem(e.Parameter);
 
        if (BeveragesModel != null)
        {
            BeveragesModel.ViewType = ViewTypes.Detail;
        }
        DataContext = this;
    }

For the others objects the process is similar.

The CanSave method

The CanSave method will define if an item can be saved or not, for it used some validations.

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

public override bool CanSave()
        {
            return !string.IsNullOrEmpty(SelectedItem.Title) &&
                   !string.IsNullOrEmpty(SelectedItem.Subtitle) &&
                   !string.IsNullOrEmpty(SelectedItem.Image) &&
                   !string.IsNullOrEmpty(SelectedItem.Description);
        }

For Special Offers will be something like

public override bool CanSave()
   {
       return !string.IsNullOrEmpty(SelectedItem.Title) &&
              !string.IsNullOrEmpty(SelectedItem.Subtitle) &&
              !string.IsNullOrEmpty(SelectedItem.Starter1) &&
              !string.IsNullOrEmpty(SelectedItem.Main1) &&
              !string.IsNullOrEmpty(SelectedItem.Dessert1);
   }

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

Changing the theme and assets

In the 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

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

Running the App

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

The main view

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

The collection view

The collection view will be the pages that show a list of objects, in this case, will be

BeveragesPage.xaml, DessertsPage.xaml, Main1Page.xaml, SpecialOffersPage.xaml and StartersPage.xaml.

The item view

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

For existing item

For a new item

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

BottomAppBar.IsOpen = true;
BottomAppBar.IsSticky = true;

Code

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.

Survey on API Consumption and Tooling

APIs lie at the heart of our cloud-first, mobile-first strategy. In order to provide you with the best-in class tooling for consuming our wide variety of APIs – VS Online, Office 365, Dynamics, Azure, Xbox, Bing, to name just a few – we would like to learn more about your experience. Which APIs provided a particularly pleasant experience to develop against? Which tools do you use on a regular basis? Where do you see room for improvement? No matter whether you just started using your first API or are an experienced developer, whether you are using Microsoft or other services, we are looking for your feedback.

survey

This survey can take as little as 5 minutes to complete and it is completely anonymous. Your feedback will help shaping a set of new developer experiences, inside and outside of Visual Studio. If you are willing to participate in further user studies or discuss your experience with us in person, be sure to check the opt-in box and provide your email address, we will then follow-up with you on feedback sessions. Please also pass the survey on to other developer who you think may want to provide input.

 

 

[TechNet Wiki] I won in 3 categories the Microsoft TechNet Guru Awards! (August 2014)

Yesterday was published the Microsoft TechNet Guru Awards! (August 2014), for the 5th month I was selected as Technical Guru, this time in three categories:

  • Miscellaneous Technical Guru – August 2014
  • Visual C# Technical Guru – August 2014
  • Windows Phone and Windows Store Apps Technical Guru – August 2014

Here are the comments for each one

technical guru

technical guru

technical guru

 

[technet wiki] Top Contributor Awards… from last week

All weeks is done an analyze to the TechnNet Wiki contributions. And in the last week, I am on the TOP 10, for the second time :)
top contributer image

read more in

Top Contributors Awards! SCSM, SharePoint 2010, Avengers, Visual Studio Plugin, Runbook, and lots of name drops! Is it you?

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

Scope

This article aims to connect the Menu App from Windows App Studio with Azure Mobile Service, using .Net back end.

Introduction

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


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

Menu Template

Menu Template is one template provide by App Studio, and it is used for the following scenario:

“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

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

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

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

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

Understanding the source code

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

  • AppStudio.Windows – project for Windows Store App
  • AppStudio.WindowsPhone – project for the Windows Phone App
  • AppStudio.Shared – shared project used for both target (it allow to reuse code)
  • AppStudio.Data – project that contains the model and data source.

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

The model

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

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

The data sources

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


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

Code

See the changes made in default Menu App, here:

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

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

Requirements

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

Azure Account

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

Azure SDK

Get the Azure SDK and install it, from Downloads.

How to create the Azure Mobile Service in Azure Portal

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

How to create the MyMenuApp Azure Mobile Service.

How to create the Azure Mobile Services

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

Recap, the model has theses classes

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

Based in these classes, we will create the follow services

  • MainSchemaController – the service for managing the MainSchemas
  • SpecialOffersSchemaController – the service for managing the SpecialOffersSchemas
  • DessertsSchemaController – the service for managingthe DessertsSchemas
  • StartersSchemaController – the service for managing the StartersSchemas
  • BeveragesSchemaController – the service for managing the BeveragesSchemas

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

The data objects (Dtos) will be:

  • MainSchema
  • SpecialOffersSchema
  • DessertsSchema
  • StartersSchema
  • BeveragesSchema

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

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

Other solutions could be, to have the Dtos mapped with the model. This article, Build a service using an existing SQL database with the Mobile Services .NET backend, shows an example that has Dtos and a model, which 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 contains shared properties.

The Dtobase class

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

public class DtoBase : EntityData
{
       public string Title { get; set; }
       public string Subtitle { get; set; }
       public string Image { get; set; }
       public string Description { get; set; }
}

The BeveragesSchema class

public class BeveragesSchema : DtoBase   {   }

The DessertsSchema class

public class DessertsSchema : DtoBase   {   }

The MainSchema class

public class MainSchema :  DtoBase   {   }

The StartersSchema class

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.

public class SpecialOffersSchema : EntityData
{
        public string Dessert1 { get; set; }
        public string Main1 { get; set; }
        public string Starter1 { get; set; }
        public string Title { get; set; }
        public string Subtitle { get; set; }
 }

Class Diagram

Here are the class diagrams


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

Services

Each service will be an Azure Mobile Service Table Controller

Each service should be defined as the following

The BeveragesSchemaController

Which the output will be something like

public class BeveragesSchemaController : TableController<BeveragesSchema> 
    { 
        protected override void Initialize(HttpControllerContext controllerContext) 
        { 
            base.Initialize(controllerContext); 
            MobileServiceContext context = new MobileServiceContext(); 
            DomainManager = new EntityDomainManager<BeveragesSchema>(context, Request, Services); 
        } 
  
        // GET tables/BeveragesSchema1 
        public IQueryable<BeveragesSchema> GetAllBeveragesSchema() 
        { 
            return Query();  
        } 
  
        // GET tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959 
        public SingleResult<BeveragesSchema> GetBeveragesSchema(string id) 
        { 
            return Lookup(id); 
        } 
  
        // PATCH tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959 
        public Task<BeveragesSchema> PatchBeveragesSchema(string id, Delta<BeveragesSchema> patch) 
        { 
             return UpdateAsync(id, patch); 
        } 
  
        // POST tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959 
        public async Task<IHttpActionResult> PostBeveragesSchema(BeveragesSchema item) 
        { 
            BeveragesSchema current = await InsertAsync(item); 
            return CreatedAtRoute("Tables", new { id = current.Id }, current); 
        } 
  
        // DELETE tables/BeveragesSchema1/48D68C86-6EA6-4C25-AA33-223FC9A27959 
        public Task DeleteBeveragesSchema(string id) 
        { 
             return DeleteAsync(id); 
        } 
  
    } 

For the other services, the process is the same, only change the dto selected and the name of the controller.

Note: The service will be inside the Controllers folder.

Class diagram

After creating all service, we will have

Validate data

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

Here is the code for insert a BeverageSchema that validate data

public async Task<IHttpActionResult> PostBeveragesSchema(BeveragesSchema item)
{
          if (item == null)
          {
              throw new ArgumentNullException("item");
          }

          if (string.IsNullOrEmpty(item.Title)
              || string.IsNullOrEmpty(item.Subtitle)
              || string.IsNullOrEmpty(item.Image)
              || string.IsNullOrEmpty(item.Description))
          {

              return BadRequest("There are properties that are not defined.");

          }

          var current = await InsertAsync(item);
          return CreatedAtRoute("Tables", new { id = current.Id }, current);

      }

The same validation can be done in the others dtos.

The DomainManager

Each service has an Initialize method where it defined the DomainManager as following

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

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

The EntityDomainManager<T>

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

The MobileServiceContext

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

The MobileServiceContext was changed because when each service was created. It was also automatically added the following DataSets

public DbSet<Data.BeveragesSchema> BeveragesSchemas { get; set; }

public DbSet<DataObjects.DessertsSchema> DessertsSchemas { get; set; } public DbSet<DataObjects.MainSchema> MainSchemas { get; set; }

public DbSet<DataObjects.SpecialOffersSchema> SpecialOffersSchemas { get; set; }

public DbSet<DataObjects.StartersSchema> StartersSchemas { get; set; }

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

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

The Database

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

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

When the project was created, we removed some code that was ignored, and with it we deleted the code related with the Database Initializer, that uses the class DropCreateDatabaseIfModelChanges it 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.

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

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

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

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

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

Defining the connection string

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

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

And then scroll to

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

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

Defining the allowed IP for the database

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

Scroll down until to find the following menu in the right

And then allow the current IP

Migration

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

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

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 for revert the process if necessary.

Seed

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

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

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

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

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

Is this that will create the database or will update the database following the current model.

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

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

Running the Services

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

Localhost

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

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

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

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

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

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

This data is the data defined in 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

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

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

Our default browser will open a window with the service.

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

By clicking in the Manage Keys we will get

How to see details about errors

When we run the service, we get this windows

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

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

And then we get the list

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

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

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

How to do the remote debugging

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

In the MyMenuApp Azure Mobile Service > Configure be sure you have this on

Note: For how uses Visual Studio 2013 Update 2 or later it is turn on automatically

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 in attach debugger

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

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

Set the breakpoint and do the request, then the breakpoint will be hit


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

Code

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

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

Manage Images

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

This article will not cover this topic. To see how to implement this feature see the following article Upload images to Azure Storage by using Mobile Services. Which 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, is time to connect the Menu App with the MyMenuApp Azure Mobile services.

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

Using Managed Nuget Pacakges

Select the AppStudio.Data project, and then open the Manage Nuget Packages

Install the Windows Azure Mobile Services nuget package like the following

Is required to install this package in each target (Windows 8.1 and Windows Phone 8.1 apps).

Using Connected Service

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


After it, login in using your Azure account and you will see your Azure Mobile Services as following


By clicking in the MyMenuApp Azure Mobile Service we will add the Nuget package for Azure Mobile Service

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


The MobileService<T>

After it, create the MobileService<T> class in DataSource folder in the AppStudio.Data project, as following

  /// <summary> 
   /// Defines the Mobile Service wrapper. 
   /// </summary> 
   /// <typeparam name="T">The type of the DTO.</typeparam> 
   public sealed class MobileService<T> 
   { 
       private static MobileServiceClient _appStudioBackEnd; 
  
       /// <summary> 
       /// Gets the application studio back end. 
       /// </summary> 
       /// <value>The application studio back end.</value> 
       private static MobileServiceClient AppStudioBackEnd 
       { 
           get 
           { 
               return _appStudioBackEnd ?? (_appStudioBackEnd = new MobileServiceClient("<the service url>", "<the application key from Portal>")); 
           } 
       } 
  
       /// <summary> 
       /// Initializes a new instance of the <see cref="MobileService{T}"/> class. 
       /// </summary> 
       public MobileService() 
       { 
           Table = AppStudioBackEnd.GetTable<T>(); 
       } 
  
       /// <summary> 
       /// Gets or sets the table. 
       /// </summary> 
       /// <value> 
       /// The table. 
       /// </value> 
       public IMobileServiceTable<T> Table { get; set; } 
   } 

Then for each data source do something like

public async override Task<IEnumerable<SpecialOffersSchema>> LoadDataAsync() 
{         
 var mobileService = new MobileService<SpecialOffersSchema>(); 
 return await mobileService.Table.ToListAsync(); 
}

After this, run the Menu App.


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

Code

See the code, here

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


How to create the Azure Mobile Service in Azure Portal

Scope

This article aims to show how to create an Azure Mobile Service in the portal and how to create the Visual Studio 2013 Project.

This article complements the article

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

Creating the Azure Mobile Service

Go to the Portal, login and click on “+ New”, at the bottom

Do the following steps

The mobile service settings

Then we will see the following screen that should be completed:

Note: In this case we selected the free database with 20 MB, be sure that is enough. Each Azure account only can have one free database.

The database settings

In this screen, define all settings for the database

At the end of this process we will have created the Azure Mobile Services and others related items.

The MyMenuApp items created in Azure Account

When the Azure Mobile Service is created, it will create in your account:

  • An Azure Mobile Service
  • The Notification Hub
  • The Database

Here are the starting points for each.

MyMenuApp Azure Mobile Service

This is the start point for the Azure Mobile Service created.

MyMenuAppHub-ns Notification Hub

Each Azure Mobile Service automatically creates a Notification Hub. This topic is outside the scope of this article.

This is the start point for the Notification Hub related with Azure Mobile Service created.

MyMenuuApp_db database

This is the start point for the database related with the Azure Mobile Service created.

By default this database is an Azure SQL Database, but the Azure Mobile Service supports MongoDb database (NonSQL database), but this scenario is outside the scope of this article. For see more about this, see the following article

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

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

There are two ways to have 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 Portal that 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

Here 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. More relative, in this article we will be creating similar classes for the Menu App.

Here is the base project that we will use for the back end development

At this moment, the project is completely empty, it only has

  • 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

Code

See the source code for the AppStudio.Menu.BackEnd, here

Step 3: Add the base project for AppStudio.Menu.BackEnd.

Download the project from the Portal

Go to the Portal, and select the MyMenuApp mobile service

And then click in “CREATE A NEW WINDOWS STORE APP” (could be other target), as following

Because we have the default Menu App from App Studio, it would be better to create the Azure Mobile Service using Visual Studio.

Nuget Package

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

Microsoft Azure Mobile Services .NET Backend Entity Framework Extension

Note: If the project shows errors related with references it’s possible to remove this Nuget package and then install it again to restore references, in some cases it is required to close the project and open it again.