Thursday, December 25, 2008

Jquery for Beginners: Events Handling Part 2

This is the second article of the Jquey for Beginners: Event Handling. In the first Article i give some information how you attach the event with the controls. Here is the list of the some of the event helper Table 1.

Event NameEvent Name
blur()blur(fn)
change()change(fn)
click()click(fn)
dbclick()dbclick(fn)
error() error(fn)
focus()focus(fn)
keydown()keydown(fn)
keypress()keypress(fn)
keyup()keyup(fn)
load(fn)unload(fn)
mousedown(fn) mousemove(fn)
mouseout(fn)mouseover(fn)
resize(fn)scroll(fn)
select()select(fn)
submit()submit(fn)
hover(handlerIn, handlerOut)toggle(handlerEven, handlerOdd)
These are the event handler used in the jquery and also called Event helper. The events i have mentioned above in the table return jquery object by which the event is bind, as jquery support chainability so the return object is used to apply another function on that object. We can divide events in the Table 2 into three categories.
  1. Events which are related to the mouse, also called mouse events which include click, mouseover , mouseout etc.
  2. Events which are related to the key board, also called Keyboard event which include the keypress, keyup etc.
  3. Events which are related to the form. which include the load and unload of the form.
Let us start with the events related to the mouse, then event related with the keyboard and the at the end the events which are related with the form.
The event listed in Table 1 are also the shorthand of the bind() event handler where you have to specify the event name and the function to be executed when the event is fired. Let us start with the most used mouse event which is click. Here is the code you can use to bind the click event with the control.
$(document).ready(function()
{
// use this to reset a single form
$("#reset").click(function()
{
alert("Button is Click")
});
});
The code above is simple one i have used the id of the button "reset" to bind the click event with it, so when the button is click alert message "Button is Click" is shown. Below is the code for both the click(fn) and click event handler. The code above is also shortcut for the .bind('click', handler)

$(document).ready(function()
{
$("#myDiv").click(ClickCalled);
$("#myDiv").click();
});

function ClickCalled()
{
alert('called');
}

you can see the from above code snip that when the page is loaded the function is called as i have call the $("#myDiv").click(); which will call the function associated with the click event or you can say in the previouse statement i have attach the ClickCalled function. This remind me the buttonName.PerformClick(); function. Which i love to use in the desktop application when i develope the desktop application, now i am happy to use it in the jquery as well and i am very happy that jquery has given this functinality.Although we can call the function but calling the click() function is really cool. Remember that you have to attach the click event handler before
calling the . click() event. The dbclick event is similar to the .click except the event is fired when mouse is double click and hope you can do yourself i will not explain it here, if you need help regarding dbclick then please tell me i will help you.
Next event which i will explain you related to the mouse is the hover() event handler , you can see in Table 1 that the .hover(handlerIn, handlerOut) takes two functions as parameter one is used when mouse enter into the control to which the hover is bind and the handlerOut is used when the mouse is leave that control. For the javascript programmer who use the mouseout and mouseover for the simple effect for example when mouse is over to over a button then the background color is change from the default to new color and when mouse is out of that control then the default color is set.
$(document).ready(function()
{
$('#myDiv').hover(function()
{
$(this).css('background','pink');;
},
function()
{
$(this).css('background','#000');;
});
});



Above is the simple code which illustrate how you can use the hover event handler to bind the two functions, the above code will change the background color of the div which to pink when the mouse is over the div and set the default color of black when mouse leave the div control.

The remain events which are related to the mouse , i will leave the reader to discover them and use them, if you need any help regarding the the mouse events please do tell l me. Events for the keyboard and the form i will discuss in next post , hope this will help you and you get some help from this post as well. If you have any question please do tell me , i will try my level best to give you answer.

back to content

How to Get Selected Value From DropDownList Using Javascript

In this post i will tell you how can you get the selected value of the DropDownList of asp.net control using javascript. It is simple code but i think this will help you. Below is the sample code you can use in your cod.

function getSelectedItem(dropDownList)
{
//get the selected index of the dropDownList
var intSelectedIndex = dropDownList.selectedIndex;
//check if there is selected item or not
if(intSelectedIndex != -1)
{
//get the value of the dropDownList
var value=dropDownList.options[intSelectedIndex].value;
//get the text of the dropDownList
var strText= dropDownList.options[intSelectedIndex].text;
/*
what ever you like to with the value and the text as you
get these properties of the dropDownList
*/
}
}

In the above code i have use function getSelectedItem which take dropDownList control object as parameter. In the first statement of the function i have get the selectedIndex of the dropDownList and store it in the variable intSelectedIndex . In the next line i have use the if condition to check whether selectedIndex is not equal to the -1 which indicate nothing is is selected. If selectedIndex is not equal to the -1 then it mean user have selected some value in the dropDownList, In the if condition block i have used that selectedIndex to get the value and the text of the dropDownList item. I have store the value and text in seperate variable so that you can use it whatever your need is. Hope this will help you and if you have any question please do ask me.
Happy programming :)

Wednesday, December 24, 2008

DropDownList Add/Remove Item Using Javascript

In this post i will discuss operations such as insert/Add and remove item from DropDownList using javascript. I have used insert and remove operation to add and remove items from dropdownlist using javascript in my projects very often. And i think it is good to share my knowledge regarding this operation with you people as well. First i will discuss how you can remove all the items from the dropdownlist and then how you can add item in the dropdownlist using javascript.

Removing Items from DropDownList

Below is the simple code to remove the items from the dropDownList. In the code below i have created a simple function name clearDropwDownList , the function will take the dropDownList control object as parameter.

function clearDropDownList(dropDownList)
{
//get the total item from the dropDownList
var intTotalItems= dropDownList.options.length;
//loop through the number of items
for(var intCounter=intTotalItems;intCounter>=0;intCounter--)
{
//remove the intCounter( currently index) item from the dropDownList
dropDownList.remove(intCounter);
}
}

At the first line of the function i have declared variable named intTotalItems which will hold the number of items in the dropDownList which is passed to the function. Then i use the for loop to remove the each item in the dropDownList by using the remove(intCounter), statement where intCounter is the current index to be removed.

Add Items from DropDownList

Now how to add new value(s) in the dropDownList, below is the code you can use to add the value to the dropDownList, i have created function for this operation as well, so you need to pass the dropDownList control object , the value field and the text field to be added in the dropDownList as new item.

function addDropDownListItem(dropDownList,value,Text)
{
//Create new item option to be added in the dropDownList
var newOption = document.createElement("option");
//assign Text value to the text property of the option object
newOption.text = Text;
//assign value to the value property of the option object
newOption.value = value;
//add new option in the dropDownList
dropDownList.options.add(newOption);
}

First i have created the option object to hold the text and the value of the new item and then i assign the values to the text and the value property and at the end added the new option in the dropDownList.

If you have any question regarding this post please ask me

Happy programming :)

Saturday, December 20, 2008

Jquery Content

These are the series of articles regard the jquery for the beginners series if you have any question please feel free to ask any question regarding my post. Here is the list of articles you can find in this series and this will updated regularly as i post new article.
  1. Jquery for Beginners
  2. Jquery for Beginners:Events Handling Part 1
  3. Jquery for Beginners:Events Handling Part 2
  4. Jquery for Beginners: Events Handling Part 2 ( continue)

hope you will like this series, if you like that i will write article of your choice regarding in this beginner series , please do tell me i will try to to add that article in my series.

Friday, December 19, 2008

Jquery for Beginners: Events Handling Part 1

This is the second article of the Jquey for Beginners. In the first Article i give some information how you can get started with the jquery. In the second article i will give starting point how you can bind the events with your control in order to do some actions against user interaction with the web application. If you see the jquery documentation for the events , documentation categorize the events into four types 1) Page Load, 2) Event Handling also called event attachers, 3) Interaction Helpers and 4) Event Helper. In first article, we noted that $(document).ready() is the jquery way to perform the action which are need to in page load and this function is similar to the javascript function onload. So if you want to read more about ready() handler please read my first article. Here are the ways you can write the ready() event handler :

//1- one way to call the ready function.
$(document).ready(function()
{
// Our code here...
});

//2- Second way to call the ready function.
$().ready(function()
{
// Our code here...
});

//3- Third way to call the ready function.
$(function()
{
// Our code here...
});

All the above three ready handler has same functionality you can call the ready handler whichever style you like.

Event Handling (Event Attachment):

Below is the list of the event handling taken from the documentation of events from jquery site. List 1

Event Name Description
bind(type,data,fn) Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
one(type,data,fn) Binds a handler to one or more events to be executed once for each matched element.
trigger(type,data) Trigger a type of event on every matched element.
triggerHandler(type,data) This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browser's default actions.
unbind(type,fn) This does the opposite of bind, it removes bound events from each of the matched elements.


The return type of the above events are the jquery object. which is used for chainablility , to apply more functions on that return control object. when you call above enent handler/attachers, you can set the type of the event by one of the below list. List 2
Event Name Event Name Event Name
blurchange focus
click dbclick error
keydown keypress keyup
mousedown mousemove mouseout
mouseover mouseup resize
scroll select submit
load unload

These are the possible value of the type which is set in the event binding. Let us start with the bind event handler.

bind():

The bind() event handler is use to bind the event with the object.You can see from List 1 parameter of the bind events are the type ( which i have mentioned in the List 2), data(optional parameter) and event handler.Here is the example how you can use the bind event handler to bind the event with the object.

$(document).ready(function(){
$( "p").bind("click", function(e){
var str = "( " + e.pageX + ", " + e.pageY + ")";
alert(str);
});

$( "p").bind("dblclick", function(){
alert("Double-click happened" );
});

$( "p").bind("mouseenter mouseleave", function(e){
$(this).toggleClass( "over");
});

});

Above code is simple one it bind the click event , dbClick and the mouse enter and mouse leave events for the paragraph tag. and you can also see how to set the type of the event in the bind event handler and also it attach anonymous callback function. The anonymous callback function which is attached with the click event is passed an event object which i will explain next. And the event handler which is attached with the dbclick didn't passed any parameter. Let me explain the event object which is passed to the event handler so you get some idea why we need to pass event object to the event handler.

The Event Object:


The callback function which is attached using the above list event handler can also take optional parameter which is used for additional information in the callback function.The additional information include such as .shiftKey (whether the shift key was held down at the time), .offsetX (the x coordinate of the mouse cursor within the element), and .type (the kind of event this is). Some of the event object's attributes and methods are not available on every platform. If the event is handled by a jQuery event handler, however, the library standardizes certain attributes so that they can be safely used on any browser. In particular:
.target:
This attribute represents the DOM element that initiated the event. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling.

.pageX:
This attribute contains the x coordinate of the mouse cursor relative to the left edge of the page.

.pageY:

This attribute contains the y coordinate of the mouse cursor relative to the top edge of the page.

.preventDefault():
If this method is called, the default action of the event will not be triggered. For example, clicked anchors will not take the browser to a new URL.

.stopPropagation():
This method prevents the event from bubbling up the DOM tree looking for more event handlers to trigger.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object. Note the parameter added to the anonymous function. You can omit the event object, if you need additional information regarding the event then you can pass the event object else no need to pass the event object.

Passing Event Data:
Now here is the code to bind the event with object using the bind event handler and also pass the data as well.The code below is taken from Infovore
$(document).ready(function()
{
$("#myDiv").bind("click",{myValue:'Some Value'}, handleToggleEvent);
});

function handleToggleEvent(event)
{
alert(event.data.myValue);
}

In the above code you can see i have bind the click event for the div control , the id of the div is myDiv as you can see from the selector. and i have pass the value is key : value, which mean if i have to access the value which is passed then i need to call event.data.myValue in the event handler, which is set at third parameter in the bind event handler.

unbind():

The unbind event handler is opposite to the bind event handler as it unbind any event attached to the object. From the List 1 you can see the the it has the following form

 unbind(type,fn)
where type is one of the type i have mentioned in List 2 , e.g 'click', 'dbclick' or any of the type which is listed in the List 2.

//1- one way to call
$(document).ready(function()
{
$("#controlID").unbind();
});

//2- Second way to call
$().ready(function()
{
$("#controlID").unbind(type);
});

//3- Third way to call
$(function()
{
$("#controlID").unbind(type, callback);
});

The first call to unbind the callback will unbind all the callback from the "ControlID" , The second call is more specific as it will remove the only callback whose type is give, for example if you give the type "click" then it will remove the callback which are bind for the click event handler. and the third one is specific then the first 2 as it will unbind the event which is passed either "click" or any of the type which is listed in the List 2 and then then remove the callback which is passed as well.

one():

The next one is the one event handler. The one event handler as its name suggest is executed only once and is similar to the bind event handler except that event is fire once , mean if you for example attach event handler for a control on its click once you click the button the code is executed but if you click again the button then the code is not executed. It is similar to that you unbind the callback, once the event is fired and you don't want to execute the code again. And here is the call to the one event handler.

one(type,data,fn)
you can see that it is similar to the bind event handler , same type parameter, same optional data parameter and same callback function parameter.

trigger():

The trigger event handler is used to execute the specific callback function, which is attached using the bind event handler.


hope you will get enough to start with the event handler , if you have any question please ask me
happy programming :)

back to content

Saturday, December 13, 2008

Jquery for Beginners

Every web developer not all 100% but i think 99% of developer must use the javascript in there project, for input validation , showing and hiding of the controls, slowly showing and slowly hiding etc .They have used the javascript in there project and they have write same code again and again in different projects or even in different form/pages. I personally love to use javascript in my web application where it is necessary and i love javascript coding. During my search on the javascript on net i have found many javascript libraries which can be use to achieve functionalists which i have mention above. The libraries include prototype, mootoo , jquery etc. All of these libraries are really good. But i have use the jquery and try to get more out of jquery library.
Let us start how we can start with jquery. First of all you have to get latest version of the jquery file from the jquery web site.

for user i have pasted the image of the location from where you can download the jquery file. as you can see there are two files which has same, the difference is in there size one is for production and one is for Development, you can download one of this or both. You can download the production file from jquery-1.2.6.min.js 54.5 KB. Next you have to include the jquery file into your page like this

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

And this is the simple starting point for you reader who are just new to the jquery. you have to put this code in the script tag of type 'text/javascript'.

$(document).ready( function()
{
alert('Hello world');
});

The above code is simple one and it contain just hello world message which is shown when the page is fully loaded. But this code contain the basic things you need to start with, first of all the dollar ($) sign, which is call the selector, if you want to select any control in the you page then you can use this dollar sign to get that control suppose you have the control whose id is "cmdButton" then what you need is to get that button but using $('#cmdButton') statement, One more important thing which i would like to share with you is that the syntax above to get the control is used when you don't have master page in you project, or your page didn't open in master page but if your page is open in your master page then what you need to do is to get the control is $('#'+'<%=cmdButton.ClientID%>') this syntax is used to get the control in jquery.

From the code above you have seen the number sign (#) The number sign is used to select the control/element by there id. You can select element by there css className, with there ElementTag and even with the element properties etc for complete referece how you can access the elements you can click here . For quick reference some of the how to access the elements.
  • To access element with there id , where myDiv is the id of the div control in the page.
    $("#myDiv").css("border","3pxsolid red");
  • To access element with there tag name . This example will apply red border of red color to all the divs in the page regardless of the id and the class name.
    $("div").css("border","3px solid red");
  • To access element with there css className . The example below will access the control whose css class name is myClass and apply the red border of 3px to every control which has myClass css class name.
    $(".myClass").css("border","3px solid red");
Now come to the $(document).ready(function(){}); event handler .This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready(function())}. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded (Source). The question which may come into your mind is why we need the $(document).ready(function(){}); The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
 window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is due to the fact that the HTML 'document' isn't finished loading yet, when you first try to run your code. To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event (Source)

why we need to use jquery, as you can see the syntax of the jquery is very easy to learn and easy to read.Second think which i like about jquery is that if you call one jquery function then that function will return same object, which is chainability , mean you can apply as many function by place the (.) dot sign and call the next function and so on and on.

Hope you like this. if you have any question then ask me.

back to content

Saturday, December 6, 2008

SqlCommand Parameter And Sql injection

Sql injection can be prevented using sqlCommand parameter, and i will show you how can we use sqlCommand paramenter to avoid the sql injection.When i think of sql injection first question that came to my mind is what is sql injection. Definition of sql injection is (Wikipedia)

A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application.

A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.
So in order to avoid such attack from hackers we need to check for invalid input from the user. Some programmer who are really good convert single quote to double quote, by writing the function, Some programmer not allowed user to enter such characters in input fields and so on and on.But the way today i will discuss is using sqlCommand parameter to avoid such attacks. Input used for this test application are as fellow.

User Name: asimsajjad';Drop Table tblUser;'

Password: 123



I have used Same database of northwind and same tblUser which i have show in my sqlCommand parameter post.First i have tested for the sqlCommand parameter so that i don't need to create tblUser table again. Hope you will create the HTML for your page as i will not write HTML code of the my test here. The .cs code which i have write on the cmdSave_Click event handler is pasted here, you can copy paste the code and change the UID and pwd with the sql server user name and password.

protected void cmdSave_Click(object sender, EventArgs e)

{

try

{

SqlConnection sqlConnection = new SqlConnection("Data Source=localhost; UID=UserName; PWD=Password; Initial Catalog=northwind;");

sqlConnection.Open();


string strQuery = "Select userID from tblUser where UserLoginName=@UserLoginName";


SqlCommand sqlCommand = new SqlCommand (strQuery, sqlConnection);

sqlCommand.Parameters.AddWithValue("@UserLoginName", txtLoginName.Text);


int intUserID=Convert .ToInt32(sqlCommand.ExecuteScalar());
}

catch (Exception Ex)

{
//handle the exception here;

}

}


The above code is simple one. i have declared and initialize the sqlConnection object and pass the connection string to the sqlConnection constructor. After initializing the sqlConnection object i have open the connection object. Then i have declared the string object to hold the sqlCommand. Next i have declared the sqlCommand object and initialized the sqlCommand with query and sqlCommand object. In the next line i have added the the value of the parameter which i have used in the query. With the above input the value is saved in the tblUser table and there is no error and no sql injection as , i have inserted Drop Table tblUser; statement in the user name field. But using sqlCommand parameter the table is not dropped.
But when i use the code below with same parameters as above then the tblUser table is drop from the database. Which confirms that dynamic query can't stop the sql injection.

protected void cmdSave_Click(object sender, EventArgs e)

{

try

{

SqlConnection sqlConnection = new SqlConnection("Data Source=localhost; UID=UserName; PWD=Password; Initial Catalog=northwind;");

sqlConnection.Open();


string strQuery = string.Concat("Select userID from tblUser where UserLoginName='", txtLoginName.Text,"'");


SqlCommand sqlCommand = new SqlCommand (strQuery, sqlConnection);
int intUserID=Convert .ToInt32(sqlCommand.ExecuteScalar());
}

catch (Exception Ex)

{
//handle the exception here;

}

}



When i posted my first post on sqlCommand parameter one of my reader ask question "does using parameters in sql command prevent sql injection?" , I also mention is that post the using sqlCommand parameter we can prevent the sql Injection, So from my above test i can answer you confidently yes.
The Guidlines of avoiding the such attacks are (How To: Protect From SQL Injection in ASP.NET)
  • Constrain and sanitize input data. Check for known good data by validating for type, length, format, and range.
  • Use type-safe SQL parameters for data access. You can use these parameters with stored procedures or dynamically constructed SQL command strings. Parameter collections such as SqlParameterCollection provide type checking and length validation. If you use a parameters collection, input is treated as a literal value, and SQL Server does not treat it as executable code. An additional benefit of using a parameters collection is that you can enforce type and length checks. Values outside of the range trigger an exception. This is a good example of defense in depth.
  • Use an account that has restricted permissions in the database. Ideally, you should only grant execute permissions to selected stored procedures in the database and provide no direct table access.
  • Avoid disclosing database error information. In the event of database errors, make sure you do not disclose detailed error messages to the user.
Some of the benefit other then i have mention in sqlCommand parameter are
1)
It is faster when executing parametrized command over query string..("MSDN Forum")
2) The second-order attack would not have been possible if parameterised queries had been used.(Code Project). Second-order attack is "it may be possible for an attacker to inject their malicious code into a data storage area that may be executed at a later date or time. Depending upon the nature of the application and the way the malicious data is stored or rendered, the attacker may be able to conduct a second-order code injection attack. " (Source)

Hope this will help.

Friday, December 5, 2008

JavaScript ToolTip

Today i will discuss tooltip in javascript how can you create it and use it very quickly in your code. I have seen that there is no such control for tooltip in asp.net, so the developer try to design there own tooltip. Some of the control in the asp.net has the property tooltip but not all has. So in order to show the tooltop for those control here is the little javascript code to use it. This Sample Javascript code is taken from the Itookia, and I have modified the code according to my need and also the i have use the stylesheet for the formatting.


and the tooltip which contain the help information .

and tooltip which contain the image.

The Css used for this tooltip which i have changed is takend from Itookia

.newDivClass

{

filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0,

StartColorStr=#ffffff, EndColorStr=#cecfde);

cursor: hand;

width: 300px;

font-size: 11px;

padding-left: 5px;

padding-right: 5px;

border: 1px solid #7b9ebd;

position: absolute;

visibility: hidden;

}



.TitleClass

{

padding: 6px 0 4px 10px;

font: bold 12px Trebuchet MS ,Arial;

float: left;

clear: both;

width: 100%;

}



.mainParagraphClass

{

font: normal 12px Trebuchet MS, Arial;

padding: 0 2px 6px 20px;

margin: 0;

float: left;

}


.MainImageClass

{

font: bold 12px Trebuchet MS ,Arial;

margin-right: 10px;

border: #BDBDBD 1px solid;

float: left;

}



The javascript code which i have modified is

var lastTooltip =null;

showTooltip = function (strTitle,strText,strHelpText,strhelpImage,strmainImage)

{

if (lastTooltip==null)

{

var newDiv = document.createElement("div");

newDiv.className='newDivClass';

var title = document.createElement("span");

title.className='TitleClass';

var titleText = document.createTextNode(strTitle);

title.appendChild(titleText);

var mainParagraph = document.createElement("p");

mainParagraph.className='mainParagraphClass';

if (strmainImage)

{

var mainImg = document.createElement("img");

mainImg.setAttribute("src",strmainImage);

mainImg.className='MainImageClass';

mainParagraph.appendChild(mainImg); }

var mainText = document.createTextNode(strText);

mainParagraph.appendChild(mainText);

newDiv.appendChild(title);

newDiv.appendChild(mainParagraph);

if (strHelpText)

{

var horLine = document.createElement("hr");

horLine.style.width='96%';

horLine.style.clear='both';

var helpDiv = document.createElement("div");

helpDiv.style.styleFloat='left';

helpDiv.style.cssFloat='left';

helpDiv.style.clear='both';

helpDiv.style.paddingLeft='6px';

helpDiv.style.height='24px';

if (strhelpImage)

{

var helpImg = document.createElement("img");

helpImg.setAttribute("src",strhelpImage);

helpImg.style.marginRight='8px';

helpImg.style.verticalAlign='middle';

helpDiv.appendChild(helpImg);

}

var helpText = document.createTextNode(strHelpText);

helpDiv.appendChild(helpText);

newDiv.appendChild(horLine);

newDiv.appendChild(helpDiv);

}

lastTooltip=newDiv;

if (document.addEventListener)

document.addEventListener("mousemove",moveTooltip, true);

if (document.attachEvent)

document.attachEvent("onmousemove",moveTooltip);

var bodyRef = document.getElementsByTagName("body").item(0);

bodyRef.appendChild(newDiv);

}

};

moveTooltip = function (e)

{

if(lastTooltip)

{

if (document.all)

e = event;

if (e.target)

sourceEl = e.target;

else if (e.srcElement)

sourceEl = e.srcElement;

var coors=findPos(sourceEl);

var positionLeft = e.clientX;

var positionTop = coors[1] + sourceEl.clientHeight + 1;

lastTooltip.style.top=positionTop+'px';

lastTooltip.style.left=positionLeft+'px';

lastTooltip.style.visibility='visible';

}

}

hideTooltip = function ()

{

var bodyRef = document.getElementsByTagName("body").item(0);

if (lastTooltip)

bodyRef.removeChild(lastTooltip);

lastTooltip=null;

};

function findPos(obj)

{

var curleft = curtop = 0;

if (obj.offsetParent)

{

curleft = obj.offsetLeft

curtop = obj.offsetTop

while (obj = obj.offsetParent)

{

curleft += obj.offsetLeft curtop += obj.offsetTop

}

}

return [curleft,curtop];

}



and the javascript function calls for all the above image show are

onmouseover="showTooltip('Simple tooltip','This is simple tooltip')"

onmouseout="hideTooltip()"

onmouseover="showTooltip('Simpe tooltip with additional info','This is simple tooltip with additional help info.','Press F1 for more help.','help.png','')"
onmouseout
= "hideTooltip()"

onmouseover="showTooltip('Complex tooltip','This is complex tooltip with image.','Press F1 for more help.','help.png','graf.png')"

onmouseout="hideTooltip()"





Hope you will like this post for the tooltip in asp.net using javascript :)
you can now download source code from here

Monday, December 1, 2008

SqlCommand Parameters

Today i will discuss the sqlCommand Parameters which i have not used before this, and i was unaware of the power of the sqlCommand Parameter. Before this i was using the dynamic query by concatenating the string and then executing that query to fetch, update delete the record from database.
I have read the following 2 article Dynamic SQL Needs to die and Dynamic SQL Can Die Automatically and i find these article very useful.
Lets start by Example then i will give the conclusion at the end.
i have created simple table name tblUser in the northwind database and table name is tblUser and is shown below.



and i have following one value in the database for my testing.


The user interface is quite simple which consist of User name , password and login button. In the image below i have set the value of the user name and password which are use name is "asim" and Password "123'3". As you can see in my example input , for user i have not set the password field property " TextMode" to Password.So that user can see the input clearly.

No when i execute the sqlcommand for dynamic query which use the concatenation of the values with the string and generate the query you can see clearly in the image blog that it will give Exception of "Incorrect syntax near '3'.\r\nUnclosed quotation mark after the character string"," and this exception often occure if we don't convert single quote to double in our code.

And when i use sqlCommand with same parameters which contain single quote in the password there is not exception in the execution of the command and i got the smoth execution of the command and result. As you can see in the image blow.



Now i am happy to knew the power of sqlCommand and ready to use it in the my new projects. The Benefits of using the sqlCommand are as fellow taken from Dynamic SQL Needs to die.

1) Single Quote.

If I forgot one of the apostrophes. The code would compile and everything would appear to be fine. However, once I executed the command, it would blow up and result in a Syntax error. This is an easy mistake to make no matter how careful you are. Also, pretend you had 15 values in the Where clause. It'd be a feat indeed to get it right the first time. Another common thing that comes up is that you can just write a function that changes the single quotes to double quotes so it can be used. Well, you'll have to call this on every SQL statement to safely assume it will work. You'll probably forget to do it at least once, and other programmers may forget it or not know that you have this function when they maintain your code.

2) Data Type

Another example is Date fields. Different RDBMS implementations require a different Date Format. It's very easy to forget about this and forget one of the critical formatting chunks. Again, if you are totally careful you probably won't make many mistakes here, but your new programmers probably will. Someone editing your code probably will etc.Another problem is fields that have an apostrophe in them. This happens so often it's amazing.

3) It's a preformance killer.

Your query won't be able to take advantage of cached execution plans. That means that the same query can hit the db over and over again and each time the Server won't be able to reuse plans it's already cached.