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.

[TechNet Wiki] Top Contributor Awards! …from last week

All weeks is done an analyze to the TechnNet Wiki contributions. And in this week, I am on the TOP 10! My first time in TechNet :)

top

read more in

Top Contributor Awards! Compatibility! Security! Tutoring! Customisation! Duplication! WE GOT IT ALL! And it’s yours! And it’s free! Happy Days!

AzureConf – An Azure Community Event

An Azure Community Event

We’ve received such a great response from the community about AzureConf 2013 that we’re proud to let you know the community conference is coming back!

On September 25th, 2014, Microsoft will be hosting AzureConf, another free event for the Azure community. This event will feature a keynote presentation by Scott Guthrie, along with numerous sessions executed by Azure community members. Streamed live for an online audience on Channel 9, the event will allow you to see how developers just like you are using Azure to develop robust, scalable applications on Azure. Community members from all over the world will join known speakers such as Michael Collier, Mike Martin, Rick Garibay, and Chris Auld in the Channel 9 studios to present their own inventions and experiences. Whether you’re just learning Microsoft Azure or you’ve already achieved success on the platform, you won’t want to miss this special event.

Register for AzureConf

If you’d like to be reminded of the upcoming event and to receive updates via email about AzureConf, please register using the form below. Registration for the event isn’t required for you to attend, but we’d love to send you some preliminary information about the event and to keep you informed as to how the event’s progressing. Once you register, we’ll give you an .ICS file you can download to block some time on your calendar to attend this free, live event online.

 

See more in

https://www.azureconf.net/

Survey for Web App developers or Cordova developers

Developer Experiences Building Hybrid and/or Web Apps 

The Visual Studio team is looking for developers building hybrid apps using Apache Cordova™  and developers building web apps to provide feedback on their experiences. Your input will provide direct feedback to support changes in future versions of Visual Studio.

 

This survey can take as little as 5-10 minutes to complete. We are also looking for people to join 30 minute feedback sessions to talk about their experiences in a phone call. If you are interested in joining a feedback session please let us know in the survey. If you are selected to participate in a feedback session, a coordinator will contact you with details regarding scheduling and gratuity. When completing this survey you may also opt in to our survey sweepstakes* for a chance to win a $100 or $50 gift card.

 

The information you provide is entirely voluntary. If you do not wish to provide us with any information, please disregard this survey. By filling out and returning this survey, you agree that we can use, disclose, reproduce, or otherwise distribute your feedback at the aggregated level. Your personal information will remain confidential. Please check http://privacy.microsoft.com/en-us/default.aspx for Microsoft Privacy Statements.

*See details on the next page on how to qualify

 

[C#] Generic Xml Serialize & Deserialize

Here are some methods to help in serialize an object to xml string and then deserialize from xml string to the object.

The Serialize method:

 /// <summary>
        /// The serialize.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="xmlWriterSettings">
        /// The xml writer settings.
        /// </param>
        /// <typeparam name="T">
        /// The object of the type T.
        /// </typeparam>
        /// <returns>
        /// The value in <see cref="string"/> that correspond the xml.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// The value cannot be null.
        /// </exception>
        public static string Serialize<T>(T value, XmlWriterSettings xmlWriterSettings = null)
        {
            if (value == null)
            {
                throw new ArgumentException("value");
            }

            var serializer = new XmlSerializer(typeof(T));

            var settings = xmlWriterSettings ?? new XmlWriterSettings
            {
                Encoding = new UnicodeEncoding(false, false),
                Indent = false,
                OmitXmlDeclaration = false
            };

            using (var textWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }

                return textWriter.ToString();
            }
        }

 

The Deserialize method:

        /// <summary>
        /// The deserialize.
        /// </summary>
        /// <param name="xml">
        /// The xml.
        /// </param>
        /// <param name="xmlReaderSettings">
        /// The xml Reader Settings.
        /// </param>
        /// <typeparam name="T">
        /// The object of the type T.
        /// </typeparam>
        /// <returns>
        /// The object of the type <see cref="T"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// The xml value cannot be null.
        /// </exception>
        public static T Deserialize<T>(string xml, XmlReaderSettings xmlReaderSettings = null)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentException("xml");
            }

            var serializer = new XmlSerializer(typeof(T));

            var settings = xmlReaderSettings ?? new XmlReaderSettings();

            // No settings need modifying here
            using (var textReader = new StringReader(xml))
            {
                using (var xmlReader = XmlReader.Create(textReader, settings))
                {
                    return (T)serializer.Deserialize(xmlReader);
                }
            }
        }

 

 

Class that inherits from other class should be defined using the attributes

[Serializable]

and

[XmlInclude(typeof( ... ))]

For example:

[Serializable]
[XmlInclude(typeof(Child))]
public class Father
{
  // something
}


[Serializable]
public class Child : Father
{
  // something
}