Getting Started with Azure Mobile Apps

Earlier this year I worked on an awesome project for IMSA. While the project was full of challenges such as Xamarin.Forms there was one part of the project that ran smoother than the rest. That part was our Azure Mobile Service. Since completing that project Azure has released a new product named Azure Mobile Apps which is an even more comprehensive solution for creating Web APIs for mobile apps. The new name is a bit confusing, but rest assured Azure Mobile Apps does not refer to the actual App package running on a device.

Why?

Before Azure Mobile Apps and Azure Mobile Services the work a developer had to perform to provide a simple API to their mobile app was quite extensive. Standing up a website with a RESTful API was only step 1. If you wanted to see metrics about how healthy your API was you’d have to go find a solution from another provider and integrate it manually. You’d have multiple places to manage your mobile app. Your database might have lived in Azure, but it’s wouldn’t have been related to any grouping of services. The ability to manage this world effectively became unreasonable and difficult very quickly.

Azure Mobile Apps provide all the necessary services to provide and support an API for your mobile app. It also groups all those services in one easy to manage location in the Azure Preview Portal. In my experience the provided services and grouping of those services has provided critical time saving and sanity preserving assistance compared to previous solutions. This is especially true because of the awesome integration with Visual Studio.

What does it do?

Azure Mobile Apps provide a suite of Azure services which are used for working with mobile app development and support. You can read their details here. All of the services are grouped into a single Resource Group. This organization is awesome! It helps you comprehend and manage all of the services used by your mobile app effectively. The default services included are:

  • Web App (aka: A website which hosts Web API Controllers)
  • Application Insights (For the Web App)

You can also add in any number of services into this Resource Group. For example you’ll probably add a Database Server and Database to store the data for you mobile app. Adding theses services allow you to leverage Entity Framework in your mobile app, which is a really cool feature.

How much does it cost?

It would be silly for me to try to repeat the values quoted my Microsoft since Azure changes things quite frequently. You can find the official pricing here. Everyone has a different definition of “affordable”, so I’ll only say that in our experience here at InterKnowlogy this service has been worth every penny!

How do I set it up?

Go to the Preview Portal. In the bar on the left click the “+ New” button. Select the “Web + Mobile” category. Select the Mobile App offering. Fill out all the data. I suggest creating a new Resource Group specifically named for this Mobile App. In my demo I’m creating a Secret Santa app so my Resource Group name is SecretSanta and my Web App name is SecretSantaApp.

image

Click the Create button and Azure will now create all the services mentioned before in a single Resource Group. When Azure notifies you that it’s done you’ll see something like this when you navigate to your Resource Group.

image

You can modify what level of service you want to use for your Web App. From the Resource Group blade click your Web App which is the item with the blue sphere. You’ll see a pair of blades like this:

image

On the right you’ll see Application Settings where you can modify any AppSetting or ConnectionString that is specific to this deployment in Azure. These settings persist in Azure across publishes. This means that you can have AppSettings and ConnectionsStrings for Local development that do not get used in Azure.

To change you Web App’s service plan look under the Essentials section and click the link under the header “App Service plan/pricing tier” which will open the following blade:

image

Click the “Pricing tier” block to open the “Choose your pricing tier” blade for different plan tiers.

image

In the image above you only see a few of the many options. For this demo I selected F1 Free which is a very limited plan, but it doesn’t cost anything which is nice for a demo or proof of concept. You can change your plan at any time. After selecting your desired plan click Select and your plan will be applied.

Now there is a bug in the link to Quickstart at the time of this writing. So at this point if you’re following along, close all the open blades using the ‘x’ button in the top right of the dark blue header.

Reopen your Resource Group and then open your Web App again. This time pay attention to the far right Quickstart blade which should look like this:

image

Azure has provided us with an awesome set of getting started tools for a bunch of different platforms. For the sake of this demo we’ll stick with Windows C#. Click on the Windows C# option. You should now see:

image

You’ll now notice that step 1 is to get Visual Studio 2015 installed. Microsoft offers the Community Edition straight up here in case you don’t have it yet. Step 2 allows you to download a starting point for your service in the cloud. Download this code and explore it. There is a lot going on. We will not cover the source in this demo. The source in basically a Web API project where you can add your Web API Controllers and build it out like you would any other Web API project. Lastly step 3 allows you to download an app that is ready to use with the Web API project you downloaded in step 2. This is an awesome starting point. The project in step 3 for Windows C# is a Windows 8.1 Universal App. If you want to do UWP and/or switch to another language you can do that just fine. At the top of this blade is a toggle button. Toggle it to Connect an Existing App and then follow the instructions to wire up your custom app that you created to the Mobile App service in Azure.

Finally I want to walk you through getting the Database to set up. At the top of this blade you’ll notice a message stating you need a database in order to complete the quick start. Click that banner. It will open a Data Connections blade. We’ll create a new data connection. Click the Add button. Follow the wizard to fill out all required data. Be sure to select “Create a new database” not “Use an existing database” if you want a new place to store your data. If you already have data that you will now leverage in this Mobile App then point at your existing database. Also, make sure you’re aware which pricing tier you’re selecting for your database. The default is standard which for most demos may cost too much.

image

After your database is created navigate back to your Resource Group. It should look something like this now:

image

You’ll notice the 2 new items. The Database Server ands the Database itself. Now you’re Azure Mobile App is ready for use.

Let’s run it!

You’ve downloaded both the Server and the Mobile App. Before you can use the server app you need to deploy it. The sample code you downloaded is ready for upload with all the settings matching your Mobile App settings. Azure does not auto deploy the server code for you because you will always change it for real projects. Go ahead and deploy the project. Follow the instructions in Microsoft’s Tutorial under the heading “Publish the server project to Azure.”

Limitation Notice

In order for your app to access the database using the default settings you need to modify your ConnectionString named MS_TableConnectionString to use admin credentials not user credentials. This is because Entity Framework code first requires permissions to create a schema for your database. Once the server code is deployed go back to the Azure Portal and open the Web App again. Open the Settings blade and select Application Settings. Modify your connection string MS_TableConnectionString to use admin credentials.

image

Save your changes. Then try out your API. You can try it out in the browser by hitting the URL for your Mobile App and then adding on /tables/todoitem. For example: http://secretsantaapp.azurewebsites.net/tables/todoitem. You should see JSON output similar to this:

image

Once this is working you can run the demo app that you downloaded from Azure. The first load of the app should look like this:

image

WOOT WOOT! Demo DONE! You’re now an expert!

The take away…

While it may have taken 15-30 min. to walk through this demo, after becoming familiar with the creation process Azure Mobile Apps take very little time and effort to get up and running. I’m very grateful for this solution. Here at InterKnowlogy we have used Azure Mobile Apps on many different projects in order to support mobile apps on Windows, Android, and iOS. Maintenance has been very straight forward and the flexibility is great. It feels like such a small thing, but has a profound impact on creating successful mobile app solutions. If you have any questions feel free to reach out on twitter @dannydwarren or here in the comments.

How to use PhoneGap API + WP7

How to get started?

In my previous blog posts I’ve shown how to use PhoneGap with Xcode and Eclipse in targeting iOS and Android platforms. For this blog post, I will show how to use the PhoneGap API with Visual Studio and the Windows Phone 7 emulator as your development environment.

For this sample project, we will also be using JQuery and JQuery Mobile UI.

Now to get started, PhoneGap has documentation on what tools to download and what steps to follow. After you have your development environment setup, you can look over PhoneGap’s API documentation. The API is not to cumbersome and is straight-forward in following for each of the different device hardware. Most of the API involvrs javascript callbacks as I will show below in example code.

For this blog post, I will discuss how to use the following:
1. Device
2. Accelerometer
3. Camera
4. Geolocation
5. Notification

Most of the API methods and objects will exist on most of the major platforms (iOS, Android, WP7). However, some things will be specific on some platforms. Android and WP7 has a search and back button but iOS doesn’t. The menu button only exists on Android. In general, you should be able to use the PhoneGap universally on all platforms. But its good practice to test and run on each device to make sure it works they way you expect.

The sample project was developed fully in Visual Studio and tested with the Windows Phone 7 emulator. The 5 device hardware features that I will interact with using the PhoneGap API is shown on their own phone screen. The examples are very simple to explain how to use the PhoneGap API.

Below is a screen shot of the sample project’s Solution Explorer in Visual Studio. Notice the “www” folder. This folder is created with the PhoneGap project template and where all your web files (HTML, CSS, JavaScript, etc) exist.

Solution Explorer

Before we dive into the API code for each phone screen, I want to mention when using the PhoneGap API you should place your javascript code inside the javascript event OnDeviceReady. If you place your javascript code that calls the PhoneGap API in here, you can guarantee the device is loaded and ready to interact with. Below is the code included in the index.html file.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing! 
        function onDeviceReady() 
        {

        }
        </script>

Now lets dive into example code.

Device – Gather device specific information

The HTML and jQuery Mobile UI for the Device screen.

<body>
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>Device</h1>
            <a href="#accelerometerpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Device API
            <!--<a href="#newpage" data-role="button">Second Page</a>
            <br/>-->
            <p id="devicename"></p>
            <p id="devicephonegap"></p>
            <p id="deviceplatform"></p>
            <p id="deviceuuid"></p>
            <p id="deviceversion"></p>
        </div>
    </div>
</body>

The jquery code inside onDeviceReady. The device object is from PhoneGap’s API and its value is added to the innerthtml for each #device element.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing!
        function onDeviceReady() 
        {
            console.log("onDeviceReady. You should see this message in Visual Studio's output window.");

            $('#devicename').html(device.name);
            $('#devicephonegap').html(device.phonegap);
            $('#deviceplatform').html(device.platform);
            $('#deviceuuid').html(device.uuid);
            $('#deviceversion').html(device.version);
        }
    </script>

The HTML and jQuery Mobile UI for the Accelerometer screen.


      <div id="accelerometerpage" data-role="page">
        <div data-role="header">
            <a href="#home" data-icon="back">Back</a>
            <h1>Accelerometer</h1>
            <a id="camerabutton" href="#camerapage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Accelerometer API
            <p id="aX"></p>
            <p id="aY"></p>
            <p id="aZ"></p>
            <p id="aTime"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object is from PhoneGap’s API. Here the navigator object calls the watchAcceleration method where the first input is the success callback method, the second parameter is the error callback method and the third parameter is the frequency in millisections the success callback method will fire.

var watchId = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, { frequency: 1000 });

        function onAccelSuccess(a) {
            $('#aX').html(a.x);
            $('#aY').html(a.y);
            $('#aZ').html(a.z);
            $('#aTime').html(a.timestamp);
        }
        
        function onError() {
            // TODO: write error logic
        }

The HTML and jQuery Mobile UI for the Camera screen. Here we will write to the imageuri the fileURI of the image we capture. It will write out the location and filename of the image.

      <div id="camerapage" data-role="page">
        <div data-role="header">
            <a href="#accelerometerpage" data-icon="back">Back</a>
            <h1>Camera</h1>
            <a href="#geolocationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Camera API
            <p id="imageuri"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object calls camera then the getPicture method. The input parameters are similar to the Accelerometer except the third parameter where we define inline the quality, destinationType and Camera.DestinationType.FILE_URI. The file_uri that is returned in the success callback method will be added to the innerhtml at imageuri.

navigator.camera.getPicture(onCameraSuccess, onError, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });

        function onCameraSuccess(fileUri) {
            $('#imageuri').html(fileUri);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Similar to the Accelerometer screen, we will write the lat/lon values to the innerhtml.

      <div id="geolocationpage" data-role="page">
        <div data-role="header">
            <a href="#camerapage" data-icon="back">Back</a>
            <h1>Geolocation</h1>
            <a href="#notificationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Geolocation API
            <p id="lat"></p>
            <p id="lon"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we’re calling the watchPosition of geolocation object and on the success callback method retrieving the lat and lon values.

navigator.geolocation.watchPosition(onGeolocationSuccess, onError, { frequency: 1000 });

        function onGeolocationSuccess(p) {
            $('#lat').html(p.coords.latitude);
            $('#lon').html(p.coords.longitude);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Here we created an anchor tag that will look like a mobile button that will display a PhoneGap notification alert.


      <div id="notificationpage" data-role="page">
        <div data-role="header">
            <a href="#geolocationpage" data-icon="back">Back</a>
            <h1>Notification</h1>
            <a href="#storagepage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Notification API
            <br/>
            <a id="notificationbutton" href="" data-role="button">Click Me!</a>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we use jquery to create a handler for notificationbutton that will call PhoneGap’s API object navigator.notification.alert. When the success callback method is reached it will update the innerhtml text of the button to Clicked.

            $('#notificationbutton').click( function() {
                navigator.notification.alert("You clicked me!", onNotificationSuccess, "Click", "Ok");
            });

        function onNotificationSuccess()
        {
            $('#notificationbutton').html('Clicked');
        }

I hope this helps in getting started with PhoneGap’s API. There is a lot more that can be discussed.

Here is the code for the sample project.