Saturday, January 24, 2009

Live Event in Jquery

In latest version of jquery 1.3 i have seen interesting is the events which i would like to share with you. These events are the live and the die event which are new in the latest version of jquery 1.3. So in this post i will explain these two event handlers.

Live Event

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events. The Live event looks like this.

live( type, fn )

Where type is one of the events like click, dbclick etc. According to jquery website currently the event type which are supported by the live event are table 1
Event Type
Event Type
click
dbclick
mousedownmouseup
mousemovemouseover
mouseoutkeyup
keydownkeypress

Table 1 contain the list of event type which are currently supported by the live event handler. You can use one of the above mentioned event type in your live event handler to bind the event to the current element(s) or the element(s) which are added in future in the form. And the events type which are not currently supported is listed in the table 2
Event Type
Event Type
blur
focus
mouseenter
mouseleave
change
submit
And the second parameter to the live function is the function to be executed when the event type event is occured.
Now let us start our example of how to use the live event. In the example code i have added a paragraph tag and also two button which are used to bind and unbind the event, in this case i am using the click event type for the example.
$().ready(function()
{
var intCounter=1;
$("p").live("click", ParagraphClick);
$("#cmdBind").click(function ()
{
$("p").live("click", ParagraphClick);
});

$("#cmdUnbind").click(function ()
{
$("p").die("click", ParagraphClick);
});

function ParagraphClick()
{
$(this).after("Paragraph Number:"+intCounter+"");
intCounter++;
}
});
First what i did is to attach click event to the paragraph tag by using the live event handler , by passing the event type of "click" and the function name ParagraphClick funtion name, the paragraphClick function just add new paragraph after the clicking element by calling after function. Now if you click the first paragraph element which contain the text "Click me" which also have different background color, new element is added after the clicking element. Now if you click the new element it(click event of the paragraph) will add new element after the clicking element. Mean the click event which is attached with the first paragraph (which is the current element added at design time) is now also attached with the new element which is created by clicking on the paragraph element. Which is the definition of the live event handler (jquery)
"Binds a handler to an event (like click) for all current - and future - matched element."

Die Event

The die event handler will do opposite to the live event , it will unbind the event type.It has following form.

die([type], [fn] )

As from the above definition of teh die event, both parameters are optional, mean if you call the the die without any parameter it will unbind all the event which are bind using the live, and if you want to remove specific event for example click, dbclick etc then you can pass the type and it will unbind on that type of event handler, but if you provide the second parameter then it will unbind that specific event handler, not the other event handler which are attched using the live event.You can download the source code from here

All and any comments / bugs / suggestions are welcomed!

Sunday, January 18, 2009

Latest Version of Jquery

Today i am pleased to tell you that new version of jquery is released. The jquery latest version can be downloaded from the the jquery Web site. Amongst the other update in that release now they(jquery team ) has release the API Browser which looks like

The new API browser includes the following features:
  • All the latest jQuery and jQuery UI documentation.
  • The ability to mark pages as favorites for those pages you keep wanting to return to.
  • Syntax highlighting in the code examples
  • Live running of examples within the browser
  • Links to edit and experiment with the code examples

Most importantly though, the API browser is also available offline as an Adobe AIR application (thanks to Tane Piper’s AIR framework). The interface looks and works the same, and includes an auto-update mechanism, so you’ll always be up to date.

And at the end Happy 3rd birthday to the jquery :)

Double Quotes In VB.Net

In my Post Using Json In Asp.net , when writing the code for the example i choose VB.Net for developing the web application. During the application development i came across little problem to place double quotes around the string. As i am working in C# for last 2 and half year and still working in C sharp, the first thought which came to my mind was to place \" but i was wrong in thinking so. So i start searching how to place the double quotes around string in VB.net. During my Search i found ControlChars class which define the constants for the such characters. I have used the quote Constant in my code to place double quotes around my string.Here are some of the important constants in the class along with there description, i not mention all the constant.
VB.Net Value
Description
ControlChars.Cr
Carriage Return
ControlChars.LfLine Feed
ControlChars.CrLfCarriage Return|Line Feed
ControlChars.NewLineInsert New Line
ControlChars.Tab
Tab
ControlChars.Quote
Quotation mark character (" or ') used to enclose values.
ControlChars.Back
BackSpace
For C sharp developer you can use this class by importing Microsoft Visual Basic namespace which is "Microsoft.VisualBasic" , When you place the Microsoft.VisualBasic at the top of your file you can access the constants define in the ControlChars class. Or if you don't want to import the Microsoft.VisualBasic namespace then you can define your own class and define the constant like VB.Net.

All and any comments / bugs / suggestions are welcomed!

Friday, January 16, 2009

About MySelf

My name is Asim Sajjad and i am web developer, my interests are to learn new technologies and also to help the other developer in their problems, so anyone there who face difficulty or has problems related to the their development ( Web application or in desktop) please do post me your question i will try my level best to solve your problem.

Well about me , i have work in Microsoft Dynamics 3.0 and also 4.0 and i like Microsoft Dynamics technology and have 1 year and 6 month working experience in Microsoft Dynamics .The other field which i like most is the Web technologies like Asp.net, HTML, Javascript, Css, Jquery And my other skills are
  • C# (1.1,2.0,3.0)
  • VB.NET
  • Crystal Reports
  • Silverlight 3, 4
  • Microsoft CRM Dynamics 3, 2011
And latest about me is that i am trying to learn the Microsoft new technology WPF. My Favorite development language is VB.net but most of my work is in C# as i like the syntax of the C/C++ which C# has. You can say that i like both the C# and VB.net at the same time.


Thursday, January 15, 2009

Using Json in Asp.net Application

In this post i will try to explain you how you can use Json in your web application , So that you can response to the user request more quickly and avoid unnecessary postbacks. It is very basic article on json used in asp.net, and it is written for the reader who are not familiar with the json or did't know how to the json in asp.net or any of the web language.

What is Json

JSON, according to the official website for JSON, is a lightweight data interchange format that is a text-based, human readable format that is used to represent objects, arrays, and other data types that is mainly used to exchange such data types over the network.

If you look at the JSON site you can see that they have explain the format of data used in the json in great detail but i will explain you the basic data format supported by json. Data format consist of name/value format, where name is the you can use to get the value. And important point is the colon(:) sign between the key and value.

How to use Json

Let us start how can we use json in our web application. For this example of how to use json in web application i have used the "northwind" database and from that database i have used following tables
  1. "region" table which is used as the parent table
  2. "territories" table which is used as child table as it contain the regionid as foreign key in the territories table.
In the default page i have used two dropdownlist controls
  1. ddlRegion dropDownList which is used as parent control and it will be filled with the region from the default page , when the page is first loaded.
  2. ddlTerritory dropDownList which is used as child control and it will be filled when then onchange event is fired in javascript, by using ajax request.
For this example i have used vb.net as code behind language you can change it to your favorite language like C# or what ever you like. This is the some introduction of what i have used in the application so that you better know which controls and database is used in the application. Now let me explain you the core section of the application so that you will get understanding of it.
First of all set start with the ddlRegion dropDownList control which is used as parent control, i have attach the onchange event of the javascript event in the code behind file. Here i have passed the control itself to the ddlRegionChange function so that i can use it in that function.

ddlRegion.Attributes.Add("onchange", "ddlRegionChange(this)")
Now lets come to the ddlRegionChange function. Below is the definition of the ddlRegionChange function.
function ddlRegionChange(currentControl)
{
xmlHttp = getXMLHttpObject();

var intSelectedIndex = currentControl.selectedIndex;
var regionID = currentControl.options[intSelectedIndex].value;

var url="ResponsePage.aspx";
url=url+"?regionID="+ regionID;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
Let us start the coding of ddlRegionChange function . In the first statement i have initialized the xmlHttp which is declared globally. And i have used getXMLHttpObject() function which return the xmlHttp object,is used to check the browser and then initialized the xmlHttp object which is assign to the global xmlHttp object. In the second statement i have declared a variable called intSelectedIndex which is used to store the selected value of the ddlRegion( which is passed as parameter to the ddlRegionChange function. In the next statement i have declared and initialize regionID variable which will store the selected item value.In the next statement i have declared and initialized the url variable, which will call the ResposnePage.aspx and also passed the regionID as parameter and as usual i have passed the random number so that each time fresh requestion is passed to the ResponsePage.aspx.
Here is code of the ResponsePage.aspx , i have paste the function which is used to write json format data.
Private Sub getTerritory()
Dim strQuery As String = String.Concat("Select TerritoryID, TerritoryDescription from territories where RegionID=", intRegionID)
Dim getRegionConnection As SqlConnection = New SqlConnection(strQueryString)
getRegionConnection.Open()
Try
Dim getRegionCommand As SqlCommand = New SqlCommand(strQuery, getRegionConnection)
Dim getRegionReader As SqlDataReader = getRegionCommand.ExecuteReader()

Response.Write("[")
While (getRegionReader.Read())
Response.Write("{" + ControlChars.Quote + "TerritoryID" + ControlChars.Quote + ":" + ControlChars.Quote + getRegionReader.GetString(0).Trim() + ControlChars.Quote + ",")
Response.Write(ControlChars.Quote + "TerritoryDescription" + ControlChars.Quote + ":" + ControlChars.Quote + getRegionReader.GetString(1).Trim() + ControlChars.Quote + "},")
End While
Response.Write("]")

Catch ex As Exception
Finally
getRegionConnection.Close()
End Try
End Sub
In the above function i have stored the passed regionID in the global variable name intRegionID . In the first statement of the function i have construct simple select statement which will fetch territoryID and territoryDescription from territories table based on the regionID. Next i have declared the connection object and passed connection string to the connection object. after the connection obejct i have declared the command object and passed the query and also the open connecton object to the command object constructor. In the next statement i have declared the sqlDataReader object and call the ExecuteReader function of the command object to fetch the territoryID and the territoryDescription.
In the function i have used the while loop to construct the following format of the json data.
[
(Key) : (Value) , (Key) : (Value) (comma)
{"TerritoryID": "TerritoryID","TerritoryDescription": "Territory Description"},
{"TerritoryID": "TerritoryID","TerritoryDescription": "Territory Description"}
]
Here i have used TerritoryID as key and the value of that key value will be the TerritoryID fetched from the database and after comma i have TerritoryDescription key and the value of TerritoryDescription key will be the territory description fetch from the database. as i need territoryID and territory description as one set so i have enclosed them in right opening curly braces and end with right closing curly braces. after on obejct is constructed i have put comma(,) after that and the start with same steps as in the first to construct the second one and so on.

Here is code to the consume the json data which is return from the ResponsePage.aspx.
function stateChanged()
{
if (xmlHttp.readyState==4)
{
var ddlTerritory = document.getElementById("<%=ddlTerritory.ClientID%>");
var jsonObject = xmlHttp.responseText.parseJSON();
ddlTerritory.innerHTML ='';
for(var intCounter=0; intCounter< style="color: rgb(51, 51, 255);">var newOption = document.createElement("Option")
newOption.value = jsonObject[intCounter].TerritoryID ;
newOption.text= jsonObject[intCounter].TerritoryDescription;
ddlTerritory.options.add(newOption);
}
}
}

In the ddlRegionChange function i have assign the onreadystatechange of the xmlHttp object a function which will be executed when the state of the xmlHttp readyState is changed. Below is the statement to assign the function to the onreadystatechange of the xmlHttp object

xmlHttp.onreadystatechange=stateChanged;

when the function is called what we did is check reaystate of the xmlHttp object, here are the possible value of the readystate of the xmlHttp object.
readystate Value
Description
0
open has not yet been called
1
send has not yet been called but open has been called
2send has been called but no response from server
3
data is in the process of being received from the server
4
response from server has arrived
But we re interested in the readystate value 4 which indicate that our ajax request is successfully. Assuming the response from the server is formatted in a JSON string object, the code first grasps the response text by using the xmlHttp property called responseText. Once the text is available, the code parses the response text using the parseJSON() function. This function will convert any well-formatted JSON string object into a JSON object.Once we have a valid JSON object, we access the object properties the same way we access any C# or VB.NET object, by simply specifying the object name, a “.” and the name of the property. To fill the ddlTerritory dropDownList control i have used the TerritoryID and TerritoryDescription key value to get there values. You can download the json.js file from the here which is utility class prepared by the JSON team for the use of json .You can download the source code from here
All and any comments / bugs / suggestions are welcomed!


Tuesday, January 6, 2009

MultiLine TextBox Length Property Problem And Solution

In this article i will try to explain the problem when using the textBox as Multiline and set the MaxLength property , then the MaxLength property did not work. When an ASP.NET TextBox control is set to MultiLine mode, it is rendered as a TextArea HTML element. TextArea element do not support 'MaxLength' attribute, and therefore the TextBox won't render this attribute in MultiLine mode. It won't give you any warning or throw an error, but quietly ignore this property.
For the example i have created a TextBox and set the TextMode to the MultiLine and also set the MaxLength of the TextBox to 100 character.

Problem:

When you see the generated html of the page, you can see clearly that there is not MaxLength property for the TextBox. You can see that other properties are rendered but only property which we need is MaxLength is missing. Due to this you can enter as many character as you can in the textBox or you can say textArea control.In the Example i have the problem form which show you the real problem. You can see the html of the page by right clicking with mouse and then clicking the View Source of the page.

Solution:

Now let us turn to the solution of the problem. What you have to do is to set the properties of the textBox like TextMode, MaxLength in the property window. You set the properties of the MultiLine textBox normally as you do for the single line textBox.And then add the following javascript in the aspx page in the script tag.

function CharacterCounter(currentControl)
{
var lblCharacterCounter= document.getElementById("<%=lblCharacterCounter.ClientID %>");
var MaxLength=<%=txtValue.MaxLength %>;
lblCharacterCounter.innerText= currentControl.value.length;
if(currentControl.value.length > MaxLength-1)
return false;
else
return true;
}

function LimitPaste(targetField, sourceEvent)
{
var clipboardText;
var resultantLength;
var currentFieldLength;
var pasteAllowed = true;
var MaxLength=<%=txtValue.MaxLength %>;

// Get the current and maximum field length
currentFieldLength = parseInt(targetField.value.length);

clipboardText = window.clipboardData.getData("Text");
resultantLength = currentFieldLength + clipboardText.length ;

if ( resultantLength > MaxLength+1)
{
pasteAllowed = false;
}

lblCharacterCounter.innerText= targetField.value.length;
sourceEvent.returnValue = pasteAllowed;
return (pasteAllowed);
}


Above is the simple code for the keypress and paste event for the JavaScript. what is common in the both function is that i have get the MaxLength of the Multiline textBox by executing the server script and store the value in a variable for further use.
In the characterCounter function which is simple one , what i did in the characterCounter function is i have pass the control itself as parameter and then i have place the if else condition to return either true or false depending on the result whether the textBox value is greater then the MaxLength property or not. If it is not greater then the MaxLength then return true mean to accept the character and if the value is greater the the MaxLength then return false mean not to accept the character.
In the LimitPaste function i have pass two parameter one is the control calling the function, second is the event which is fired. This function is also simple one, let me explain you the main functionality of the function. what is important to be noted in the function is the clipboardText = window.clipboardData.getData("Text"); in this line i have get the get the Text which is selected from window.clipboardData.getData("Text") and store it in the local variable. In the next line i have store sum of the textBox value length and length of the clipboardText. Then i have place the if condition to check the if the resultantLength is greater then the MaxLength value if yes then assign false to the pasteAllowed flag.

At the end here is the code you can bind the onkeypress and onpaste event for the textBox in the cod behind file.I have use the VB.net hope you can easily convert it into C# or your favorite language.
txtValue.Attributes.Add("onkeypress", "return CharacterCounter(this);")
txtValue.Attributes.Add("onpaste", "return LimitPaste(this, event);")
Hope this will solve you problem if you have any question please ask me.You can download source code from by Clicking here

Sunday, January 4, 2009

Jquery for Beginners: Events Handling Part 2 (Continue)

In previous post Jquery for Beginner: Event Handling Part 2 i have give complete list of events which are available in jquery. In previous post i have discuss the event which are related with the mouse, but in this article i will discuss events which are related to the keyboard. The keyboard events are
Event NameEvent Name
keydown()keydown(fn)
keypress()keypress(fn)
keyup()keyup(fn)
Above are the list of events which are related to the keyboard. Let us start with keydown event which is fired when any of the keyboard key is down. The syntax for calling the event is as below.
$(document).ready(function()
{
$('#txtValue').keydown(function(passedEvent)
{
alert(passedEvent.keyCode);
});
});
Above code is simple example of how you can bind the keydown event handler with any of the input control you have on your web page. In the above code i just output the keyCode which is the property of the event, which is passed as argument to the keydown function. The event name is optional, if you don't want to pass the parameter you can remove the parameter. But if you need to know which key is press or some additional information when the key is down then it is helpful to pass the event.
Property
Description
altKeyValue will be true if alt key is press else false.
ctrlKeyValue will be true if ctrl key is press else false.
shiftKeyValue will be true if ctrl key is press else false.
keyCodeThis Property hold the value of the key in numeric format.
whichThis property hold the value of the key in numeric format, in case of key board event.
metaKeySet to true if the Meta key was pressed when the event was triggered, false if not.The Meta key is the Ctrl key
on PCs and the Command key on Macs
In the above table , these are the some of the properties which are available when event is passed to the function which is bind with the event. Importantly, the keypress property isn’t reliable cross-browser for non-alphabetic characters. For instance, the left arrow key has a code of 37, which works reliably on keyup and keydown events. Safari returns nonstandard results for these keys on a keypress event. We can get a reliable, case-sensitive character code in the which property of keypress events. During keyup and keydown events, we can only get a case insensitive key code (so a and A both return 65), but we can determine case by checking shiftKey. The Event instance contains not only properties that give us information regarding the event that’s handled, but also possesses a handful of methods that lets us control the propagation of the event.
The which property which is used to hold the value of the key in numeric format. And if the event is cause by the mouse then it will hold the value of the mouse key which is
  1. 1 for left mouse key
  2. 2 for middle mouse key
  3. 3 for right mouse key.

Key press:

The keypress event is fired after the keydown event. This is similar to the keydown event, except in the case of key repeats. The keypress and keydown event are similar but there is difference in between these two, the keydown event is fired if you press modifier keys such as shift key.But the keypress event is not fired if you press the shift key or ctrl key(control key).
One important thing to remember is that keydown and keyup event handler will give you the code which key is press which include the shift, ctrl key as well, But the keypress event key code indicate which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 97 by all events. This can be the primary motivator for deciding which event type to use.

key up:

The keyup event is fired after the keypress event.The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.


You can download source code from by Clicking here
back to content

Thursday, January 1, 2009

Jquery , Ajax Update Panel Problem and Solution

In this article i will share my experience of using the Jquery with the Ajax UpdatePanel and the problem i have faced when using the both at the same time. I will try to explain the problem and then i will give you the solution of the problem in simple manner so that you understand it clearly.

The Problem

In the example which i will use contain one dropDownList , a label to show the selected value of the dropDownList and a button which bind the jquery click event. All the three controls are inside the Ajax UpdatePanel. This is the simple example to show you what is the problem when using Jquery and Ajax UpdatePanel at the same time. So when i run the web application and page is loaded in my browser first thing i do is to click on the button, and it display the message 'From ready Function' is displayed, but when the selectedIndex changed event of the dropDownList is fired and the page is partial postback, and now if i click the button again no message is displayed. Due to the partial postback, UpdatePanel completely replaces the contents of the UpdatePanel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.

$().ready(function()
{
BindEvents('From ready Function');
});


function BindEvents(strPassedValue)
{
$('#cmdClickMe').click(function()
{
alert(strPassedValue);
});
}

So the jquery click event which was bind when page was first requested is not any more attached with the button. So we need to bind the click event again with the button.

Solution

The solution to the above problem is very simple one what you have to do is to place the below function just after the ContentTemplate tag inside the UpdatePanel. Here what i did is the call the BindEvents function which is also called when the ready() function of the jquery is executed. So when the partial postback end we capture the endRequest event and then call the function which will bind the event again. now if you repeat the cycle which i have mention in the problem section then you can see
  1. when page is loaded first time if we click the button then it will display message 'From ready Function'.
  2. Now if you click the dropDownList then it will display the selected value from the dropDownList in the label and the partial postback occurred.
  3. Now if you click the button again then you can see the message 'From add_endRequest called!' which mean the event is bind from the add_endRequstion function.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function()
{
BindEvents('From add_endRequest called!');
});

This is the simple application to let you know what is the problem and how can you solve that problem. Hope this will solve your problem.

You can download source code from by Clicking here