Quickstart: Add a mobile service (.NET backend)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This Quickstart walks you through adding a cloud-based backend service to an existing app using Azure Mobile Services. Mobile Services makes it easy to store and query for data, login users with popular identity providers, and send and receive push notifications in your app. To learn more, see the Mobile Services dev center. When you are done, you will have created a new mobile service in your Azure subscription, added Mobile Services code to the starter app project, and run the app to insert data into the new mobile service.

This Quickstart demonstrates creating a mobile service with a .NET backend. You can also create a mobile service with a JavaScript backend. See Quickstart: Add a mobile service (JavaScript backend).

If you have a Universal Windows App, see Quickstart: Add a mobile service to a Universal Windows App.


Download and run the GetStartedWithMobile Services project

First, you will download and test out a Visual Studio 2013 project for a Windows Store app to which Mobile Services support will be added. This starter app stores items in memory.

  1. Download the GetStartedWithMobileServices sample app project. Choose the C# or Visual Basic version.
  2. In Visual Studio, open the downloaded project. If this is the first time you've created or opened a Windows Store project, you'll be asked to register for a developer license for Windows 8.1.
  3. Open the MainPage.xaml.cs file. Notice that added TodoItem objects are stored in an in-memory ObservableCollection, then press the F5 key to rebuild the project and start the app.
  4. In the app, type some text in Insert a TodoItem, then click Save. Notice that the saved text is displayed in the second column under Query and update data.
  5. Move the pointer to the top right of the screen, or use ALT+TAB, to return to Visual Studio and stop the debugger.

Create a new mobile service

The following steps create a new mobile service in Azure and add code to your project that enables access to this new service. Before you can create the mobile service, you must connect to your Azure subscription inVisual Studio. This enables Visual Studio to connect to Azure on your behalf. When you create a new mobile service, you must specify a Azure SQL Database that is used by the mobile service to store app data.

  1. (Optional) In Visual Studio 2013, open Server Explorer and on the shortcut menu for the Azure node, choose Connect to Microsoft Azure....

  2. Sign in to your Azure subscription using the same Microsoft Account that you use to sign in to the Azure management portal.

  3. Open Solution Explorer, right-click the project, and then click Add > Connected Service....

    The Services Manager dialog box appears.

  4. If you didn't sign in through Server Explorer, you can sign in by clicking on the Manage subscriptions link, and signing in from the Manage Subscriptions dialog.

  5. Click Create service..., then in the Create Mobile Service dialog, select your Subscription and the desired Region for your mobile service. Type a Name for your mobile service and make sure that name is available. A red X is displayed if the name is not available. For the mobile services runtime, choose .NET Framework to create a mobile service with a .NET backend. In Database, select <Create New>, supply the Server user name and Server password, then click Create.

    Note  As part of this Quickstart, you create a new SQL Database instance and server. You can reuse this new database and administer it as you would any other SQL Database instance. If you already have a database in the same region as the new mobile service, you can instead choose the existing database. When you choose an existing database, make sure that you supply correct login credentials. If you supply incorrect login credentials, the mobile service is created in an unhealthy state.


  6. In the Services Manager dialog box, select the service you just created, and choose the OK button.

    After the mobile service is created, a reference to the Mobile Services client library is added to the project and your project source code is updated.

  7. In Solution Explorer, open the App.xaml.cs code file, and notice the new static field that was added to the App class, which looks like the following example, with the name you chose for your mobile service instead of todolist in the URL:

    public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient 
        todolistClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
    Public Shared todolistClient _
            As New Microsoft.WindowsAzure.MobileServices.MobileServiceClient(

    This code provides access to your new mobile service in your app by using an instance of the MobileServiceClient class. The client is created by supplying the URI and the application key of the new mobile service. This static field is available to all pages in your app.

Add a mobile service project

When you follow the steps in the previous project to create a mobile service, the mobile service project is created for you, so you can skip this step. When you want to create a mobile service without creating a client project, start here and continue with the rest of the walkthrough.

  1. In Solution Explorer, open the shortcut menu on the solution node and choose Add > New Project, and choose a Visual Basic or C# Cloud project, Azure Mobile Service.

  2. In the New ASP.NET Project dialog box, choose Azure Mobile Service.

    If you haven't already, you can create a mobile service in Azure by choosing the Host in the Cloud checkbox. There's no need to do this if you are creating a mobile service project for a service that you already created in Azure. If you don't create a mobile service in Azure now, you can create one later when you publish your mobile service project in Step 5.

    A project is added to the solution for the .NET backend for a mobile service. This project is a specially configured Web API project that's designed to provide the backend for mobile services. Web API provides support for developing web services. See ASP.NET Web API.

  3. Examine the project that got created. The default template contains starter code for the TodoItem mobile service. In the DataObjects folder, open the item TodoItem.cs or TodoItem.vb. It looks like this:

    using Microsoft.WindowsAzure.Mobile.Service;
    namespace TodoListMobileService.DataObjects
        public class TodoItem : EntityData
            public String Text { get; set; }
            public bool Complete { get; set; }
    Imports Microsoft.WindowsAzure.Mobile.Service
    Public Class TodoItem
        Inherits EntityData
        Public Property Text As String
        Public Property Complete As Boolean
    End Class

    TodoItem represents the data type and maps onto a single database table. The class inherits from EntityData, which means this data object maps onto a mobile service table and can be used as a template type with the table controller, TableController<TEntityData>. Entity Framework is a powerful data access library that promotes code-first data development. See Entity Framework. It works well with Web API and is the default data access framework for mobile services with a .NET backend.

  4. In the Controllers node, open the file TodoItemController.cs or TodoItemController.vb. The code looks like the following.

    using System.Linq;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.OData;
    using Microsoft.WindowsAzure.Mobile.Service;
    using TodoListMobileService.DataObjects;
    using TodoListMobileService.Models;
    namespace TodoListMobileService.Controllers
        public class TodoItemController : TableController<TodoItem>
            protected override void Initialize(HttpControllerContext controllerContext)
                TodoListMobileServiceContext context = new TodoListMobileServiceContext(Services.Settings.Schema);
                DomainManager = new EntityDomainManager<TodoItem>(context, Request, Services);
            // GET tables/TodoItem
            public IQueryable<TodoItem> GetAllTodoItems()
                return Query();
            // GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
            public SingleResult<TodoItem> GetTodoItem(string id)
                return Lookup(id);
            // PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
            public Task<TodoItem> PatchTodoItem(string id, Delta<TodoItem> patch)
                return UpdateAsync(id, patch);
            // POST tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
            public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
                TodoItem current = await InsertAsync(item);
                return CreatedAtRoute("Tables", new { id = current.Id }, current);
            // DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
            public Task DeleteTodoItem(string id)
                return DeleteAsync(id);
    Imports System.Linq
    Imports System.Threading.Tasks
    Imports System.Web.Http
    Imports System.Web.Http.Controllers
    Imports System.Web.Http.OData
    Imports Microsoft.WindowsAzure.Mobile.Service
    Public Class TodoItemController
        Inherits TableController(Of TodoItem)
        Protected Overrides Sub Initialize(ByVal controllerContext As HttpControllerContext)
            Dim context As MobileService2Context = New MobileService2Context(Services.Settings.Schema)
            DomainManager = New EntityDomainManager(Of TodoItem)(context, Request, Services)
        End Sub
        ' GET tables/TodoItem
        Public Function GetAllTodoItems() As IQueryable(Of TodoItem)
            Return Query()
        End Function
        ' GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        Public Function GetTodoItem(ByVal id As String) As SingleResult(Of TodoItem)
            Return Lookup(id)
        End Function
        ' PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        Public Function PatchTodoItem(ByVal id As String, ByVal patch As Delta(Of TodoItem)) As Task(Of TodoItem)
            Return UpdateAsync(id, patch)
        End Function
        ' POST tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        Public Async Function PostTodoItem(ByVal item As TodoItem) As Task(Of IHttpActionResult)
            Dim current As TodoItem = Await InsertAsync(item)
            Return CreatedAtRoute("Tables", New With {.id = current.Id}, current)
        End Function
        ' DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        Public Function DeleteTodoItem(ByVal id As String) As Task
            Return DeleteAsync(id)
        End Function
    End Class

    The TodoItemController class is a Web API controller. It's a special kind of Web API controller, since it inherits from TableController, which is designed to work with mobile services tables. The class contains methods that implement a REST api which your mobile service clients call to create, update, read, or delete data. REST is a preferred design pattern for web services and is the design pattern used by mobile services table controllers. The comment lines indicate the type of HTTP requests that this Web API accepts, all of which are standard to a REST API. The class also contains an Initialize method that sets up some context objects and creates the entity domain manager for Entity Framework.

  5. (Optional) Open the TodoListMobileServiceContext class in the Models folder. This is a class that is required to enable Entity Framework. You won't need to modify this class in this tutorial. You can have at most one data context class in each mobile service.

Test the mobile service by running it on the local machine

Now that you've created a mobile service project, test it on the local machine to make sure it works. When testing, you'll be using the mobile service like a standard Web API web service that takes HTTP requests.

  1. In Solution Explorer, select the mobile service project node that you just created, open its shortcut menu, and choose Set As Startup Project.

  2. Press F5, or choose Start with Debugging from the Debug menu. The mobile service starts in the local IIS or IIS Express web server, and a welcome page appears.

  3. On the welcome page, choose Try it out. A list of available web methods appears.

  4. Choose the POST method on the TodoList controller. A page appears that allows you to compose a POST request over HTTP to your web service.

  5. Enter text to post, and submit. When the service processes the POST, it triggers Entity Framework to create a database and a table from the TodoList DataObject class.

  6. In Server Explorer, choose Add Database Connection, and specify (localdb)\v11.0 as the server. Choose the database that just got created from the list of databases, choose OK, and expand the tables node to see the data tables.

    You can edit your data, but you shouldn't change the schema of a table through the database tools .

Publish the mobile service to Azure

The mobile service works on the local machine. Now publish it to Azure.

  1. In Solution Explorer, select the solution node, open its shortcut menu, and choose Publish, and then choose the Azure Mobile Services option.

  2. If you haven't already signed in, provide the credentials for your Azure subscription.

  3. Choose your mobile service from the dropdown list in the Select Existing Mobile Service dialog box.

  4. Visual Studio sets the default values for the text fields in the wizard based on the mobile service that you created. These values are saved as part of a publish profile. You can change them later, for example to publish to a different mobile service in Azure.

  5. Choose the Validate Connection button. If the connection succeeds, a green checkmark appears.

  6. Choose the Configuration you want to publish.

    If you plan on using remote debugging, choose a Debug configuration.

  7. If the mobile service you are publishing already exists, be sure to expand the File Publish Options link and make sure the Remove additional files at destination checkbox is selected.

  8. Choose the Next button to advance through the next few pages until the Preview page appears. If you want, you can choose the Start Preview button to see the files that Web Deploy will publish to Azure.

  9. Choose the Publish button. The Output window shows the progress of the publishing process. When it's finished, your mobile service is published in Azure, and a browser window appears with a welcome page for your mobile service.

    Tip  When you publish a mobile service project, the browser opens with the same welcome page that appears when you start the mobile service project on your local machine. However, for security reasons, the pages that appear when you choose thetry it out link are not accessible when you access your mobile service in Azure.


  10. On the welcome page, choose the try it out link. When prompted, type any text for the username, and copy the application key from App.xaml.cs or from the portal for the password. Note: You can also use the master key from the management portal.

Update the client app with the data object

Before you can use your mobile service, update the client app by adding a data object class to represent the data it gets from the service. In the sample code you downloaded, the code you would normally write is commented out, so in the next steps, you'll follow TODO comments in the sample source and uncomment the code that you'd normally add to a client app.

  1. Open MainPage.xaml.cs, and uncomment the following using statements:

    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json;
    Imports Microsoft.WindowsAzure.MobileServices
    Imports Newtonsoft.Json
  2. In this same file, uncomment lines in the TodoItem class definition:

    public class TodoItem
        public int Id { get; set; }
        [JsonProperty(PropertyName = "text")]
        public string Text { get; set; }
        [JsonProperty(PropertyName = "complete")] 
        public bool Complete { get; set; }
    Public Class TodoItem
        Public Property Id As Integer
        Public Property Text As String
        Public Property Complete As Boolean
    End Class

    The JsonPropertyAttribute is used to define the mapping between property names in the client type to column names in the underlying data table.

  3. Comment the line that defines the existing items collection, then uncomment or add the following lines and replace yourClient with the MobileServiceClient field added to the App.xaml.cs file when you connected your project to the mobile service:

    private MobileServiceCollection<TodoItem, TodoItem> items;
    private IMobileServiceTable<TodoItem> todoTable = 
    Private items As MobileServiceCollection(Of TodoItem, TodoItem)
    Private todoTable As IMobileServiceTable(Of TodoItem) = _
        App.yourClient.GetTable(Of TodoItem)()

    This code creates a mobile services-aware binding collection (items) and a proxy class for the database table (todoTable).

  4. In the InsertTodoItem method, remove the line of code that sets the TodoItem.Id property, add the async modifier to the method, and uncomment the following line of code:

    await todoTable.InsertAsync(todoItem);
    Await todoTable.InsertAsync(todoItem)

    This code inserts a new item into the table.

    Note  New tables are created with only an Id column. When dynamic schema is enabled, Mobile Services automatically generates new columns based on the JSON object in the insert or update request. For more information, see Dynamic schema.


  5. In the RefreshTodoItems method, add the async modifier to the method, then uncomment the following line of code:

    items = await todoTable.ToCollectionAsync();
    items = Await todoTable.ToCollectionAsync()

    This sets the binding to the collection of items in the todoTable, which contains all of the TodoItem objects returned from the mobile service.

  6. In the UpdateCheckedTodoItem method, add the async modifier to the method, and uncomment the following line of code:

    await todoTable.UpdateAsync(item);
    Await todoTable.UpdateAsync(item)

    This sends an item update to the mobile service.

Test the app against your new mobile service

Now that the app has been updated to use Mobile Services for backend storage, it's time to test the app against Mobile Services.

  1. In Visual Studio, press the F5 key to run the app.
  2. As before, type text in Insert a TodoItem, and then click Save. This sends a new item as an insert to the mobile service, and the item is added to the collection.
  3. Shut down and then restart the app. Notice that the added data is displayed, having been persisted and then reloaded from the mobile service.

Now that the app is storing data in Azure, let's modify the query to filter out completed items from the results.

Modify the query to filter out completed items

  1. In the MainPage.xaml.cs project file, replace the existing RefreshTodoItems method with the following code that filters out completed items:

    private async void RefreshTodoItems()
        // This query filters out completed TodoItems. 
        items = await todoTable
           .Where(todoItem => todoItem.Complete == false)
        ListItems.ItemsSource = items;
    Private Async Sub RefreshTodoItems()
       items = Await todoTable _
           .Where(Function(todoItem) todoItem.Complete = False) _
        ListItems.ItemsSource = items
    End Sub
  2. Restart the app, check another one of the items in the list and then click the Refresh button. Notice that the checked item now disappears from the list. Each refresh results in a round-trip to the mobile service, which now returns filtered data.

Debug the mobile service in Azure

You can attach the Visual Studio debugger to the mobile service to debug it in Azure.

  1. Make sure that you published a Debug configuration of the mobile service. If not, republish the mobile service according to the instructions in Step 5.

  2. Set a breakpoint in a mobile service controller, such as the PostTodoItem method by selecting a line of code in the method, and choosing the F9 key.

  3. In Server Explorer, open the shortcut menu for the mobile service, and choose Attach Debugger.

    The mobile service home page opens in a browser window.

  4. Use the Start button or Windows key to bring up the Start Screen, and type in the name of the app, GetStartedWithMobileServices. The app launches.

  5. Insert an item into the todoList, and use ALT+TAB to return to Visual Studio. Visual Studio stops with the instruction pointer positioned at your break point.

Summary and next steps

Now you know how to use Mobile Services to add remote data storage capabilities to an existing app.

Next, learn how to use Mobile Services to extend the database: How to use controllers to access data (.NET backend). Or, learn how to add custom APIs and scheduled jobs: How to create custom APIs and scheduled jobs (.NET backend).

Quickstart: Add a mobile service (JavaScript backend)

Get started with data (.NET backend)

Quickstart: Add push notifications (.NET backend)