Monday, October 24, 2016

React-Navite - Introduction

React Native is one of the very few frameworks that has changed the way mobile applications can be built. Notice how I said mobile applications and not iOS or Android applications or for that matter mobile or tablet devices. React native applies to both. Now you think ahhhh, I have heard this before, we have looked at a lot of frameworks/packages like this before - PhoneGap, Titanium, Kony, Xamarin and so many others. If you think React-Native is one among them you are thoroughly mistaken.

What we look for in mobile applications

There is always a native language to build applications for smart devices and in the case of iOS, there is more than one. Why even concern about anything more to build a native application. What's special about React-Native and why should we care about it. That's a great question to start with.

Developing applications for smart devices is no longer simple anymore. It's not some 5 forms and a list application pattern. People are building CRM and ERP applications for mobile. Today, mobile solutions have changed from antiquated or even an extension from web into a full fledged solutions. In some cases mobile applications are the only go, they don't even have web counter-parts and future looks more like that. I have personally built applications that have more than 100 forms and at least about 40 lists. I am not going got brag about my mobile development experience here, but what I am trying to say is, it is a complex world out there. Applications are gynormous. Maintenance is a major  head-ache. In addition to our work on module, size complexities you have to think about several other factors and that includes


  1. How intuitive is the UI
  2. Support for mobile analytics 
  3. How Keyboard UI is presented and their customizations
  4. Application behavior in different orientations
  5. Graphics/Animation support inline with the application (I am not talking about those fancy animations that annoy users, so to say, but simple animations), 
  6. Access to native objects/applications to build a complete application
  7. Access to local storage, where ever possible. 
  8. Security of data, network operations
These are just a few of them, but you see where I am going

Benefits of building application from common frameworks


We may talk about couple more choices, but I think, if we can have a custom framework that allows us to do all of the above in one seamless form, we all can agree that, it's a great way to get started. And here are some reasons


  1. Code sharability (Even if it is a copy-paste code between iOS & Android, although there are nice design-patterns to handle such cases)
  2. Consistent design patterns between different devices, frameworks
  3. Similar and consistent approach for development, process and maintenance tools
  4. Better planning on tool investment like CI, code analysis etc
  5. Better network handling

Can React-Native help?


We talked about benefits of using a consistent programming language, but such a thing seems to be in an utopian world. Do we have anything closer to reality? The answer is YES and that's where React-Native comes in. This framework from Facebook, allows you to write your application in ES6. Compiler behind the scenes will convert your code into native application. Sounds great. This way you are not dealing with some HTML5 framework or a web solution but a real-world native application. Now all that you need to do is, stick with-in the boundaries of ES6 and React-native framework.

This framework has been tested and FB internally uses this framework to build some of their applications. Apart from FB, there are a lot of other enterprises that are using React-Native for day-to-day applications. Rest assured that you are not the first man to walk this terrain. If you have not tried it, I'd encourage you to read on and give it a shot.

In this section, I will walk you through some simple applications I built to help you see through the advantage of building React-Native application. Things like authentication, weather service, modal applications, better navigation etc are some. These are not typical applications that do the job of showing how to use some basic UI components, but I have weaved together components with application functionality that you can apply for your respective cases. Please stay tuned.....

Monday, October 10, 2016

rocky.js - Pebble Watchface in JavaScript

Create diagital watchface with rocky.js

Pebble is a familiar name in tech world. They were the one's who made the world turn on them when it comes to smart watches. When wearable technology was a dream, their design and approach made them great innovators. They followed it up with Pebble steel which did a wonderful business. Their OS agnostic approach has helped them gain love from both iOS & Android folks. Pebble has made a huge market for itself through its constant innovation and focus. With Pebble2, they have raised the bar a little more. I am not going to review about Pebble2 here. Our interest here is their new JS framework - rocky.js.

Pebble applications have been built with Pebble "C" and to some extent with Pebble JS. With Pebble 4 SDK, rocky.js will be one of the preferred way for pebble apps. rocky.js can be used to develop both watchface's as well as watch apps. Its support for canvas, makes it easy to render complex graphics fast too.

Although, I'd not rank rocky.js to be production ready yet, I'd also not shy away from saying that is is not far off from production grade either. Give it a month, by the time Pebble Time2 comes out to market, I'd say rocky.js may be the face of pebble application development.

What do I need to get started?
Head to developers.pebble.com, register your account and browse into cloudpebble.net, start cranking your code

Let's start by creating a new project, name it "HelloWorld"



You will be taken to cloud studio, from the left navigator, tap/select index.js



We will build our first simple display current time watch face, copy paste the following lines of code

var rocky = require('rocky');
var formatAMPM = function(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}
var display_time = function(ctx) {
  // Determine the width and height of the display
  var w = ctx.canvas.unobstructedWidth;
  var h = ctx.canvas.unobstructedHeight;
  var d = new Date();
  // Set the text color
  ctx.fillStyle = 'white';
  // Center align the text
  ctx.textAlign = 'center';
  ctx.font = '30px bolder Bitham';
  // Display the time, in the middle of the screen
  ctx.fillText(formatAMPM(d), w/2, 50, w);
}
rocky.on('draw', function(event) {
  // Get the CanvasRenderingContext2D object
  var ctx = event.context;
  // Clear the screen
  ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);

  display_time(ctx);

});
rocky.on('minutechange', function(event) {
  // Request the screen to be redrawn on next pass
  rocky.requestDraw();
});

Most of the the code is self-explanatory. We start by registering for event-notifications from rocky. One for 'minutechange' (you can try 'secondchange', 'hourchange', etc) and other for redraw. Every minute, code invokes redraw, where-in we display current time through a custom format function.

You are restricted on size and type of fonts, pretty much the same as in "C". However, you can have custom fonts for your applications.

You are all set. Tap on "run", wait and watch your code execute

Tuesday, October 4, 2016

Authentication in NodeJS

We all know and have done authentication for variety of applications - be it on web, mobile, windows or mac applications. The challenge with authentication lies on a couple of different fronts

  1. How easy it is for different applications to integrate and use the same authentication mechanisms
  2. How easy is it to use different strategies without breaking client applications


Its lot more easier said than done. In the past, client application will accept user names and passwords, encrypt credentials and send them over to a safe network and will wait for authentication status from server(s). This works great if we have a singular repository for authentication. Todays users have too many accounts to remember, one would think, its lot more easier to use any of the social network for authentication, while authorization can be managed internally. Such a solution will need more work from both client and server side on one dimension. But from the other dimension, it requires less work in terms for process. Client applications help user choose from one of many social engineering repositories, captures information and passes it to the server. While the server, does not digest this information, but rather, reaches out to the selected repository for information, gets back minimum profile information, along with a token identifier that can be used for back-forth communication. As long as all of the information from the server is available in request header, communication has no problems. If either TTL expires or the request header is manipulated, then authentication process is broken and the user is no longer identified as a authenticated user. He'll be re-directed to logon screen. Behind the scenes, developer needs to classify what constitutes secure paths and what are open for public, which is pretty much like the way he has to do for any regular secure application. No changes there. Enough talking. Lets get down to business.

How about creating a simple NodeJS application that will help you authenticate with different repositories like - Google+, Facebook, Twitter, LinkedIn etc? Sounds exciting. Here' how we can do it

Create a simple NodeJS application and see it work on the choice of your port. I prefer port 3000, you can choose any port of your choice. Once you have the intiial setup, head on to https://developers.facebook.com/, from there choose "My Apps". Tap on "Add a New App". You'll get a pop over, fill in the details, like display name, description, type of application etc. Now, in "Settings" section provide additional information like "App domain", which in our case will "localhost:3000" callback URL will be "http://localhost:3000/auth/facebook/callback". This is the URL that FB application will call us back on, after both successful or failed logon, with appropriate response. Note down App Id and secret key information from FB's site. Under Products section, you'll see "Facebook Login". Under "settings", make sure you set "http://localhost:3000/auth/facebook/callback" for "Valid OAuth redirect URIs".

Now, back in our node application, let's build strategies to handle this. For us to let application talk to FB, we need some more basic set up

Open terminal, navigate to your root directory of node application

npm init
npm install passport --save
npm install passport-facebook --save
npm install passport-github --save
npm install passport-linkedin-oauth2 --save
npm install passport-google-oauth --save
npm install body-parser --save

Each of these npm packages installed allow us to interface with respective authentication repositories. Now, back to FB's authentication. Import passport and passport-facebook packages into your application


var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

app.use(passport.initialize());
app.use(passport.session());

passport.use(new FacebookStrategy({
    clientID: AppConstants.FaceBook.appId,
    clientSecret: AppConstants.FaceBook.secretKey,
    callbackURL: BASE_URL + AppConstants.FaceBook.callbackURL
}, function (accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
        done(null, profile);
    });
}));

We set the application use passport, passport session and FacebookStrategy as its middleware. Either replace  'AppConstants.FaceBook.appId' and 'AppConstants.FaceBook.secretKey' with the one you got from FB's site, or you can create a separate file with this information. Both of these are less secure, although, later one is slightly better. Personally, I'll store secret key and appID information in a remote location and fetch it when the application starts, or dump it in a secure remote DB, or even better store it as an environment variable. For this sample application, we are fine with any approach.

Now to handle callback from FB, here's what you amy want to do in your router configuration


// Facebook Router
router.get('/auth/facebook', passport.authenticate('facebook'));
router.get('/auth/facebook/callback', passport.authenticate('facebook', {
    successRedirect: '/success',
    failureRedirect: '/error'
}));

router.get('/success', function (req, res, next) {
    if(req.session != null) {
        console.log('Session information');
        console.dir(req.session);
    } else {
        console.log('SESSION is NULL');
    }

    res.redirect(302, 'home');
});
router.get('/error', function (req, res, next) {
    res.send("Error logging in.");
});
router.get('/', function (req, res, next) {
    res.sendfile('public/login.html');
});

And that's it. If your authentication is successful, you'll be re-directed to "home" page. You can follow this same procedure for all other authentication strategies like LinkedIn, Twitter, Google and Github. Working code for all of this is available in location