Compartir a través de


Quickstart: Adding a mobile service (JavaScript 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 applies to mobile services that use the JavaScript backend. If you are using the .NET backend, see Quickstart: Add a mobile service (.NET backend).

Prerequisites

  • Microsoft Visual Studio 2013**.
  • Active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.
  • GetStartedWithMobileServices project. This is a Windows Store app project that will be enabled to use Mobile Services.

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.
  2. In Visual Studio, open the downloaded project and examine 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.
  3. 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.

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 import the publishsettings file from your Azure subscription intoVisual 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. InVisual Studio 2013, open Solution Explorer, right-click the project then click Add Connected Service....

  2. In the Services Manager dialog, click Create service..., then select <Import...> from Subscription in the Create Mobile Service dialog.

  3. In Import Azure Subscriptions, click Download subscription file, login to your Azure account (if required), click Save when your browser requests to save the file.

    Note  The login window is displayed in the browser, which may be behind your Visual Studio window. Remember to make a note of where you saved the downloaded .publishsettings file. You can skip this step if your project is already connected to your Azure subscription.

     

  4. Click Browse, navigate to the location where you saved the .publishsettings file, select the file, then click Open and then Import. Visual Studio imports the data needed to connect to your Azure subscription. When your subscription already has one or more existing mobile services, the service names are displayed.

    Note  After importing the publish settings, consider deleting the downloaded .publishsettings file as it contains information that can be used by others to access your account. Secure the file if you plan to keep it for use in other connected app projects.

     

  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 when the name is not available. 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.

     

    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.

  6. 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:

    public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient 
        todolistClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "https://todolist.azure-mobile.net/",
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    
    Public Shared todolistClient _
            As New Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
        "https://todolist.azure-mobile.net/",
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    

    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 new table to the mobile service and update the app

Before you can store data in your new mobile service, you must create a new storage table in the service. These steps show how to use Visual Studio 2013 to create a new table in the mobile service. Then you update the app to use Mobile Services to store items in Azure instead of in the local collection.

  1. In Server Explorer, expand the Azure node, expand the Mobile Services node, right-click your mobile service, then click Create Table. In the Create Table dialog, and type TodoItem in Table Name.

  2. Expand Advanced, verify that the table operation permissions default to Anybody with the Application Key, then click Create. This creates the TodoItem table on the server, where anyone that has the application key can access and change data in the table without having to first be authenticated.

    Note  The application key is distributed with the application. Because this key is not securely distributed, it cannot be considered a security token. To secure access to your mobile service data, you must instead authenticate users before accessing. For more information, see Permissions.

     

  3. In the file MainPage.xaml.cs, add or uncomment the following using statements:

    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json;
    
    Imports Microsoft.WindowsAzure.MobileServices
    Imports Newtonsoft.Json
    
  4. In this same file, replace the TodoItem class definition with the following code:

    public class TodoItem
    {
        public string 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 String
    
        <JsonProperty(PropertyName:="text")>
        Public Property Text As String
    
        <JsonProperty(PropertyName:="complete")>
        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.

  5. 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 = 
        App.yourClient.GetTable<TodoItem>();
    
    
    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).

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

     

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

  8. 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)
           .ToCollectionAsync();
    
        ListItems.ItemsSource = items;
    }
    
    Private Async Sub RefreshTodoItems()
       items = Await todoTable _
           .Where(Function(todoItem) todoItem.Complete = False) _
           .ToCollectionAsync()
    
        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.

Summary and next steps

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

Next, you'll learn how to use Mobile Services to add push notification functionality to your app: Quickstart: Adding push notifications for a mobile service.

Validate and modify data in Mobile Services by using server scripts

Refine Mobile Services queries with paging