Uncategorized

Node : Express app with Swig

Today , I will write about a Template Engine for Express App.

And This is Swig – A simple, powerful, and extendable JavaScript Template Engine.

Its Data Binding Syntax is like Angular, And I liked it, its really simple and fun.

This is how we can configure Swig in our Express App-

var cons = require('consolidate');
 
var app = express();
app.engine('html', cons.swig);
app.set('view engine''html');
app.set('views', __dirname + "/views");
 
app.get('/'function (req, res) {
    res.render('index', { name: 'Shahjada' });
});
 
var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

And our html is like below as simple –

<h1>Hello {{name}}</h1>

 
Its easy , right ?

Cheeers

Standard
Uncategorized

NodeJS : Connect MongoDB and get Data from Collection

In any Web application , its important to connect to Database for data .

In MEAN , as we use MongoDB , so I will write code how a Node app can talk with MongoDB Database.

I have a Database named newDB and I have a collection named myColl in my local MongoDB server.

Like below , we can connect and get data from Mongo Server.

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/newDB'function(err , db) {
 
	if(err) {
		console.log(err);
		throw err;
	}
	
	db.collection('myColl').findOne({} , function(err , doc){
	
		if(err) {
			console.log(err);
			throw err;
		}
		console.dir(doc);
		db.close();
		//res.send(doc);
	});
 
	console.dir("Called FindOne");
});

Hope this Helps.

Standard
Uncategorized

ExpressJS – Configure Routing for Express App

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Express is the most popular Web Framework on Node . So, I planned to write on Express and personally I am a MEAN (Mongo, Express , Angular , Node) Stack fan and MEAN stack became much powerful in Modern Web World.

This article shows how we can configure the routing for an Express app.

var express = require('express');
var app = express();
 
app.get('/'function (req, res) {
	res.send("Home");
});
 
app.get('/profile'function (req, res) {
	res.send("Profile");
});
 
app.get('/contact'function (req, res) {
	res.send("Contact");
});
 
app.get('*'function (req, res) {
	res.send("Not Found" , 404);
});
 
var server = app.listen(3001, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Express app listening at http://%s:%s', host, port);
});

The code is itself self explanatory . I have created 3 Routes and if User hits any other route beside these , Express will return “Not Found” with 404 Status which has been maintained by *

Here we can see server is listening to 3001 port , make sure to use that port which is empty

app takes 2 arguments , first is the route path and second is the callback which would be fired when that Route has been hit by User.

Hope this helps.

Cheers

Standard
C#

Gravatar – Get avatar by email in C# and check available or not

gravatar.com is very popular now a days. So many large sites use this feature . I needed this feature in one of my working projects

But I needed to check also that email exists in Gravatar or not. If Gravatar does not have that email Id of the user , The app will show its custom Image . But If we call the Gravatar API , Gravatar sends a default image if that email is not available which was not our app’s behavior , so I needed to track and validate that.

UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(email));
            StringBuilder sb = new StringBuilder(hashedBytes.Length * 2);
            for (int i = 0; i < hashedBytes.Length; i++)
            {
                sb.Append(hashedBytes[i].ToString("X2"));
            }
            var imageHashCode = sb.ToString().ToLower();
            string gravatarImageUrl = "http://www.gravatar.com/avatar/" + imageHashCode + "?d=404";
            var uri = new Uri(gravatarImageUrl);
 
            using (WebClient client = new WebClient())
            {
                try
                {
                    var imageByte = client.DownloadData(uri);
                    var headers = client.ResponseHeaders;
                    if (headers != null && headers["Content-Disposition"] != null)
                    {
                        var header = headers["Content-Disposition"];
                        if (header.Contains(imageHashCode))
                        {
                            MemoryStream memoryStream = new MemoryStream(imageByte);
                            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(memoryStream);
                            BitmapSource image = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                            return image;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
                return null;
            }

Check the URL generation part in the code , I have used ?d=404 . This is the main thing which does the trick so that it returns 404 if that email address does not belong to Gravatar

But if anyone needs the default behavior of Gravatar , then just remove ?d=404 from the URL . It will show the default image if the email is not available.

Hope , this helps.

Cheers

Standard
AngularJS

Apology for not being regular here !

I know and I agree , I was not so much active in writing articles in 2014 ,In fact I was too much busy/sad/frustrated with so many things( New Language/frameworks are also parts of these).

I am planning to be more dedicated on writing new Articles in 2015. And I really need to thank to all the people of the world who visited my site in 2014.

And WordPress sent me an annual report that my site got traffic from 155 countries in 2014 which made me much confident and forced me to be more dedicated here.I thank you all.

Here is the public report : https://shahjadatalukdar.wordpress.com/2014/annual-report/

In 2015 , I am planning to write articles on MEAN stack (Mongo , Express , Angular , Node) .

I have already few articles on Angular.And Will continue more. Please visit/subscribe/like/comment on articles . I really appreciate your valuable comments/suggestions.

Cheers

Shahjada

Standard