Build a Hybrid Application with the Ionic Framework and Microsoft Azure Mobile Services

Introduction

In this post I’ll show you how to create a hybrid mobile application using the open source ionic framework and how to integrate the application securely to a Microsoft Azure Mobile Services backend. By integrating  with azure mobile service you get to connect to reliable cloud storage via a simple JavaScript SDK.

I’ve made the complete source code is available on GitHub  – feel free to fork the code or use it however you like.

Ionic Framework

Ionic is an open source JavaScript and CSS framework for building cross-platform HTML5 mobile applications. It’s built with Cordova and AngularJS and it comes with a nifty command life interface that lets you build  IOS and Android apps. My experience working with ionic has been really good. It is very easy to get started with ionic and there is a strong community behind with about 200 contributors to the codebase. Work is well underway to remove the dependency on AngularJS which means you’ll be able to plug the inoic framework into your JavaScript framework of choice in the near future.

Microsoft Azure Mobile Services

Microsoft Azure Mobile Services is a mobile backend as a service (MBaaS) offering from Microsoft. Almost every mobile application needs to store some data, deal with push notifications, service monitoring and authentication. With microsoft azure mobile services you get all of this as a “platform as a service” offering. You don’t need to spin up a single server to go live with a mobile app, simply provision yourself a mobile services backend in azure and  and you have access to all of these features along with a a fully programmable node.js or .NET backend.

The todo appapp I’ll take you through the key steps and code needed to build a simple todo mobile app. Users will authenticate with a google plus account. Once logged in they’ll be able to create new tasks and maintain a list of outstanding tasks.


Creating the ionic app

First up install apache cordova and the ionic framework via npm

npm install -g ionic
$ npm install -g cordova

Next,  create a new ionic application using one of the sidemenu starter template

$ ionic start Azure-Ionic-App sidemenu

That’s it! if you run the command “ionic serve” a browser will open running your application.The application we are building consists three simple views and controllers – login, add task, and  view all tasks.

Implementing Google Authentication

Firstly, create a new azure mobile service  via the azure portal. If you don’t have an account you can sign up for a free trial here. You’ll get more than enough credits with a trial account to develop  and test an application.

Once your mobile service is provisioned take a note of the mobile service url  on the dashboard page https://ionic-todo.azure-mobile.net this is your unique the API endpoint for your mobile app.

create mobile back end

The process of how to register your app for a google login is already well documented here . You’ll need to login to the google developer console, create a new web project and register for “Google +API” OAuth authentication then in the credentials tab, enter the authorization redirect URL for you application. This will be “your-mobile-services-url/login/google” , in my case its “https://ionic-todo.azure-mobile.net/login/google”google console

Now to associate your google application with the mobile service backend. Go back to the azure portal and enter the google client id and secret on the identity tab..

google register

To integrate a google login into your ionic application you’ll need to bundle the mobile services JavaScript client library with your application and add the following AngularJS factory class which returns a mobile service client object .

angular.module('azure', [])
  .factory('client', [function () {
    var client = new WindowsAzure.MobileServiceClient(
      "https://ionic-todo.azure-mobile.net/",
      "your-mobile-services-application-key"
    );
    return client;
  }]);

Using the client object we can take care of the OAuth flow by simply calling client.Login(“google”);


//the login controller calls client.login("google") to perform the oAuth dance
angular.module('azure', [])
angular.module('app.controllers', ['azure'])
.controller('LoginCtrl', function(client,$scope, $state) {
    $scope.login = function() {
      client.login("google").then(function succes(data){
        console.log('logged in succesfully..')
        $state.go('app.list');
      }, function(error){

        //login failed.
      });
    }
  })

The OAuth flow happens in a separate browser window.You must install the Cordova InAppBrowser plugin from to be able to show the login popup on a mobile device. Run the following command to install the plugin locally

$ ionic plugin add cordova-plugin-inappbrowser

then add the plugin to your config.xml file to bundle it as part of the ionic build process.

  <feature name="InAppBrowser">
    <param name="ios-package" value="CDVInAppBrowser"/>
    <param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser"/>
  </feature>

Once logged in, a user context is set on the client object. You can access this at any time by simply injecting the client factory class we created earlier into the relevant controller; client.currentUser.userId

We’ll store the unique userId property as part of each todo item in the data store to make the solution multi-tenanted and to ensure you only get to see your own todo list tasks, I know I for one don’t want to complete other peoples tasks!

Storing Data in Azure Mobile Services

When you provisioned a mobile services on azure  you also provisioned a SQL Server backend but chances are you won’t treat the backend like a relational database. When you provision a new table in the database it gets allocated a dynamic schema by default ( very cool but you can turn this off if you like). As you make API calls to store data in a table new columns are generated based on the properties of the JSON object you send to the API.

Go to the data tab in mobile services and a create a table called “Task” to store the todo items. Set the table permissions for insert, update,delete and read operations to “authenticated users”.  You can now read and write data to this table via the mobile services client factory class we created earlier.

Its worth highlighting that the backend API that writes to the database table is fully programmable and you can write node.js scriptlets to validate and transform your data before it gets written to the data store. If you’d prefer to write your data to a MongoDB or DocumentDB data store its pretty easy to swap out the database completely  – more information here

For the purposes of this post we won’t create any server side scriptlets, we’ll let the data go straight through to the tasks table.To keep the ionic application more modular I created a separate AngularJS factory to class to connect to the azure backend.

There’s a few things worth highlighting in the code

  • when saving data in the addTask() function I tack on a userId property.
  • when reading data in the getAll() function I create a filter expression to filter to return the tasks for the logged in user.
angular.module('app.services', ['azure'])
  .factory('azureAPI', ['client' ,'$q', '$rootScope', function (client, $q, $rootScope) {

    return {
      getAll: function () {
        var deferred = $q.defer();

        var userId = client.currentUser.userId;

        //filter by user id
        client.getTable('Task').&amp;amp;lt;strong&amp;amp;gt;where({userId:userId})&amp;amp;lt;/strong&amp;amp;gt;.read().then(function () {
          deferred.resolve.apply(this, arguments);
          $rootScope.$apply();
        }, function () {
          deferred.reject.apply(this, arguments);
          $rootScope.$apply();
        });

        return deferred.promise;
      },

      addTask: function (task) {

        &amp;amp;lt;strong&amp;amp;gt;task.userId = client.currentUser.userId;&amp;amp;lt;/strong&amp;amp;gt;
        var deferred = $q.defer();

        client.getTable('Task').insert(task).then(function (data) {
          deferred.resolve.apply(this, arguments);
        }, function (error) {
          deferred.reject.apply(this, arguments);
        });
        return deferred.promise;
      },

      updateTask: function (task) {
        var deferred = $q.defer();
        task.userId = client.currentUser.userId;

        client.getTable('Task').update(task).then(function (data) {
          deferred.resolve.apply(this, arguments);
        }, function (error) {
          deferred.reject.apply(this, arguments);
        });
        return deferred.promise;
      }

    };
  }]);

That’s it. We’ve now hooked up google authentication and our mobile is storing data against a microsoft azure mobile services backend.

All the code is available here :

https://github.com/aidancasey/Azure-Ionic-App

Hope this helps

Advertisements

4 thoughts on “Build a Hybrid Application with the Ionic Framework and Microsoft Azure Mobile Services

  1. Pingback: Mobile Web Weekly No.78 | ENUE Blog

  2. Pingback: 200+ Ionic Framework Resources | Yahaay CodeStash

  3. Pingback: 200+ Ionic Framework Resources

  4. Pingback: 240+ Ionic Framework Resources – IndaSoft

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s