Sunday, September 20, 2015

Azure Mobile Service as your App's backend

In continuation to the two previous blogs (Parse and Firebase), in this one describing Azure Mobile Services. It's an another option for cloud based back end that's quick to get started. Microsoft Azure is a sophisticated cloud service provider with great pricing options.

In this blog, focus is on server side code. I'm picking JavaScript back end (NodeJS) for Azure Mobile Service, which will be configured to use MongoDB for data storage.

If you are looking for JavaScript code consuming the Mobile Service use my earlier blog. It's using SQL Azure and a table for storage.

Let's get started. Log into Microsoft Azure Management portal.

Using MongoLab for our Mobile Service

Let's use Mongo Lab for the database integrating with Mobile Service. It provides MongoDb as a service on the cloud. Checkout more here.
This is also available on Azure Market Place, which we will use in this sample.
  1. Click New, Select Market Place. 
  2. Find and select MongoLab
  3. Click next and select your plan. I'm choosing Sandbox, which is free for the purposes of this blog.
  4. Click next, review and complete the purchase.

Once done select Mongo service in the Portal. Click Connection Info. Copy the connection string.


Working with Azure Mobile Service

Select the Mobile Service we wanted to work with. Make sure it's JavaScript back end. Dot net back end services have slightly different options.

Setup Source Control and clone to your machine.

Setup Source Control by clicking Setup Source Control in dashboard tab. This is required to be able to add MongoDb NPM Package to the Mobile Service back end.

Next navigate to Configure tab, copy git Url.

(Note: You always have a git URL at this place. I had to find it hard way, unless Setup Source Control is done, git URL doesn't work. I was hoping it will work with Microsoft/Azure credentials, but it has it's own user id and password)
  1. In any folder on your machine, use git clone << git URL >>
  2. Use npm install mongodb
  3. Commit and push your changes.
    • git add --all
    • git commit -m "Added MongoDB Package"
    • git push
Now the Mobile Service is ready for MongoDB Code.

Modify the mobile service to integrate MongoDB (instead of tables)

In the Mobile Service, select Data tab and resource you want to work with. In this example resource is named Book.


Next select Script tab. Here we can select Insert, Update, Read and Delete from the drop down. The script for each operation has one line by default request.execute(), which performs respective action to the SQL table. We can add additional server side validations if we wish to.

For using Mongo DB we are going to modify the script to update Mongo DB instead of SQL Table. Below are basic scripts to do so. You might improvise on these to make it more sophisticated.

Note: if you leave request.execute() it will also perform operation to the table. One interesting idea would be to go to Mongo for specific kind of data and use table for the rest.

C . R . U . D

In the data tab and selected resource (table) use drop down to switch between C.R.U.D (Create/Insert, Retrieve/Read, Update and Delete) and write code to read/insert/update/delete from MongoDB.

client.connect takes connection string, which was copied from MongoLab Market Place service earlier in the blog.



Note- Mobile service uses Patch instead of put for update

































In conclusion Azure Mobile Services are flexible to use with multiple data storage options other than the default tables and yet it's quick to get started with many out-of-box features. There are many other Mobile Services' features like Push notifications, Scheduled Jobs etc. I hope to hack more of it soon.

Happy Coding.

Thursday, September 10, 2015

Parse as your app's backend

Parse is a cloud based backend service. For an application either a mobile app or a web app, Parse provides storage, SDK for easy integration and cloud services for additional processing including push notification support, analytics etc.

Parse provides APIs for variety of technologies. This blog is focusing on JavaScript. The framework is inspired by backbone and it's style of coding in JavaScript. Lot of articles use Handlebars and other templates in their examples. For simplicity, I'm using JQuery in this blog.

Get Started

  1. Once you register and login at Parse.com, create an app and launch quick start guide for it.
  2. Choose Data - Web - and New Project
  3. Here you can chose to download a blank HTML/JavaScript project or explore APIs to be added in an existing project.

Core

Parse Core provides data storage, retrieval and Data Browser. The Data Browser allows you to create one or more classes (which can be visualized as a table - refer to the screenshot). Here you can add/delete and modify data. It's the same data your app is integrating with, so changes are reflected in your app automatically (as you refresh screens).

Click on Add Class - provide name. It creates a table with default columns like objectId, CreatedAt, updatedAt etc. Click +cols to start adding custom columns.


Now, get started with code-

// Get started with initialize function
Parse.initialize("[application_id]", "[JavaScript Key]");

You get these keys as soon as you create the app. You could go to Key's screen to view and copy all available keys. If you chose to download the blank template you may use boilerplate code.

Create an object of class created in Data Browser. I'm referring to a class named book in my example.

var Book = Parse.Object.extend("book");

// Now create an object of book.
var book = new Book();

C.R.U.D

Following code demonstrates Create, Retrieval, Update and Delete of books data
// Create new records
// use set
book.set("aKey", "aValue");


Key here is same as column name in Data Browser

// Or set all column values at one-go.
book.set({aKey: 'aValue', secondKey: 'secondValue'});

//save creates the record for the table/class

// you may pass above object instead of null/first param. Then set is not required
book.save(null, {success: function(response){
   // On successful save response has all saved records.
}, error: function(error){
  // error information if occurred is in error object.
}
});


// ----------------------------------------------------------------- // Retrieval
// To Parse.Query function pass the class 
// Book below is not new'ed. It's returned value of Parse.Object.extend(). Refer to code above.
var query = new Parse.Query(Book);

// You may filter with queries like below. This looks for key with a value specified
query.equalTo("key", "value");

//or directly calling find() returns all records
query.find({
success: function(results){
for (i in results){
var data = results[i];

    // addBookRow() updates DOM with new row.
addBookRow(data.get("title"),
data.get("author"),
data.get("publisher"));
}
},
error: function(error){
$(".error").hide();
console.error(error);
}

// ----------------------------------------------------------------- // Update by getting an instance of book class for an existing record.
// I used find() for it.
query.find({
   success: function(result){
        // Get first row from results
var row = result[0];

        // update the first "title" column with new value
        row.set("title", "new value");
        row.save(null, { success: function(){}, error: function(){}});

   }
});

// -----------------------------------------------------------------
// Delete by getting an instance of book class for an existing record
// Used query.find to get it
query.find({
   success: function(result){
        // Get first row from results
var row = result[0];

        // Delete with destroy function.
        row.destory({ success: function(){}, error: function(){}});

   }
});

Refer to complete sample here

This is a introductory blog on Parse, planning to followup with concepts of
  • More queries and explore more of JavaScript parse library
  • Cloud code - additional hooks and validations on cloud. It's server side logic. Used instead of adding complex logic with-in a browser or a mobile app.
  • Parse Push - Easy integration of Push for various mobile platforms. Currently it's only for mobile devices.
Have fun Parsing!

Sunday, September 6, 2015

Firebase as your app's backend


Firebase is a cloud based back-end as a service provider. It can be used as a very effective No SQL data-store. Your application can store JSON objects. Integration is made easy with variety of libraries provided by Firebase. For this blog I'm focusing on Web/JavaScript library.

As a developer it's quick to get started. No overhead of installation and setup. It's a cloud service, so don't have worry about setting-up servers. Firebase tools on your machine are provided as an NPM package. Install with following command, globally on your machine.

npm install firebase-tools -g

This makes it a good choice for independent mobile/web app developers. Signup and login to Firebase.
Create an app. Remeber your app has a URL. JSON Key/Value pairs are shown at that URL. You might chose to manually add/remove/modify data as well.

Synchronized:

As and when data is updated in the backend, JavaScript events are raised and the callbacks provided are invoked with updated data. Hence your app is in near synchronous state all the time. With this approach we write less code, retrieving data is made simpler. Down below I've mentioned couple of data retrieval options. Checkout more here.

Consider Two Tier Architecture

With JavaScript and browsers being more and more powerful, you don't have to look at mandatory middle tier. Firebase can act as your middle tier and data store. Security, validation and authentication features of Firebase do allow this kind of architecture. 

Get Started

by referencing Firebase library in your Web Page. You could use CDN location. Or by downloading Firebase bower or npm package. I chose bower (package manager).

bower install firebase

And reference of firebase.js in bower_components. There after

//create an object of Firebase
var ref = new Firebase('URL of your firebase app');

Save Data to Firebase:

// to set a primitive data value
ref.set('sample value')
ref.set(100);

// you may set a JSON object instead
ref.set({
field1: 1,
field2: {
  child1: 'value'
}});

//If you are storing a new object every time, use push (array) instead of set.
ref.push({
field1: 1,
field2: {
  child1: 'value'
}});

Retrieve data from Firebase:

As mentioned earlier, Firebase keeps data synchronized. Data is pushed to the browser as changes happen. JavaScript code need to have callback functions defined to update view as data is retrieved automatically.

//Look for changes to the data
ref.on('value', function(snapshot){
    console.log(snapshot.val());
});

// data added as a child node.
ref.on('child_added', function(snapshot){
    console.log(snapshot.val());
})


All data elements in Firebase are represented by URL. You can traverse through the nodes in the URL itself. For example, to reach child1 in above example, you could provide URL "http://yourapp.firebase.io/field2/child1" to the Firebase function.

or you could use ref.child('field1/child1')


Running your application:

You may use any Web-Server to serve HTML files on your machine. Serve is a good choice.

npm install serve -g

Run serve from at the root folder of your application.
Firebase also provides hosting service. Run

firebase init
(Link application to Firebase app in this step.)

firebase deploy
(Deploys to Firebase cloud service)

You can serve HTML files on the cloud now. URL is on App Card It will be your appname.firebasepp.com

This is an introductory blog. Do checkout Security, Authentication, OAuth and Offline features of Firebase.


Also, I've basic Firebase examples on my Github. Use this link to explore.