Creating Azure Mobile App With Visual Studio

In this article we are going to create a mobile application with Azure using Visual Studio. Before you start with it make sure that you have some azure credits with you. You can always create a new azure free account where you can claim some free credits with an  Azure free trial . Please note that you can get only limited Azure credits with the free account. But to get started, that is more than enough. Now we will go and create our application. I hope you will like this.

Please see this article in my blog here 

Download the source code

You can always download the source code here.

Background

We all know what Azure is. If you are really new to Azure, I strongly recommend you to have a look here .To get started, please make sure that you have installed Visual Studio in your machine. Download Visual Studio.

Setting Azure Portal

Login to your Azure portal from Azure Portal. Once you logged in, you can see a dashboard and a menu as follows.

Microsoft Azure Portal Menu
      Microsoft Azure Portal Menu

Now click on New -> Web+Mobile -> Mobile App.

Web Mobile Category In Azure Portal
                                   Web Mobile Category In Azure Portal

Now name your mobile application. Select your subscription, it will be automatically selected if you have only one subscription. Please select the subscription accordingly if you have multiple subscriptions. Select or create new resource group. You may be thinking what is this resource group, and what are all the benefits for using it. According to Microsoft, a resource group is a collection of resources so that you can use those accordingly. A resource can be included only in one resource group and it is possible to link the resources in other resource group. Please be noted that you can’t edit and rename your resource group name. Only option you are allowed is to move your resources to your new resource group. Please see Move resources to a new resource group in azure if you need to move your resources.

Now select your service plan or location as per your need. Now click on that link. You can see all the service plans you have used so far, you can select those if you want or you can create a new one.

Available App Service Plan In Azure
                                 Available App Service Plan In Azure

To create a new one, please click the ‘Create new’ option.

New App Service Plan In Azure
               New App Service Plan In Azure

Now select your app service plan, location, pricing tier. When you select the pricing tier, please be cautious because Azure charge you according to your use. Select it according your use.

App Service Pricing Tier
                     App Service Pricing Tier

Now this is how you Mobile App service set up looks like. You can always pin your mobile app to your dashboard.

Mobie App Service
                           Mobie App Service

Once this is done, you will get a notification that your mobile app deployment is succeeded if nothing goes wrong and you can see the app in your dashboard. Now click on the settings of your mobile application and then quick start.

Quick Start Option In Azure Mobile App
                                    Quick Start Option In Azure Mobile App

Select Windows(C#) from it. Now you will be asked to complete three actions.

  • Connect a database
  • Create a table API
  • Configure your client application

Connect a database

Click on connect a database ( We will create a database first). Click Add and add a data connection as follows.

Data Connections In Azure Mobile App
                                    Data Connections In Azure Mobile App

Now give your database name and pricing tier. For now I am going to select the pricing tier as Basic. You can see 5 DTUs are available for Basic tier. According to Microsoft, The Database Transaction Unit (DTU) is the unit of measure in SQL Database that represents the relative power of databases based on a real-world measure: the database transaction. Please read more here.

Did you notice that there is a field called Collation? Basically a collation is a set of rules and regulation we set for the proper use of characters. Like the characters are much different in all the languages, we set the collation accordingly. The default collation for character data in Azure SQL database isSQL_Latin1_General_CP1_CI_AS. You can read about collation here.

Next, set your server and click OK. Once you click OK, you can see the connection strings is being set automatically for you. Creation of data connection may take few minutes. Now we will create a table API.

Create a table API

To store the data in your back end. You need a table, isn’t it? The first option you will see here is select the language for your back end actions. You can select either C# or Node JS.

There was a time, that we can do server side actions only by using server side languages like C#,Vb.Net, PhP etc. Now everything changes, we can do server side actions with few set of JavaScript, that is Node JS.

Once you select your language you can see a message as “Once you’ve downloaded your personalized server project, extract it and open in Visual Studio. Right-click the project and select “Publish” to host the code in your mobile backend. The TodoItem table will be created automatically using Entity Framework.” Now we will do as suggested.

Please open your downloaded project in Visual Studio. Right click the project file then click publish. You can see a window and finish Profile, Connection, Settings steps.

Azure Mobile App preview
                                             Azure Mobile App preview

Click publish once you verified the settings. It may take few minutes according to your internet bandwidth. In the meanwhile you can see all the controllers and additional files had been created for us automatically. For example below is the Values controller.

  1. using System.Web.Http;  
  2. using System.Web.Http.Tracing;  
  3. using Microsoft.Azure.Mobile.Server;  
  4. using Microsoft.Azure.Mobile.Server.Config;  
  5. namespace SibeeshTasksService.Controllers  
  6. {  
  7. // Use the MobileAppController attribute for each ApiController you want to use  
  8. // from your mobile clients  
  9. [MobileAppController]  
  10. public class ValuesController : ApiController  
  11. {  
  12. // GET api/values  
  13. public string Get()  
  14. {  
  15. MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();  
  16. ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter();  
  17. string host = settings.HostName ?? "localhost";  
  18. string greeting = "Hello from " + host;  
  19. traceWriter.Info(greeting);  
  20. return greeting;  
  21. }  
  22. // POST api/values  
  23. public string Post()  
  24. {  
  25. return "Hello World!";  
  26. }  
  27. }  
  28. }  
Now the publish process is completed, you can see a message as follows.
  
Azure App Service Publish
                                       Azure App Service Publish

Now please go back to your Azure portal.

Configure your client application

It is time to configure our client application now. Download the client application by clicking the link provided. And open the project in Visual Studio. Please install the missing files if it is asked to do so.

MIssing Componenets
                                         MIssing Componenets

Once the installation is done, reload your project and it will be asked to enable developer mode for windows 10. Go ahead and change that in settings.

Now please open the shared project and click on MainPage.cs file, you can see the CRUD operation actions are already created for us.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.WindowsAzure.MobileServices;  
  6. using Windows.UI.Popups;  
  7. using Windows.UI.Xaml;  
  8. using Windows.UI.Xaml.Controls;  
  9. using Windows.UI.Xaml.Navigation;  
  10. // To add offline sync support, add the NuGet package Microsoft.WindowsAzure.MobileServices.SQLiteStore  
  11. // to your project. Then, uncomment the lines marked // offline sync  
  12. // For more information, see: http://aka.ms/addofflinesync  
  13. //using Microsoft.WindowsAzure.MobileServices.SQLiteStore; // offline sync  
  14. //using Microsoft.WindowsAzure.MobileServices.Sync; // offline sync  
  15. namespace SibeeshTasks  
  16. {  
  17. sealed partial class MainPage: Page  
  18. {  
  19. private MobileServiceCollection<TodoItem, TodoItem> items;  
  20. private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();  
  21. //private IMobileServiceSyncTable<TodoItem> todoTable = App.MobileService.GetSyncTable<TodoItem>(); // offline sync  
  22. public MainPage()  
  23. {  
  24. this.InitializeComponent();  
  25. }  
  26. private async Task InsertTodoItem(TodoItem todoItem)  
  27. {  
  28. // This code inserts a new TodoItem into the database. When the operation completes  
  29. // and Mobile App backend has assigned an Id, the item is added to the CollectionView.  
  30. await todoTable.InsertAsync(todoItem);  
  31. items.Add(todoItem);  
  32. //await SyncAsync(); // offline sync  
  33. }  
  34. private async Task RefreshTodoItems()  
  35. {  
  36. MobileServiceInvalidOperationException exception = null;  
  37. try  
  38. {  
  39. // This code refreshes the entries in the list view by querying the TodoItems table.  
  40. // The query excludes completed TodoItems.  
  41. items = await todoTable  
  42. .Where(todoItem => todoItem.Complete == false)  
  43. .ToCollectionAsync();  
  44. }  
  45. catch (MobileServiceInvalidOperationException e)  
  46. {  
  47. exception = e;  
  48. }  
  49. if (exception != null)  
  50. {  
  51. await new MessageDialog(exception.Message, "Error loading items").ShowAsync();  
  52. }  
  53. else  
  54. {  
  55. ListItems.ItemsSource = items;  
  56. this.ButtonSave.IsEnabled = true;  
  57. }  
  58. }  
  59. private async Task UpdateCheckedTodoItem(TodoItem item)  
  60. {  
  61. // This code takes a freshly completed TodoItem and updates the database. When the service  
  62. // responds, the item is removed from the list.  
  63. await todoTable.UpdateAsync(item);  
  64. items.Remove(item);  
  65. ListItems.Focus(Windows.UI.Xaml.FocusState.Unfocused);  
  66. //await SyncAsync(); // offline sync  
  67. }  
  68. private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)  
  69. {  
  70. ButtonRefresh.IsEnabled = false;  
  71. //await SyncAsync(); // offline sync  
  72. await RefreshTodoItems();  
  73. ButtonRefresh.IsEnabled = true;  
  74. }  
  75. private async void ButtonSave_Click(object sender, RoutedEventArgs e)  
  76. {  
  77. var todoItem = new TodoItem { Text = TextInput.Text };  
  78. await InsertTodoItem(todoItem);  
  79. }  
  80. private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)  
  81. {  
  82. CheckBox cb = (CheckBox)sender;  
  83. TodoItem item = cb.DataContext as TodoItem;  
  84. await UpdateCheckedTodoItem(item);  
  85. }  
  86. protected override async void OnNavigatedTo(NavigationEventArgs e)  
  87. {  
  88. //await InitLocalStoreAsync(); // offline sync  
  89. await RefreshTodoItems();  
  90. }  
  91. #region Offline sync  
  92. //private async Task InitLocalStoreAsync()  
  93. //{  
  94. // if (!App.MobileService.SyncContext.IsInitialized)  
  95. // {  
  96. // var store = new MobileServiceSQLiteStore("localstore.db");  
  97. // store.DefineTable<TodoItem>();  
  98. // await App.MobileService.SyncContext.InitializeAsync(store);  
  99. // }  
  100. //  
  101. // await SyncAsync();  
  102. //}  
  103. //private async Task SyncAsync()  
  104. //{  
  105. // await App.MobileService.SyncContext.PushAsync();  
  106. // await todoTable.PullAsync("todoItems", todoTable.CreateQuery());  
  107. //}  
  108. #endregion  
  109. }  
  110. }  
And following is the XAML file created for our app design.
  1. <Page  
  2. x:Class="SibeeshTasks.MainPage"  
  3. IsTabStop="false"  
  4. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  5. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  6. xmlns:local="using:SibeeshTasks"  
  7. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  8. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  9. mc:Ignorable="d">  
  10. <Grid Background="White">  
  11. <Grid Margin="50,50,10,10">  
  12. <Grid.ColumnDefinitions>  
  13. <ColumnDefinition Width="*" />  
  14. <ColumnDefinition Width="*" />  
  15. </Grid.ColumnDefinitions>  
  16. <Grid.RowDefinitions>  
  17. <RowDefinition Height="Auto" />  
  18. <RowDefinition Height="*" />  
  19. </Grid.RowDefinitions>  
  20. <Grid Grid.Row="0" Grid.ColumnSpan="2" Margin="0,0,0,20">  
  21. <StackPanel>  
  22. <TextBlock Foreground="#0094ff" FontFamily="Segoe UI Light" Margin="0,0,0,6">MICROSOFT AZURE MOBILE SERVICES</TextBlock>  
  23. <TextBlock Foreground="Gray" FontFamily="Segoe UI Light" FontSize="45" >SibeeshTasks</TextBlock>  
  24. </StackPanel>  
  25. </Grid>  
  26. <Grid Grid.Row="1">  
  27. <StackPanel>  
  28. <local:QuickStartTask Number="1" Title="Insert a TodoItem" Description="Enter some text below and click Save to insert a new todo item into your database" />  
  29. <StackPanel Orientation="Horizontal" Margin="72,0,0,0">  
  30. <TextBox Name="TextInput" Margin="5" MinWidth="300"></TextBox>  
  31. <Button Name="ButtonSave" Click="ButtonSave_Click" IsEnabled="False">Save</Button>  
  32. </StackPanel>  
  33. </StackPanel>  
  34. </Grid>  
  35. <Grid Grid.Row="1" Grid.Column="1">  
  36. <Grid.RowDefinitions>  
  37. <RowDefinition Height="Auto" />  
  38. <RowDefinition />  
  39. </Grid.RowDefinitions>  
  40. <StackPanel>  
  41. <local:QuickStartTask Number="2" Title="Query and Update Data" Description="Click refresh below to load the unfinished TodoItems from your database. Use the checkbox to complete and update your TodoItems" />  
  42. <Button Margin="72,0,0,0" Name="ButtonRefresh" Click="ButtonRefresh_Click">Refresh</Button>  
  43. </StackPanel>  
  44. <ListView Name="ListItems" Margin="62,10,0,0" Grid.Row="1">  
  45. <ListView.ItemTemplate>  
  46. <DataTemplate>  
  47. <StackPanel Orientation="Horizontal">  
  48. <CheckBox Name="CheckBoxComplete" IsChecked="{Binding Complete, Mode=TwoWay}" Checked="CheckBoxComplete_Checked" Content="{Binding Text}" Margin="10,5" VerticalAlignment="Center"/>  
  49. </StackPanel>  
  50. </DataTemplate>  
  51. </ListView.ItemTemplate>  
  52. </ListView>  
  53. </Grid>  
  54. </Grid>  
  55. </Grid>  
  56. </Page>  
Now please run your project. Here I am running the app in visual studio. You can always run the same in Windows Emulator. If nothing goes wrong you can see an output as follows.
  
task
                                                                                 Azure Mobile App Output

task                                                                  Azure Mobile App Output Inserting And Reading

Just to make sure that the entries has been inserted and the data is getting from the database we can go back to our Azure portal. We all are humans, we believe things when we see. We all asks for the proof. Isn’t it? Click on SQL databases from the menu. Now you can see all the databases you have created, click on the database and get the server name, user id and password form the connection string. Once you get it, open your SQL Server Management Studio in your local machine and provide the details you took from the connection string. Now you can see the our Azure SQL database in your local SSMS.

Connect Azure SQL Database Through SSMS
         Connect Azure SQL Database Through SSMS

Now we can query our table and see the data. Right?

  1. USE [Tasks]  
  2. GO  
  3. SELECT [Id]  
  4. ,[Text]  
  5. ,[Complete]  
  6. ,[Version]  
  7. ,[CreatedAt]  
  8. ,[UpdatedAt]  
  9. ,[Deleted]  
  10. FROM [dbo].[TodoItems]  
  11. GO  
I am sure you will get an result as follows.
  
Querying Azure SQL Database In SSMS
                           Querying Azure SQL Database In SSMS

You can always run this same application in Windows Emulator, Now we will see how we can do that.

Download Windows Emulator

Before getting started, you must install Windows Emulator in your machine. You can get the Windows 10 emulator from here. Please be noted that there are some sysytem requirements and actions to be taken care of before going to install the emulator. Basically Microsoft emulator works as a virtual machine on Hyper V. You must enable it.

Enable Hyper-V in Windows

To enable Hyper-V, go to control panel and select Programs, then click on ‘Turn windows feature on or off’ and then select all the items under Hyper-V.

Enable Hyper V in Windows
                                 Enable Hyper V in Windows

You may need to restart your system once. There are some additional requirements too.

System Requirements

We must enable the following configurations in BIOS.

  • Hardware-assisted virtualization
  • Second Level Address Translation (SLAT)
  • Hardware-based Data Execution Prevention (DEP)

And we need,

  • 4GB or more RAM
  • OS Windows 8 or higher(Pro edition or higher)

To go to BIOS settings in Windows 10, Just type ‘change advanced startup options’ in the start search box. And then click on the Restart under advanced settings. There you will see the BIOS options. Once you are done these procedures, you can go ahead and install Windows Emulator. After you install the emulator you can see an option to run the app in emulator in Visual Studio.

Run app in Windows emulator

Please see the option as follows in visual studio.

Emulator option in Visual studio
                                    Emulator option in Visual studio

Now you can run your application in emulator if everything works fine.

Windows emulator output
                        Windows emulator output

I guess we are done. Hope you enjoyed reading. I will see you soon with another article.

Conclusion

Did I miss anything that you may think is needed? Did you try Azure yet? Have you ever created any mobile apps? Did you find this post  useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.