Quickstart: Working with mobile services in Visual Studio (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]

You can more easily build connected Windows Store and Windows Phone apps by using tools for tAzure Mobile Services in Microsoft Visual Studio 2013. For example, you can use Visual Studio tools to connect to a mobile service, edit the scripts for your mobile services that customize their behavior, and add push notifications to your app.

In this quickstart, you'll create a sample app that's named Photo Liker. In this app, users can like a photo and receive a push notification whenever another user likes a photo that they uploaded.

This topic shows how to work with mobile services with a JavaScript backend. If you want to create a mobile service with a .NET backend, see Quickstart: Add a mobile service (.NET backend) and related topics.

Prerequisites

  • Visual Studio 2013
  • An Azure subscription. 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.
  • A Windows Store developer account. See Become a Windows Store developer.

In Visual Studio, create a Windows Store project in C# with the Blank App (XAML) template, and name the project PhotoLiker.

Add a Connected Service Reference

  1. Right-click your project, and then choose Add Connected Service.

    The Services Manager appears.

  2. Click the Import subscriptions link to download your subscriptions from the Azure Management Portal.

    The Import Microsoft Azure Subscriptions dialog box appears.

  3. Click the Download subscription file link, and then follow the download instructions on the window that appears.

  4. After you download your subscription file, specify its location, and then click Import.

    You can now view all your services.

  5. To create a mobile service, click the Create Service link.

    The Create Mobile Service dialog box appears.

  6. Give your new service a unique name, choose a region, create a database or choose an existing one, enter a user name and a password, and then click Create.

    After a short delay, your service is ready to be consumed.

  7. Now that you’ve created a service, click it in the list of services, and then click OK.

    Visual Studio adds a reference to the Mobile Services SDK in your project and adds a MobileServicesClient object (as a code snippet) to your App.xaml.cs file. The MobileServicesClient is initialized with both your application url and your application key. You don’t need to leave Visual Studio or go to the management portal.

      public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient PhotoLikerClient =
          new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "https://photoliker.azure-mobile.net/",
            "<-- application key --->");
    

    You should never share or publish your application key.

  8. To use the MobileServiceClient object, simply enter App.NameOfMobileServiceClient. For example, you can insert a photo object into the PhotosTable of the PhotoLiker app and then do the following: (You'll create the PhotosTable in the next section.)

       async private void UploadNewPhoto() {
                var photo = new JObject();
                photo.Add("fileName", "kittens.jpg");
                photo.Add("imageSize", "2MB");
                try
                {
                    await App.PhotoLikerClient.GetTable("PhotosTable").InsertAsync(photo);
    
                }
                catch (Exception exception) 
                {
                    HandleInsertChannelException(exception); 
                }
    
            }
    

    You’re now all set to start using your mobile service in your Windows Store app! See Getting started with data and Getting started with authentication.

Azure Mobile Services in Server Explorer

In Server Explorer, you can view your existing mobile services, tables, and their scripts. In addition, you can also create services and tables and, most importantly, edit your table scripts. Because you can perform all these tasks in Server Explorer, you don’t need to switch between Visual Studio and the management portal.

  1. To create a table, right-click a service, and then click Create Table.

    If you expand the Advanced section, you can control permissions for insert, update, delete, and read operations in your table. The default value is Anybody with the application key.

  2. To edit your table scripts, open Server Explorer, expand your table, and double-click a script (for example, read.js).

    Script contents are retrieved from Azure and appear in a JavaScript editor window.

  3. Make your edits, and then choose Save.

  4. To troubleshoot your mobile service, click it, and then choose Browse to Portal.

    The management portal opens in your default browser so that you can navigate to the dashboard of your mobile service.

  5. Click Logs, or choose a table from the dashboard.

    To view table data within Visual Studio, you can use SQL Server Object Explorer.

Push Notifications

Push notifications can be a powerful tool for informing users of changes in their data. The Push Notification Wizard guides you through all of the steps that you must complete to enable your mobile service to send push notifications (tiles, toasts, and badges) to your app.

  1. In Solution Explorer, right-click your project, point to Add, and then click Push Notification.

  2. Click Next to advance past the first screen of the wizard, which describes what the wizard will do.

  3. On the next screen, click the name of the app to which you want to add notifications.

  4. Click Next, and then sign in to your Windows Store developer account so that you can associate your app with the Windows Store.

    An app signs up to get push notifications by requesting a channel in the Windows Notification Service (WNS). Notifications to that channel must be authenticated, and associating an app with the Windows Store generates a Package Security Identifier (SID) and a client secret, which are used to perform that authentication. The Push Notification Wizard will handle that detail, but you must provide your Store association to make everything work. See Push Notification Overview.

  5. In the Select an app name dialog box, click an app in the list, and then click Next.

    The Services Manager shows only the Azure Mobile Services node.

  6. Choose the mobile service that will send push notifications to your app.

    If you haven’t used the Services Manager yet, see the previous sections for how to import Azure credentials and create services from it. If you’ve already used the Services Manager with a specific service, you can choose it again.

  7. Click Next, and then finish the wizard.

    The wizard makes several modifications to your project.

  8. Before you look at all the details, launch the app (Ctrl+F5), and wait for just a second.

    If a toast notification for your app ("Sample toast from sample insert") appears, you've succeeded! Otherwise, a message appears in the General section of the Output window, and you can use that message to figure out what went wrong.

What does the Push Notification Wizard actually do? First, it associates your app with the app name that you specified. (Like the Packaging Wizard, if your app was already associated, your app isn't modified. See Packaging your Windows Store app.)

Next, the Push Notification Wizard modifies your project in the same way that the Services Manager does for a specific mobile service—it adds the SDK reference and adds a MobileServicesClient object to your App.xaml.cs file with your application url and application key.

In addition, the wizard adds code to your project. Specifically, the wizard creates a class that's named PhotoLikerPush in the file services/mobile services/PhotoLiker/push.register.cs, with one main function, which is named UploadChannel:

        public async static void UploadChannel()
        {
            var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.
                CreatePushNotificationChannelForApplicationAsync();

            var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
            string installationId = Windows.Security.Cryptography.CryptographicBuffer.
                EncodeToBase64String(token.Id);

            var ch = new JObject();
            ch.Add("channelUri", channel.Uri);
            ch.Add("installationId", installationId);

            try
            {
                await App.PhotoLikerClient.GetTable("channels").InsertAsync(ch);
            }
            catch (Exception exception)
            {
                HandleInsertChannelException(exception);
            }
        }

This code pulls together a WNS channel URI and a hardware identifier that's specific to the current app package. Then the code uses the PhotoLikerClient to upload these two strings to the channels table in the PhotoLiker mobile service. The PhotoLiker mobile service will need this data to send push notifications to this app.

Meanwhile, the following code appears at the end of the OnLaunched function in App.xaml.cs:

PhotoLiker.<mobile service name>Push.UploadChannel();

The code in push.register.cs will run every time that the app is launched.

Finally, the last modification to your project is to set Toast capable in the app manifest to Yes. You can confirm this if you locate the Application UI section in the app manifest designer and then locate the Badge Logo subsection. This value tells Windows that this app should receive toast notifications.

On the server, the channels table is created, which appears in Server Explorer. The insert.js script is interesting:

function insert(item, user, request) {

    sendNotifications(item.channelUri);

    var ct = tables.getTable("channels");
    ct.where({ installationId: item.installationId }).read({
        success: function (results) {
            if (results.length > 0) {
                // we already have a record for this user/installation id - if the 
                // channel is different, update it otherwise just respond
                var existingItem = results[0];
                if (existingItem.channelUri !== item.channelUri) {
                    existingItem.channelUri = item.channelUri;
                    ct.update(existingItem, {
                        success: function () {
                            request.respond(200, existingItem);
                        }
                    });
                }
                else {
                    // no change necessary, just respond
                    request.respond(200, existingItem);
                }
            }
            else {
                // no matching installation, insert the record
                request.execute();
            }
        }
    })

    function sendNotifications(uri) {
        console.log("Uri: ", uri);
        push.wns.sendToastText01(uri, {
            text1: "Sample toast from sample insert"
        }, {
            success: function (pushResponse) {
                console.log("Sent push:", pushResponse);
            }
        });
    }

When a request arrives, the script first uses the push.wns.sendToastText01 API to send a toast notification to the channel URI that was passed in with the request. This is why a toast notification appears as soon as you launch the app. Then, the script inserts the channel URI and hardware ID into the table, after confirming that it won't duplicate existing data. This data isn't used right now, but later in this topic, you'll discover how to use this data to send more push notifications.

Finally, the Push Notification Wizard also takes care of one last detail. Messages that go through WNS must be authenticated with the Package SID and the client secret. The wizard takes these values from the Windows Store and uploads them to the PhotoLiker mobile service. If you go to the management portal and check the Push section of the PhotoLiker mobile service, you can verify that the client secret and Package SID fields are filled out correctly.

In addition to passing your client secret and Package SID to your mobile service, the Push Notification Wizard also sets your app's redirect domain to the mobile service that you chose. If you go to the Live connect portal and look at the configuration for your Store app, you’ll see that the redirect domain is set to “https://photoliker.azure-mobile.net”. This is required to use Live Connect from your mobile service. See redirect domain.

That should give you an understanding of the Push Notification Wizard, but this isn’t completely realistic yet—you aren’t often going to want a push notification sent to your app as soon as it starts up. With just a bit more work, you can make a relatively realistic scenario work.

  1. First, copy the following code into MainPage.xaml. This creates a couple of XAML text boxes and buttons with Click event handlers:

            <StackPanel Orientation="Vertical">
                <StackPanel Orientation="Horizontal">
                    <TextBox x:Name="filenameBox" Text="cats.jpg" Width="300" />
                    <Button Content="Upload new photo" Click="UploadNewPhoto" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBox x:Name="likePhotoBox" Text="cats.jpg" Width="300" />
                    <Button Content="Like a photo" Click="LikePhoto" />
                </StackPanel>
            </StackPanel>
    
  2. The first text box/button combination pretends to upload a photo. UploadNewPhoto is somewhat like the code in push.register.cs:

            async private void UploadNewPhoto(object sender, RoutedEventArgs e)
            {
                var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
                var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
                string installationId = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(token.Id);
    
                var ch = new JObject();
                ch.Add("channelUri", channel.Uri);
                ch.Add("installationId", installationId);
                ch.Add("filename", filenameBox.Text);
    
                try
                {
                    await App.PhotoLikerClient.GetTable("channels").InsertAsync(ch);
                }
                catch (Exception exception)
                {
                    HandleInsertChannelException(exception);
                }
            }
    
  3. At this point, you’ve copied over the code from push.register.cs and added the highlighted line to add the filename of the photo that you’re pretending to upload. Because you’re registering and uploading your channel here and associating each channel with an uploaded photo, you don’t need the code in push.register.cs, and you don't want that code to run on launch. Delete push.register.cs, and remove the reference to it in the OnLaunched function in app.xaml.cs.

  4. Now, let’s add the ability to “like” these photos. First, we’ll need a table in the PhotoLiker mobile service to store the likes. Create a table called “likes” by using Server Explorer. (See the previous section for details.)

    Now, you’ll use our second text box/button combo to like photos. You can use a very similar function to uploading, except that it updates a different table and uploads only the filename:

            async private void LikePhoto(object sender, RoutedEventArgs e)
            {
                var ch = new JObject();
                ch.Add("filename", likePhotoBox.Text);
    
                try
                {
                    await App.PhotoLikerClient.GetTable("likes").InsertAsync(ch);
                }
                catch (Exception exception)
                {
                    HandleInsertChannelException(exception);
                }
            }
    
  5. The last step is to send a push notification to the user who uploaded the photo every time someone else likes their photo. Here’s the insert script for the likes table:

    function insert(item, user, request) {
        tables.getTable('likes').where({filename: item.filename})
            .read({success: function(results) {
                if (results.length > 0) {
                    results[0].likes++;
                    request.respond(statusCodes.OK, item);
                    tables.getTable('likes').update(results[0], {success: function() {
                        notifyUploader (results[0]);
                    }});
                } else {
                    item.likes = 1;
                    request.execute({success: function() {
                        notifyUploader (item);
                    }});
                    request.respond();
                }
            }});
    
        function notifyUploader(resultItem) {
            tables.getTable('channels').where({filename: resultItem.filename}).read({success: function (results) {
                if (results.length > 0) {
                    push.wns.sendToastText01(results[0].uri, {text1:
                        'Your image ' + resultItem.filename + ' was liked! You now have ' +
                        resultItem.likes + ' likes for this image!'});
                }
            }});
        }
    }
    

(If you’re not familiar with the way server scripts work, see Mobile Services server script reference.) First, this script checks whether the photo has any likes already. If it does, the script just increments the number of likes. Otherwise, the script creates an entry for that photo. Then the notifyUploader callback gets called. This function looks up the filename in the channels table, finds the channel that corresponds to that filename, and sends a toast notification. You can pretend to upload a photo called “cats.jpg”. Then, from a different computer for maximum effect, “like” that same photo. The first computer will get a toast notification that someone liked the photo!

Summary and next steps

In this quickstart, you created a mobile service to connect a Windows Store app to Azure. You then learned how to share photo data with other users and created a push notification when other users clicked a Like button on your photo.

As a next step, upload the photo to Azure storage. See Upload images to Azure storage by using Mobile Services.

For a more advanced sample app that demonstrates all of the above concepts in more depth, see Quickstart: creating a connected app with mobile services.

Connecting to mobile services

Quickstart: Add a mobile service

Quickstart: Add push notifications

How to: Create a service, table, and edit scripts