Thursday, July 05, 2012

Fiddle with EJS filters

Lets play with EJS filters a bit. Lets pay greetings to the first user in the array of names with a message as "Welcome <firstname> <lastname>"

Lets take the names in an array of objects as below:

var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];

Now lets create a filter to create the message, in this filter the first selected object will be passes, which comes from the previous filter "first"

ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};

The call to the filter is made in the index.ejs file as below, here insted of first you can can also use last filter

<%=: users | first | greeting %>

Lets see the whole program.

server.js
var express = require('express');
var io = require('socket.io');
var http = require('http');
var ejs = require('ejs');
 
var app = express();
var server = http.createServer(app);
 
var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];
 
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/'));
  app.set('view engine', 'ejs');
  app.set('view options', {
    layout: false
  });
});
 
ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};
 
app.get('/', function(req, res) {
  res.render('index', {
    title : 'Welcome to Express EJS',
    users: names
  });
});
 
server.listen(8080);

index.ejs
<html>
 
<head>
<title><%= title %></title>
</head>
 
<body>
<p><%=: users | last | greeting %></p>
</body>
 
</html>

Simple application using ExpressJS, SocketIO & EJS

I came across EJS (JSP look-a-like for Node) and fell in love at first site, there are some other view rendering engines like Jade, but EJS clicked me as I saw it. So just went down to have a look my first app. There were some problems I faced regarding the API changes made in express latest version which I resolved with some googling. Lets get down to the code.

Create the test application with folder structure as below.

server.js
var express = require('express');
var io = require('socket.io');
var http = require('http');
 
var app = express();
var server = http.createServer(app);
var listener = io.listen(server);
 
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/views'));
  app.set('view engine', 'ejs');
  app.set('view options', {
    layout: false
  });
 
});
 
app.get('/', function(req, res) {
  res.render('index', {
    title : 'Welcome to Express EJS',
    message : 'Below you will see the message recieved via socket.io event'
  });
});
 
listener.on('connection', function (socket) {
 
  console.log('Connection to client established');
 
  socket.emit('news', 'This is the news');
 
  socket.on('newsresponse', function (data) {
    console.log(data);
  });
 
  socket.on('disconnect',function(){
    console.log('Server has disconnected');
  });
 
});
 
server.listen(8080);

index.ejs
<html>
<head>
<title><%= title %></title>
<script src="/socket.io/socket.io.js"></script>
<script src="/jquery.min.js"></script>
 
<script>
var socket = io.connect('http://localhost:8080');
 
socket.on('connect',function() {
  console.log('Client has connected to the server!');
});
 
socket.on('news', function (data) {
  $("#iomsg").html(data);
  socket.emit('newsresponse', 'this is news response');
});
</script>
 
</head>
 
<body>
<p><%= message %></p>
<div style="color:#3333ff;" id='iomsg'></div>
</body>
 
</html>

If you come across any undefined modules, just do and "npm install <module>". Run the server "node server.js" and then try to access "http://localhost:8080"

Wednesday, July 04, 2012

Exploring ExpressJS & Socket.IO

The next line of action today was to check the working of Socket.IO along with Express. Took me a while to get my sample working, here it goes if someone likes to use.

Index.html to be present in the same directory.

<html>
<head>
<title>Test - Node Views</title>
<script src="/socket.io/socket.io.js"></script>
 
<script>
var socket = io.connect('http://localhost:8080');
 
socket.on('connect',function() {
  console.log('Client has connected to the server!');
});
 
socket.on('news', function (data) {
  console.log(data);
  socket.emit('newsresponse', 'this is new response');
});
</script>
 
</head>
 
<body bgcolor="#ffffff" text="#000000"></body>
 
</html>

Server.js

var express = require('express');
var io = require('socket.io');
var http = require('http');
 
var app = express();
var server = http.createServer(app);
var listener = io.listen(server);
 
app.configure(function(){
  app.use(app.router);
  app.use(express.static(__dirname + '/'));
});
 
listener.on('connection', function (socket) {
 
  console.log('Connection to client established');
 
  socket.emit('news', 'this is the news');
 
  socket.on('newsresponse', function (data) {
    console.log(data);
  });
 
  socket.on('disconnect',function(){
    console.log('Server has disconnected');
  });
 
});
 
server.listen(8080);
 

Thursday, June 28, 2012

Mootools Class in NodeJS global context - Second Approach

In my last article here, I described how to load Mootools class in NodeJS global context. What if I do not want to make use of include to load the class, is there a way I can still do it with require. So, lets rewrite the program, and check how to do it

Application.js
(function(){
 
var Application = this.Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
})();

So, now the main file contains the code as below

Server.js
require('./mootools');
require('./Application');
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Hope this will solve !

Wednesday, June 27, 2012

Mootools Class in NodeJS global context

In continuation of my previous articles, here I came across a requirement to load Mootools Class in NodeJS global context. Let me try to explain, NodeJS module system is one-on-one with module-on-file, which creates a problem. For example lets say I have a Class Application as described in my other article, defined in Application.js

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
exports.Application = Application;

And now I try to make use in my Server as below

server.js
require('mootools');
var _Application = require('./Application');
 
var app = new _Application.Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Not so good, you see _Application.Application() to create the object, this is fine if you want to have module to be in its own context, but what about if you don't ? Lets check how to load the Application class in global context so you could create the object in old fashion way var app = new Application();

To do so, you do not have to export the class as before, so the new code becomes as follows

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});

Create one file Include.js with the following contents
 
Include.js
var fs = require('fs');
var vm = require('vm');
 
(function(){
 
var include = this.include = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
 
})();

And the server file with following contents

server.js
require('./mootools');
require('./Include');
include('./Application.js');
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

The Include.js file have a function include that does the job of loading the javascript file in global context. So you can access the class the good way.

Working with Mootools & NodeJS - Second Approach

In my last article here, I described how to make use of Mootools in a NodeJS applications. It included defining a class Application and then doing stuff with it. The class itself was defined in the same server.js file. This sometimes (very often for me) becomes a bottleneck as we start to work with one class per file approach. So, lets rewrite the program, create the file Application.js with following contents below
Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});

exports.Application = Application;

So, now the main file contains the code as below
Server.js
require('./mootools');
var _Application = require('./Application');

var app = new _Application.Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Working with Node.js & Mootools

This article will simply explain how to make use of Mootools with ServerSide JavaScript. I am focusing on NodeJS and will try to explain how to do it. I have worked on Mootools on client side in the past, but recently got a chance to work on NodeJS project, so it is based on my current experience with this project. Ok so lets get started with a simple example of creating a class, instantiating it object and calling some functions, here it goes.

server.js
require('mootools');
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

You must have Server Side mootools in the current working directory, downlodable from Mootools Site
Try running the code.

E:\mootools-node>node server.js
App initialize
App compute
App done

Thursday, January 26, 2012

Hello Eclipse

As a developer, you know that the first impression of a development framework is how easy it is to write "Hello, World." with Eclipse CDT as your IDE, because it provides a great plug-in that handles your project creation and management to greatly speed up your development cycles.

Ok, so lets start by opening Eclipse and creating new C++ project.

  • From the eclipse menu create new project, File --> New --> C++ Project
  • In the C++ Project dialog, put Project name as "HelloEclipse" & select Toolchain as "MinGW GCC" & press Finish.

Now we have to create a C++ file for us to write code into.

  • From the eclipse menu create new source file, File --> New --> Source File
  • In the new source file dialog, put the file name "main.cpp" and choose Template as "Default C++ source template" & press Finish.

Now lets put in some code to our source file

#include <iostream>
using namespace std;

int main() {
   cout << "Hello World!\n";
   return 0;
}

Build the project, from Eclipse menu do, Project --> Build All or (Ctrl+B)

Migrating from Visual Studio to Eclipse CDT

After working long with Mirosoft Visual Studio, it is usually very difficult to move on, work with an entirely new environment. I am too facing problems, no doubt Visual Studio is a wonderful tools, but I want to try with something new. I also work with some of the tools provided by Microchip & its just when I tried to download new IDE, I got to know they are moving on to Eclipse, wow! thats a big change, as far as I could recall, the IDE is based on Win32 & not Java. So, here I go, I decided to put away MSVC and use Eclipse CDT for the development work along with MinGW as compiler toolchain. I will also be using the GnuWin32, which is the collection of GNU utilities build to run on Windows platform natively.

The next part was to choose the opensource alternative for MFC, there are vaious to choose from, I loved Qt the most. Qt is known as a cross-platform graphical user interface toolkit. It is that, but it's also a toolkit for dealing with databases, file access, sockets, and much more. Qt is not only a concurrent of MFC. It is a full toolkit, with many features available in a simpler way than in MFC, and many that simply have no equivalent in MFC:

  • Controls: Qt is a graphical toolkit, so provides a rich set of graphical controls: labels, combo box, toggle buttons. Some of them are very sophisticated, like the listview which allow to have multi column list view with icons and toggle buttons.
  • XML: Qt provides classes to manipulate XML documents (using Sax2 or Dom). The tool is simple, powerful, complete and bug free.
  • Regular Expressions: Qt provides full support for perl-compatible regular expression. This goes far beyond the simple '?' and '*' meta-characters. Regular Expressions are a very powerful tool, to parse documents, to grep patterns inside documents, to build filters, to define masks for edit controls.
  • Multi-platform: Qt is multi-platform. It works on Windows (any of them), Unix (any of them), MacOs X and embedded platforms. You just have to recompile your code to get it working on a different platform. Except for the compiler adjustments (or limitations), you don't have to touch your code.
  • Template classes: Qt provides useful classes to handle lists, files, dictionnaries, strings, threads, etc. All of them are very powerful and very handy; more than the STL and the MFC equivalents.
  • Memory management: Qt has many facilities that makes memory management a no-brainer. Qt objects are automatically destroyed when their parent is destroyed. Many classes have an implicit sharing mechanism that relieves you from the pain of managing destruction and copy of these objects.
  • Network API: Qt features classes to help programming with Network programming: socket, dns, ftp, http.
  • Database API: Qt features classes for seamless database integration : Data aware wigets, database connection, SQL queries.
  • OpenGL API: Qt provides classes for seamless integration with OpenGL (3D accelearted) libraries.
  • Canvas: Qt provides classes optimised for handling quickly moving 2d objects, usually known as sprites.
  • Styles: It is possible to fully customize the rendering of all the Qt controls. That way, Qt emulates the style of all the available toolkits: Motif, MFC, NextStep, etc

To start with you need to download some of the tools as follows:

  • The latest build of Eclipse for C++ development, this includes CDT. Download from here.
  • Download and install the Qt build with MinGW from here.
  • Also install the Qt Integration Plugin for Eclipse, this will give you the liberty to play with Qt inside Eclipse.
  • Install the MinGW compiler, available from this location.
  • Download and install GnuWin32 packages available here.

Once you are all done with installations, you are all set to try the "Hello Eclipse !" tutorial.