Share via


Quickstart: Adding a mobile service (JavaScript)

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.

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 Microsoft 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 sample app project.
  2. In Visual Studio, open the downloaded project, expand the js folder, then examine the default.js script file. Notice that added TodoItem objects are stored in an in-memory List, 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 into Visual 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 Microsoft Azure Subscriptions, click Download subscription file, login to your Microsoft 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, expand services, mobile services, your service name, then open the service.js file and notice the newly added variable, which looks like the following example:

    var todolistClient = new WindowsAzure.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 object. The client is created by supplying the URI and the application key of the new mobile service.

  7. Open the default.html file and notice that two new script references have been added, one to the Mobile Services client library in Azure and one to the script that defines the MobileServiceClient object in your project.

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 Azure, expand Mobile Services, 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 default.js script file, comment the line that defines the existing items collection, then uncomment or add the following line of code and replace yourClient with the variable added to the service.js file when you connected your project to the mobile service:

    var todoTable = yourClient.getTable('TodoItem');
    

    This code creates a proxy object (todoTable) for the new database table.

  4. Replace the InsertTodoItem function with the following code:

    var insertTodoItem = function (todoItem) {
        // Inserts a new row into the database. When the operation completes
        // and Mobile Services has assigned an id, the item is added to the binding list.
        todoTable.insert(todoItem).done(function (item) {
            todoItems.push(item);
        });
    };
    

    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. Replace the RefreshTodoItems function with the following code:

    var refreshTodoItems = function () {
        // This code refreshes the entries in the list by querying the table. 
        todoTable.read().done(function (results) {
            todoItems = new WinJS.Binding.List(results);
            listItems.winControl.itemDataSource = todoItems.dataSource;
        });
    };
    

    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. Replace the UpdateCheckedTodoItem function with the following code:

    var updateCheckedTodoItem = function (todoItem) {
        // This code takes a freshly completed TodoItem and updates the database. 
        todoTable.update(todoItem);
    };
    

    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.

Modify the query to filter out completed items

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

  1. In the default.js script file, replace the existing RefreshTodoItems method with the following code that filters out completed items:

    var refreshTodoItems = function () {
        // More advanced query that filters out completed items. 
        todoTable.where({ complete: false })
            .read()
            .done(function (results) {
                todoItems = new WinJS.Binding.List(results);
                listItems.winControl.itemDataSource = todoItems.dataSource;
            });
    };
    
  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 Windows Store app.

Next, you'll learn how to use Mobile Services to add push notification functionality to your Windows Store 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