Hiteshagja.com
Knowledge is power
Show MenuHide Menu

Node.js Video Tutorial 1 of 8 – Introduction to node.js

April 26, 2013

In this

Node.js Video Tutorial

you will get an idea about how node.js works. You will also get an idea about how to install node.js. Using 5 lines of code you can create your own up and running web server.

get source code

Video by node.js creator himself. Video is is almost more than 1 hour long but I can guarantee you that you will know what you should know about before digging into node.js

What kind of application you can create in node.js
My answer is almost almost any application. You can create

  • Stock Market Application
  • Real Time News
  • Project Management Application
  • Web Based Game

or any application you can think of. Node.js is very fast try it and see what node.js can do for you.

Comment your thoughts.

Geographical SVG Map With Example

April 6, 2013

In web if you want to provide any geographical svg map related solution then consider map as some random shape. Every map is nothing but a random shape. And in web if you want to draw any shape SVG is the best option. SVG stands for Scalable Vector Graphics.

But to draw shape like this will require lot of skill and time. So, I find one website which gives us almost all countries detailed map in different formats like GIF, PDF, SVG and many other.

Please visit d-maps.com

I have taken India map from d-maps.com. This is SVG map.

Rest is depending upon your logic. :)

SQL Group By Age Range

March 29, 2013
SQL Group By Age Range

SQL Group By Age Range is tedious task because there is no direct method exists. So you need to apply some logic to get your desired result.

Let’s say you want to find total visitors count by specific age group.

For example result you want is something like
SQL Group By Age Range Output

Approach which I would suggest is simple and at the same time gives you facility to change age group range dynamically without changing your SQL query.

You have to do following things
1. Create master table for age group as shown below.
Create SQL Group By Age Range Master Table

2. Insert range data
Insert SQL Group By Age Range Master Data

3. Write SQL query using JOIN.

SELECT B.[RANGE] AS [Age Group(in Years)],COUNT(A.pk_ID) AS [Total Visitors]
FROM dbo.tbl_visitors A
RIGHT JOIN dbo.mstRange B ON A.AGE BETWEEN B.MINVALUE AND B.MAXVALUE
GROUP BY B.[RANGE],B.MINVALUE
ORDER BY B.MINVALUE

done !

Share your views!

Apply Culture In Silverlight Application

September 1, 2012

Culture In Silverlight Application plays a very important role. Silverlight application always sits on client browser and works as a plug-in. So you always need to keep in mind that control panel setting of different user might be different especially regional and language settings. Different user on different countries uses different date, time and number formats so while building Silverlight application you have to consider this fact and build your application accordingly and you need to make sure that you have applied culture in Silverlight application.

Recently I come across issue where application uses M/d/yy format date throughout application and it worked fine till user had not changed anything from regional settings. When user changed short date time format from control panel > regional and language settings application started giving errors of bad date and time. So I needed to apply default en-US culture in my application to resolve this issue. What I have done is I have applied en-US culture in current thread on application startup i.e. app.xaml.cs.

Here is the code for the same.

private void Application_Startup(object sender, StartupEventArgs e)
{
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("en-US");
c.DateTimeFormat.LongDatePattern = "dddd, MMMM dd, yyyy";
//YOU NEED TO PROVIDE ESCAPE SEQ IF YOU ARE USING SLASH IN YOUR FORMAT
c.DateTimeFormat.ShortDatePattern = "M\\/d\\/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = c;
System.Threading.Thread.CurrentThread.CurrentUICulture = c;
}

I hope this will help others to solve the same problem.

JSON in Javascript Explained

August 15, 2012

What is JSON in Javascript?

JSON stands for Javascript Object Notation. JSON is nothing but an object which contains key value pairs. Advantage of JSON over other data format is it is lightweight. JSON is platform independent as well as language independent data exchange format.

JSON object example

Example:

var jsonObj = {id:1,name:”hiteshagja”};

In this example Keys are id and name and Values are 1(typeof int), hiteshagja(typeof string).

So If you write alert(jsonObj.name) in javascript you will get alert containing text hiteshagja. Isn’t this so amazing about JSON.

Add New Property(key) to already existing JSON object.

Example 1:

jsonObj.email=”hiteshagja24@gmail.com”;

Or

jsonObj[“email”]= ”hiteshagja24@gmail.com”;

This will add new key email to already existing jsonObj. You don’t need to write anything else other than this.

But if you write like

Example 2:

jsonObj.name=”hiteshagja.com”;

Or

jsonObj[name]=”hiteshagja.com”;

This will only update our JSON object key value from hiteshagja to hiteshagja.com.

JSON currently supports

String
Number
Object
Array
Boolean
Data types and
Null value

Get JSON object’s keys count

Object.keys(jsonObj).length

will return number of keys in given JSON object. In our case this will return 3(id,name and email).

Delete key

delete jsonObj[“email”]

this will remove email key value pair from jsonObj. Delete is a keyword which will accomplish this task.

String to JSON object

Example:

var jsonStr=’{“id”:”1”,”name”,”hiteshagja”}’;

Let’s say you have string value just like shown above and you want to convert it into JSON object.

var

jsonObj=JSON.parse(jsonStr);

Or

var jsonObj=eval(jsonStr);

will convert JSON string into object.

JSON object to String

In some cases you will be needed converting JSON object into string there you can use conversion like shown below.

Example:

var jsonStr= JSON.stringify(jsonObj);

This will convert jsonObj into string.

JSON Array

Till now you have seen how to create single JSON object. Now in some cases we will need to store data as an array. Let’s see how we can do so.

Example 1:

var jsonObj={id:1,name:”hiteshagja”,phone:[1111111111,2222222222]};

Here as you can see I have written phone value as an array.

You can access phone number using jsonObj.phone[0] just like you are accessing other array objects.

Example 2:

var jsonObj={

Products:[ {name:”Product1”

color:”Red”

code:1},

{name:”Product2”

color:”Green”

code:2},

{name:”Product3”

color:”Blue”

code:3}]

};

Example 2 is real time scenario where you will have array of products. jsonObj is array of products which contains 3 products in our example.

If you want to access product 2 then you can simple write

Products[1][Key].

I will keep updating this post whenever I will find anything interesting about JSON.

jQuery Signature Pad using HTML5 Canvas

February 25, 2012

With introduction of HTML5 Canvas we can easily create jquery signature pad plug-in. This article is all about jquery based signature pad that works in almost all modern browsers.

Recently I come across situation where I need to provide browser based Signature Pad and It should work fine in all the devices including apple devices. So I don’t have any other option left then HTML5 Canvas.

If you want to create a browser based signature pad then visit the link below.

http://thomasjbradley.ca/lab/signature-pad/

To save signed signature visit the link below. (CODE IS IN C#)

http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx

Silverlight – Listbox Scrollbar Problem

June 23, 2011

Recently I have observed that listbox scrollbar has virtualization problem when we re-bind listbox. Let me explain this with an example.

I have added 50 items into listbox control programmatically. Here is the screenshot for the same.

Image after 50 Items bound to listbox

Normal Listbox Binding

Re-bind listbox

Re-bind button click without scroll bar move

As you can see I have added two buttons to Reset and to Re-bind listbox again.

If I click on any of the button everything will work as expected but real problem is when we move scroll bar to bottom of the listbox and we re-bind listbox data.

See what kind of problem you shall face.

Problem displaying data

Solution :

Use scrolltoview function after assigning ItemsSource to listbox. See code snippet below.

[sourcecode language="csharp"] List<ListBoxItem> a=GetItemsList(txt,count);

listbox1.ItemsSource = a;

if(a.Count()>0)

{

listbox1.UpdateLayout();

listbox1.ScrollIntoView(a[0]);

}

[/sourcecode]

Dealing with DateTime Formats in C#

June 8, 2011

Dealing with datetime formats in C# is very easy if you use framework functions properly. Recently I come across very ugly error which makes my application crashed. Actually it was problem converting DateTime for specific format. You should make your DateTime conversion independent of client computer’s culture setting. This thought in mind I am going to present this post.

1.       Convert String  to DateTime

Let’s take an example:

Suppose you have

[sourcecode language="csharp"] String strDate = "10/23/2011"; [/sourcecode]

Which is in MM/dd/yyyy format and you want to convert it in DateTime variable then you should write like

[sourcecode language="csharp"] DateTime dt = Convert.ToDateTime(strDate,System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

You could write above code if you are sure that the format is in MM/dd/yyyy. If the format is in say dd/MM/yyyy then DatTime.ParseExact is the perfect option for you.

Code above can be rewritten as

[sourcecode language="csharp"] DateTime dt = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

In all above code lines I have mentioned System.Globalization.CultureInfo.InvariantCulture parameter, which will make date format, culture independent.

2.       Convert Datetime to Specific Format

Let’s say you have

[sourcecode language="csharp"] DateTime dt = DateTime.Now; [/sourcecode]

and you want to convert it in different format. 

Example : Format : dd-mmm-yyyy

[sourcecode language="csharp"] String s = dt.ToString("dd/MMM/yyyy"); [/sourcecode]

But this will be overridden by current culture.

So you should do something like this

[sourcecode language="csharp"] String s = dt.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

In short, CultureInfo parameter plays an important role.

Run Executable (exe/bat) file from Web Page

August 22, 2010

To run an exe from your web page is quite easy process. I have used simple JavaScript to accomplish this task. Have a look at the code listed below.

[code lang="javascript"]
function WriteToFile() {

var fso, s,folderName;

fso = new ActiveXObject("Scripting.FileSystemObject");

if (!fso.FolderExists("C:\HITESH"))

{

folderName=fso.CreateFolder("C:\ HITESH ");

}

if (!fso.FileExists("C:\ HITESH \LaunchApp.bat")){

s = fso.OpenTextFile("C:\ HITESH \LaunchApp.bat" , 8, 1, -2);

s.writeline("IF EXIST d:\hitesh GOTO LABEL1”);

s.writeline("IF EXIST k:\hitesh GOTO LABEL2”);

s.writeline(":LABEL1”);

s.writeline("D: ”);

s.writeline("D:\hitesh\AppTest.EXE”);

s.writeline("EXIT”);

s.writeline(":LABEL2”);

s.writeline("K: ”);

s.writeline("K:\hitesh\AppTest.EXE”);

s.writeline("EXIT”);

s.Close();

}

}

function LaunchApp() {

WriteToFile();

var oShell = new ActiveXObject("WScript.Shell");

var prog = "C:\ HITESH \LaunchApp.bat";

oShell.run ('"'+prog+'"',1);

}
[/code]

This javascript will create an object of WScript.Shell and will execute DOS based batch file. In addition with this I have also created LaunchApp.bat file programmatically if it does not exist on the client side (So you don’t need to worry about whether file exist or not J). This file will execute EXE depending upon conditions specified in the LaunchApp.bat. LaunchApp() is the starting point.

Populate data in Gridview using jQuery AJAX

August 9, 2010

I search a lot in Google for a whole day but didn’t find any perfect example to populate data in gridview using jquery ajax. Then I have decided to do it myself and I find it easy at the end of the day.

In the example which I illustrated below follows the flow:

  1. On document ready method it initiates jQuery AJAX call.
  2. Response will be redirected to the ASPX page and in tern server will respond with JSON data.
  3. jQuery AJAX call back success method used to generates HTML Table with data.
  4. Add HTML to DIV.

Here is the code:

Default.aspx

[code lang="html"]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script src="js/commons.js" type="text/javascript"></script>

</head>

<body>

<form id="form1" runat="server">

<div id="divperson">

<strong>[Newly generated HTML will seat here]</strong>

</div>

</form>

</body>

</html>
[/code]

Default.aspx.cs

[sourcecode language="csharp"]
public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

if (Request.QueryString["id"] == "person")

GetString();

}

}

public void GetString()

{

JavaScriptSerializer _serializers = new JavaScriptSerializer();

string _personJSON = _serializers.Serialize(Person.GetPersonDetails());

Response.Clear();

Response.Write(_personJSON);

Response.End();

}

}

<strong>//Person Class and Members</strong>

public class Person

{

public string Name { get; set; }

public string State { get; set; }

public string PhoneNumber { get; set; }

public Person(string name, string state, string phone)

{

Name = name;

State = state;

PhoneNumber = phone;

}

public static List<Person> GetPersonDetails()

{

List<Person> _person = new List<Person>();

_person.Add(new Person("Hitesh", "Gujarat", "123"));

_person.Add(new Person("Urvish", "Maharastra", "345"));

_person.Add(new Person("Deepak", "Madhya Pradesh", "456"));

return _person;

}

}
[/sourcecode]

I just created Person class, created some properties and a static method to generate list of Person class objects. You need to include System.Collections.Generic and System.Web.Script.Serialization name space for List Class and JavaScriptSerializer class respectively.

In Page_Load method, based on the querystring value the GetString() method will call and JSON response will be generated and submitted as response. You need to catch this response on client side to retrive values within JSON formatted data.

commons.js (a separate JS file)

[code lang="javascript"]
$('document').ready(function(){

$.ajax({

type: "GET",

data:({id:"person"}),

url: "Default.aspx",

dataType: "json",

success:function(resultdata){

var person;

var _html='<table border="1">';

_html += '<tr>';

_html += '<th>Name</th>';

_html += '<th>State</th>';

_html += '<th>Phone</th>';

_html += '</tr>';

for(index in resultdata)

{

_html +='<tr>' ;

_html +='<td>' + resultdata[index].Name + '</td>';

_html +='<td>' + resultdata[index].State + '</td>';

_html +='<td>' + resultdata[index].PhoneNumber + '</td>';

_html +='</tr>' ;

}

_html +='</table>' ;

$('#divperson').html(_html);

}

});

});
[/code]

Nothing fancy, using jquery.ajax method I made a GET request to Default.aspx page with some data. Page has return JSON data which I parsed in jquery.ajax success method.

Before you attempt to run this code in your app, make sure you have included jquery-1.4.2.min.js file.