AngularJS, JavaScript

AngularJS One Time Binding Concept

Angular 1.3 added a new feature called One Time Binding . This is definitely an awesome enhancement for performance of an angular app.

We know , If a data changes in angular app, The $digest cycle checks for changes through watchers and gets the new value and renders the view. But if the app gets bigger with so many data , so many bindings , the $$watchers count increases with $digest loop size. Though in a large collection only few data got changed but the whole data gets rendered which is not good for performance.

One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value

The main purpose of one-time binding expression is to provide a way to create a binding that gets deregistered and frees up resources once the binding is stabilized. Reducing the number of expressions being watched makes the digest loop faster and allows more information to be displayed at the same time.

Lets see how we can do this in angular app.

<div>
        <h1>Angular OneTimeBinding</h1>
        <br />
        <table>
            <tr ng-repeat="profile in profiles">
                <td>
                    {{::profile.Id}}
                </td>
                <td>
                    {{::profile.Name}}
                </td>
                <td>
                    {{::profile.Address}}
                </td>
            </tr>
        </table>
        <br />

        <button ng-click="addProfiles()">addProfiles</button>
        <button ng-click="getWatchers()">getWatchers</button>

        <div>
            <h3>OneTimeBinding Watchers Count :::  {{totalWatchers}}</h3>
        </div>

    </div>

Here I added {{::}} this syntax for One Time Binding.

Lets see our Controller’s code-

app.controller('profileCtrl' , ['$scope' , function($scope){
    console.log('profileCtrl is running...');

    $scope.profiles = [
                    { Id: 1, Name: 'Masoom', Address: 'Dhaka1' },
                    { Id : 2 , Name : 'Talukdar' , Address : 'Dhaka2' },
                    { Id: 3, Name: 'Shahjada', Address: 'Dhaka3' }
    ];

    $scope.addProfiles = function () {
        var id = $scope.profiles.length + 1;
        $scope.profiles.push({ Id: id, Name: 'AAAA' + id, Address: 'Dhaka' + id });
    };

    $scope.getWatchers = function () {
        var watchers = ($scope.$$watchers) ? $scope.$$watchers.length : 0;
        var child = $scope.$$childHead;
        while (child) {
            watchers += (child.$$watchers) ? child.$$watchers.length : 0;
            child = child.$$nextSibling;
        }
        $scope.totalWatchers = watchers;
    };

}]);

Here If we add a new profile by clicking the addProfile Button , it will add a Row , but the Watcher Count will not increase as its One Time Binding But if we remove the OneTimeBinding Syntax , I will increase the count which hampers the performance.

And, if we do not use One Time Binding in Property Level , but in Collection level like below , then If we click and click addProfile button , it will add new item in the collection inside $scope , but the UI will not render the new Items coz we have used OneTimeBinding in the Collection/List Level.

<table>
            <tr ng-repeat="profile in ::profiles">
                <td>
                    {{profile.Id}}
                </td>
                <td>
                    {{profile.Name}}
                </td>
                <td>
                    {{profile.Address}}
                </td>
            </tr>
        </table>

Hope , It helps you.

Cheers

Standard
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
AngularJS, ASP.Net MVC, JavaScript, jQuery, jQuery AJAX, MVC WebAPI

Add Request Header for REST API Calling with AngularJS & jQuery

In the Web World , We always call REST APIs from our Web Applications .

When We call REST APIs through jQuery or AngularJS , they added few default Request Headers .

But many a time , we need to pass Custom Request Headers for different purposes.

A Common scenario is for Authentication we need to pass Customer Request header .

But how we can add this ?

Lets see the below samples :::

for jQuery , we can easily add Request Headers when we do AJAX Calling .

$.ajax({
            type: "POST",
            url: '/api/test',
            data: myObj,
            headers: { 'Custom-Header': 'Value'},
            success: function (resp) {
                alert(resp);
            },
            error: function (x, y, z) {
                alert(x);
            }
        });

In AngularJS , If we use $http for REST API calling , we can add Request Header like below , after we create AngularJS Module , we can do :::

myModule.run(['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';
        }]);

Thanks

Standard
AngularJS, HTML5, JavaScript

WebSQL : Welcome to client side DB – Part1

I think , We,all the Devs, know about SQL . Like , we have already worked with MySQL , MS SQL Server etc .

But then what is WebSQL ? If I say in a simple statement – WebSQL is SQL which is available in Client Browser .

Inside Browser :S ? Where is it ? I never saw that :@

Then please see the below image 🙂

WebSQL in Chrome Browser

WebSQL in Chrome Browser

Now lets begin…

With HTML5, there was also a desire to develop applications so that they’d run off-line. Where could they store data when there is no Internet?

Currently , we can store Data in browser in the below ways –

1.Local Storage
2.WebSQL
3.IndexedDB

You can get few browsers do not support all these , like previous versions.

LocalStorage can store data in Key-Value pairs but nothing more than that.To know more about LocalStorage , you can check out my another Article on LocalStorage .

WebSQL is based on a free database product called SQLite which is written in C , Go here

In a WebSQL Database , we can create DB and Tables kinda like MySQL or SQL Server and store Data in the same manner what we knew earlier 🙂

Lets do some Coding…

I have used WebSQL in a AngularJS application . I have created an Angular Service which is separated from another Controllers and can be injected in any controller when needed where I have used WebSQL APIs .

Below is the code of my Service…

app.service('WebSqlDbService', function ($resource) {

    this.createDbAndTables = function () {
        var db = openDatabase('myClientDB', '1.0', 'Mobile Client DB', 2 * 1024 * 1024);
        db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS User (UserInfo)');
        });
    };

    this.storeUserInfo = function (user) {
        var db = openDatabase('myClientDB', '1.0', 'Mobile Client DB', 2 * 1024 * 1024);
        db.transaction(function (tx) {
            tx.executeSql('INSERT INTO User (UserInfo) VALUES ( ?)', [JSON.stringify(user)]);
        });
    };

});

Then I have used WebSqlDbService in my Controller and called the Functions of the Service something like this…

$scope.userInfo = {
            UserId: 'as34fsdf*i#sad454',
            UserName: 'shahjada',
            IsAdmin: true
        };

        webSqlDbService.createDbAndTables();
        webSqlDbService.storeUserInfo($scope.userInfo);

I have saved the JSON Object by Stringifying , and when we will get this from WebSQL , we will convert it to JSON Object…

After saving Object to WebSQL DB , my DB and Table looks like below…

WebSQL in Chrome Browser - DB and Tables

WebSQL in Chrome Browser – DB and Tables

We can also write SQL Queries like SQL Server Management Studio…

Just follow the Image below…

WebSQL in Chrome Browser - SQL Queries

WebSQL in Chrome Browser – SQL Queries

Its nice and cool , right ?

I will write another Article on IndexedDB very soon .
Keep an eye on my Blog Site , Share/Subscribe…

Thanks and regards

Standard
AngularJS, ASP.Net MVC, jQuery AJAX, MVC WebAPI

Delete Functionality : REST API with AngularJS $resource and jQuery-Ajax

For every Web Application , an important feature is Delete Functionality . We can not think a single app without it . But we already know how to develop DELETE Functionality inside a Web App . Then why is this article for?

Well , that’s true . But now , we will see how we can develop DELETE Functionality with $resource of AngularJS and/or also with jQuery . and for both cases , we have a REST URL of the server which is doing the real back-end thing .

Lets jump…

First lets see the Server code of REST API Delete Functionality . Here I have used .Net WebAPI . And the Method looks like below :::

public HttpResponseMessage Delete(int id)
        {
            //Delete Related Logics + Data Access calling etc
            return Request.CreateResponse(HttpStatusCode.OK);
        }

Now lets see the client side function of DELETE which is using AngularJS $resource .

$scope.delete = function() {
        $resource('api/Ticket/:id').delete({ id: $scope.ticket.Id }, function (data) {
            alert('Succeeded');
        });
    };

We can do the same thing by jQuery also , if we do not use AngularJS . But after learning AngularJS , you will never use jQuery 🙂 For jQuery lovers , we can do this like below with jQuery Ajax:::

$scope.delete = function () {
        $.ajax({
            url: 'api/Ticket/' + $scope.ticket.Id,
            type: 'DELETE',
            success: function (data) {
                alert('Succeeded');
            },
            error: function (x, y, z) {
                alert('Failed');
            }
        });
    };

Well , Thanks . Hope , you liked it .If you do , please share / subscribe …

Cheers 🙂

Standard
ASP.Net MVC, EntityFramework

EntityFramework in C# – Part2 : Calling MS SQL StoredProcedure

While we use EntiryFramework as ORM , we can use/call MS SQL StoredProcedure in our C# code . EF allows us to import StoredProcedures into our C# app as Functions .

Now I am gonna show , how we can use SP in EF . To know basic EF,please refer to my another article EntityFramework in C# – Part1 : Welcome To EF

For this demo , I have a simple SP which will return the data from a table.

StoredProcedure for EF in C#

I will fill an ASP.Net Grid with that data , and I am gonna pull the data using EF .

For this, after taking the update of EDMX , I will get the StoredProcedure inside the EDMX , and will add a Function for that SP like below —

EF - Add Function Import

Click Add Function Import and then…

EntityFramework with StoredProcedure - Function Import

Our SP is now ready in our app as a Function and we can just call that function as usual as we do.So my C# code for calling the function is like below :::

ImportantDBEntities dbEntities = new ImportantDBEntities();
            
            //Execute stored procedure as a function
            var employees = dbEntities.GetEmployees();
            if (employees != null)
            {
                employeeGrid.DataSource = employees;
                employeeGrid.DataBind();
            }

So our Grid is ready with data 🙂

Cheers

Standard