An AngularJS CRUD using Azure Mobile Services

Lately, we saw very promising web technologies coming out. I am currently exploring some new web applications stacks that are more RAD and flexible. I especially focused on angularJS and Azure Mobile Services which are in my opinion two of the most interesting technologies of the past months.

Why AngularJs?

AngularJSI would describe AngularJS as a javascript view oriented framework. It offers a very element way to build dynamic web pages using two-way binding, events, controllers, router, … I particularly the very elegant and direct approach of solving the issue by keeping very close with the javascript philosophy. It is comparable to KnockoutJs, EmberJs, or BackboneJs, but I choose none of those because I found they over-thought the issues with too much code and abstractions.

Why Azure Mobile Services?

Windows AzureAt first Azure Mobile Service sounds like a plateform for mobile applications. It offers an online SQL storage with SDKs for iPhone, Android and Windows Phone plateforms for easy CRUD access. It also has some bonuses like a push notification system and a dynamic mode where the SQL schema is enriched every time a new field is pushed on a table. What’s more is the fact that the online stack is an SQL database with a nodejs frontend acting as a REST service. There is also now a javascript SDK that allows web-applications to connect with the storage service.

Building a CRUD

My tutorial is about creating a CRUD for Azure Mobile Services using AngularJS, an interesting alternative has been brought recently using AmberJS, but, as I said, I prefer AngularJS.

First, setup mobile services:

1. First of all you need an Azure account with the preview for Mobile Services activated.
2. Create a mobile services:
Create an Azure Mobile Services
3. Follow the wizard steps then go to your newly created service.
4. Then go the the Data tab then create a table:
Create a data table
5. In the configure tab, be sure that the dynamic schema is activated and that your development/production host is in the cors configuration:
Configure the service
6. In the dashboard tab, note the mobile service url, and in the manage keys popup, get your Application Key:
Get you service url and application key

Then, lets prepare our angular website:

1. The first thing to do is to create a js file, configuring a resource to your mobile service table:

// mobile-service.js
'use strict';

angular.module('mobileServices', ['ngResource']). // new service mobileServices depending on ngResource
    factory('Task', function($resource) { // declaring a MyTable resource
        return $resource('https://myservice.azure-mobile.net/tables/task/:taskId', {taskId: '@id'}, // binding to the table url
            {
                'update': { method:'PATCH' } // adding an update function
            }
        );
    });

Here a new service named mobileServices is configuring the ngResource service to provide a Task resource connected to the table named task in our Azure Mobile Service. Note that we added a supplementary update action that uses the method PATCH. This is because Azure mobile service uses POST only for creation and PATCH must be used for update. Note that the Task resource is already provided with get, query, save, remove and delete.

2. In the app.js file configuring angularjs, lets tweak some code:

// app.js

angular.module('myapp', ['mobileServices']). // setting up our app to use the mobileServices service
    config(['$httpProvider', function($httpProvider) { // coniguring the httpProvider
        $httpProvider.defaults.headers.common['X-ZUMO-APPLICATION'] = 'myapplicationkey'; // add the application key
        $httpProvider.defaults.headers.common['Content-Type'] = 'Application/json';
    }]);

We just configured our app to use the mobileServices service and added the application key that will allow authentication to he Azure Mobile Service.

3. Now, you can easily import the Task resource in any controller, here is an example:

// controller.js

function MyCtrl($scope, Task) {
    $scope.tasks = Task.query(); // load all tasks
    $scope.newTask = new Task(); // create an empty new task

    // saving a new task
    $scope.createTask = function() {
        // call the service
        $scope.newTask.$save(function() {
            // when saved, reload the list and recreate a new task
            $scope.tasks = Task.query();
            $scope.newTask = new Task();
        });
    }

    // removing a task
    $scope.deleteTask = function(task) {
        // call the service
        task.$delete(function() {
            // when deleted, reload the list
            $scope.tasks = Task.query();
        });
    }

    // saving an existing task
    $scope.updateTask = function(task) {
        // call the service
        task.$update();
    }
}

Ad you can see, this commented controller is very straight forward. The controller has a list of tasks and an empty one dedicated to the creation process. Three functions allows to create, update and remove a task.

4. To complete the example here is a possible HTML usage:

<!DOCTYPE html>
<html ng-app="myapp">
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="angular-resources.js"></script>
    <script type="text/javascript" src="mobile-service.js"></script>
    <script type="text/javascript" src="controllers.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <div ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="task in tasks">
                <input type="checkbox" ng-model="task.done"
                       ng-click="updateTask(task)">
                <span>{{ task.text }}</span>
                <a ng-click="deleteTask(task)">delete</a>
            </li>
        </ul>
        <form ng-submit="createTask()">
            <input type="text" ng-model="newTask.text"
                   placeholder="add new task here">
            <input type="submit" value="create">
        </form>
    </div>
</body>
</html>

Here we display the list of task. Each item has a checkbox which is instantly saved upon click and a delete button. Also a form allows the creation of a new task.

Wrap up

Thanks to AngularJS + Azure Mobile Services. In a very few lines of codes and configuration, we were able to build a CRUD web application in a very reactive way.

Advertisements

How to run your Symfony2 PHP app on Azure website

Windows AzureBestComparator is part of the DojoBoost accelerator in Paris and a Bizpark partner. We have the chance to have some partnerships with Microsoft and thus have some support and early access to some technology. Especially about Windows 8 and Azure.

Talking about Azure, they made tremendous upgrades to the platform during the year. They moved from a PAAS platform to a full layered cloud solution. From SAAS to IAAS you can do almost everything. Create a WordPress in a few clicks, create a VM, configure a VPN, create a SQL server, create a mobile service that interface an autogenerated backend storage with your iPhone/Android/Windows phones, scale your services by moving a slider…
Being at the Azure Open Source Summit really amazed me about all the possibilities that are offered to developers and how fast new features comes to the portal. One of those which interested me the most is the possibility to run a PHP website on Azure using the Web Site feature.

About PHP and Azure

PHPYou currently have two main options to run PHP on azure.

First you can simply create a VM using Azure Virtual Machine, after choosing an OS (Windows Server, CentOS, Suse, Ubuntu…) you just connect to your server and configure everything you need. You can change the size of you VM, it goes up to 8 cores and 15GB of RAM. I am running it in production for a few mounts now, and it is pretty stable and reliable. Nevertheless there are some drawbacks. You have to maintain your environment (which is not my job) and it has some limitations in terms of scalability (if you want more power, you will need to maintain another VM and start configuring load balancing and synchronization…). This is pure IAAS.

The other option I recently explored is using Azure website. You simply ask for a computation service which uses a code synchronized via git. It takes care about all the environment maintenance for you and just runs your code. Moreover, you can leverage some nice features such as the possibility to increase the size of the underlying instance (up to 4 cores and 7GB of RAM), but also increase the number of instances (up to 20) seamlessly. Azure takes care of the rest for you. This is more PAAS oriented and let you concentrate on developing your app.

Let’s start a first PHP website:

  1. First of all go to your azure portal
  2. Create a new website using the custom wizard
  3. Select the name of your website, the region, a database (or not) and check the “publish from source control” option
    step2
  4. Choose “git” and “local git repository” as source control setup
    step3
  5. In a third step select your credential, they will be required for git synchronization and ftp login (if you want to)
  6. Now, open the deployments panel in the newly created website you will find there the git url
    step4
  7. On your local machine, simply clone the repository (or set a remote): git clone https://michel@blog-test.scm.azurewebsites.net/blog-test.git
  8. Put your PHP code in the cloned repository, commit, and push to azure
  9. When pushing to azure, it will automatically publish the newly updated code to the website, you can visualize it directly by connecting to the url of the website displayed in the website dashboard

At this point you can upload PHP code to Azure and run it. Here is what you might want to know:

  • You can switch PHP version (5.3 and 5.4) in the configure tab
  • You can scale the size and the number of the instances in the scale tab
  • You can map your domain name using the “manage domain” option available in the bottom bar if you are in “shared” or “reserved” mode (available in the scale tab)
  • If you don’t want to deploy from a local git repo, you can using github, codeplex or bitbuket. It is configurable from the wizard in step 4.
  • You can set environment variables in the configure tab
  • You can choose which branch of your git to deploy in the configure tab
  • You can access the server via ftp using the credential given in step 5 and the ftp configuration in the dashboard
  • You can override the php.ini by giving a .user.ini at the root of your repo

What about Symfony2 websites?

Symfony2 LogoRunning a Symfony2 website is doable but it will require some more work. You will have two main issues to fix:

  1. Activate url rewriting to web/app.php, and reroute web requests to the web directory
  2. Find a way to use the composer and the console

The first issue can be tackled simply by adding a Web.Config file at the root of you repo. It works just like .htaccess for apache but for IIS. Here is the content:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="web directory">
                    <match url=".*" ignoreCase="false" />
                    <action type="Rewrite" url="web/{R:0}" appendQueryString="true" />
                </rule>
                <rule name="app_php handling" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/web/app.php" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

In the Web.Config file we define two rules. The first one reroutes every request to the web directory, and the second one routes the requests to the web/app.php script when there is no physical file requested.

I did not yet tackled the second issue (ie. composer and console use). What I know is that there is no command line access to Azure website but it seems like you can use the exec PHP function from PHP scripts. So everything seems doable with some web interface that simulates command line using PHP functions. I will edit this post as soon as I find a better solution.

What if I want to add some extensions/tweak to PHP runtime?

You may notice that Symfony recommends the use of the intl extension for PHP which is used for internationalization of the validation component (and also in some BCC bundles). You might also need a specific setup of PHP such as a specific version, a configuration which cannot be overridden in the .user.ini file or another extension.

Don’t worry, you can give to Azure you own PHP runtime:

  1. Go to http://windows.php.net/download/ and get the version of PHP you want (which has to be “VC9 x86 Non Thread Safe”)
  2. Unzip it to a directory in your repo, in my case in a ./bin directory
  3. Configure your php.ini file in bin/php.ini
  4. Remove the extensions you don’t want in bin/ext/*
  5. Add, commit and push the files (which might take some time considering the size of your php runtime)
  6. When git is synchronized, go the configure tab on azure
  7. At the bottom of the section, add a handler mapping configuration. The extension is *.php and the script processor path is D:\home\site\wwwroot\bin\php-cgi.exe (because D:\home\site\wwwroot\ is the root of the website and my PHP runtime is in the bin directory)
    step5

Everything is set and you website now runs on your own PHP runtime.

Wrap up

Despite Azure is very young, it offers a lot of possibilities in terms or configuration. I hope this post will help you understand better how it works and how to setup your favorite PHP environment while leveraging all the nice features of Azure.