Udostępnij za pośrednictwem


Quickstart: Add a mobile service to a Universal Windows App

[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 Universal Windows 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).

Prerequisites

Download and run the GetStartedWithData Mobile Services project

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

  1. Download the GetStartedWithData sample app project. Choose the C# 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.cs file in the shared project. 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. Close the app 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 an 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 Windows Store 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 providing your credentials in 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. If you chose a .NET backend service, Visual Studio creates a new mobile service project and adds it to your solution.

  7. In Solution Explorer, in the shared project, 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:

    #if WINDOWS_APP
    // https://go.microsoft.com/fwlink/?LinkId=290986@clcid=0x409
    public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient 
        todolistClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "https://todolist.azure-mobile.net/",
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    #endif
    

    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.

  8. For the Windows Phone project, use Add, Connected Service to bring up the Services Manager dialog box as you did for the Windows Store project, but instead of creating a new service, choose the service you just created.

    Visual Studio adds code to client a mobile service client to App.xaml.cs in the shared project, similar to the code it added for the Windows Store project.

  9. Visual Studio added another instance of the mobile service client initialization, this time surrounded by #if WINDOWS_PHONE_APP. Delete one of the entries, and delete the preprocessor directives, so the final code looks like this, with your application key instead of the X's.

    // https://go.microsoft.com/fwlink/?LinkId=290986@clcid=0x409
    public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient 
        todolistClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "https://todolist.azure-mobile.net/",
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    

Examine the mobile service project

  1. Examine your solution in Solution Explorer. When you created the mobile service, Visual Studio added a project 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.

  2. 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. 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; }
        }
    }
    

    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.

  3. 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)
            {
                base.Initialize(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);
            }
        }
    }
    

    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.

    Mobile services data tables use a standard primary key named id for each table, with type string and GUIDs as values. This matches the name and type of the parameter in the controller methods. You can't change the type or name of the id parameter without breaking the code.

  4. (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. (Optional) 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 to the Preview page. 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.

     

  10. On the welcome page, choose the try it out link. When prompted, type any text for the username (the username text is ignored), and copy the application key from App.xaml.cs or from the portal for the password. In the portal, to get the application key, choose your mobile service, choose the Manage Keys button at the bottom of the screen, and choose the copy icon next to the Application Key field in the dialog box that appears. Note: You can also use the master key from the same dialog in 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. In the shared project, open MainPage.cs, and uncomment the following using statements:

    using Microsoft.WindowsAzure.MobileServices;
    
  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; }
    }
    

    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 IMobileServiceTable<TodoItem> todoTable = App.yourClient.GetTable<TodoItem>();
    private MobileServiceCollection<TodoItem, TodoItem> items;
    
    

    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);
    

    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();
    

    This sets the binding to the collection of items in the todoTable, which contains all of the TodoItem objects returned from the mobile service. Note that ToCollectionAsync returns only the first 50 items since it returns only the first page of data.

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

    await todoTable.UpdateAsync(item);
    

    This sends an item update to the mobile service.

Test the Windows Store client with your new mobile service

Now that the app has been updated to use Mobile Services as a mobile backend, 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.

Test the Windows Phone client with the mobile service

For this procedure you need a Windows Phone emulator on your development computer. You can also register your Windows Phone for development, so you can test your app on a real phone.

  1. Right-click the Windows Phone project and choose Set As Startup Project.

  2. Using the start button on the Visual Studio toolbar, choose the emulator you want to use, and launch the app.

  3. If the emulator is not installed, you are prompted to install it.

  4. When the app appears in the emulator, enter some text for a ToDo item, and choose the Save button.

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 pressing the F9 key, or right-click and choose Set Breakpoint.

  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. Start the app on the local machine. The first time you run the app, start it from Visual Studio so that it deploys. Thereafter, you can use the Start button or Windows key to bring up the Start Screen, and type in the name of the app.

  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)