Wednesday, September 30, 2009

Dotnetkicks.com kick it for blogger blogspot blogs

I know most of bloggers are searching for this…. If you are writing ASP.NET related posts in your blog then you should need it to publish your posts to dotnetkicks.com. So, here is a nice tip to add kick it for your blogspot blogs.
  • Go to your blog. After you sign in, in admin section you have a tab named "layout".
  • Under layout tab select "Edit HTML".
  • Before you do any changes, please download full template.
  • Then tick the checkbox "Expand Widget Templates."
  • In your browser, press Control+F and find the keyword "data:post.body".
  • Go to that line [<data:post.body/>] and hit enter and add the below code as is.
<p><a expr:href='&quot;http://www.dotnetkicks.com/kick/?url=&quot; + data:post.url'><img alt='kick it on DotNetKicks.com' border='0' expr:src='&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=&quot; + data:post.url'/></a></p>

Note: expr: is the syntax for expression and it will execute by blogger code and replace the correct values before send response to browser.
  • Now, save the template and view blog for the changes.
  • I think, you are smiling now by seeing kick it icon on your blog for each post.
  • Enjoy!!!
Love to hear comments from you. Is this helpful?

Wednesday, September 23, 2009

Jquery intellisense in Visual Studio 2008

This is a small tip I want to tell to my readers. I know, most of the dev's think like if Jquery intellisense is available in visual studio then that will be good :). So, this post will help you to solve that problem.
Below are the steps we need to follow to get the intellisense working in Visual studio 2008. Before start with the steps I will tell you how it helps us.
  • Learn more and implement more: Because of having this intellisense support in vs 2008, we can solve so many problems and can implement so much in JQuery. It will be very difficult for everyone to remember all the functions and members for the Jquery objects. So, This will give more support to learn more and implement more.
  • Fast and rapid development of the client side scripting. Until you don't know what methods and properties it has you can't write program fast and efficient.
  • Time saving: Complete documentation for all Jquery objects, methods and properties. The inline description is more than enough to understand it well. Till these days, every time need to go to Jquery documentation site and need to search for what we need and read about them. But, now everything is in visual studio. Big time saving here.
  • Load time: I know, at this point you may think how it will effect load time by adding the Jquery documentation file to page. By adding the vsdoc file [~188Kb] to the page won't increase the page size or won't effect the load time at all. We will refer the documentation file while coding or at development time only but it won't render on the client side. How? I will explain it later in this post.
Requirements:
  • Install Visual Studio SP1.
  • We need to download the vsdoc file from here.
  • Install the hotfix for visual studio before proceed.
Steps to refer the documentation file(vsdoc):

  • Refer the documentation file to js file: If you need jquery intellisense on the js file then you need to write the below declaration as the first line of your js file.
/// <reference path="jquery-1.3.2-vsdoc.js" />
Note: the path value is the actual path of the vsdoc file.
  • Refer documentation file in ASPX page: This is what we need most of the times for writing inline scripting on the page. So, add below code to the <head> tag of the page for JQuery intellisense.
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<% if (false) { %>
<script src="jquery-1.3.2.min-vsdoc.js" type="text/javascript"></script>
<% } %>

Note: The Jquery file reference should always be the top of the Jquery documentation file reference. And if you install Visual studio SP1 and the hot fix then there is no need to place the complete IF block from the above code. And the vsdoc file should be in the same folder where the jquery file is.
Note: The short cut for the update intellisense in Visual Studio is Ctrl + Shift + J. So, once reference added please done it once to update the intellisense.

How, Jquery intellisense work in Visual Studio?
It's simple. What JQuery –vsdoc.js file contains? Nothing but the description text for all the defined methods and properties. So, when you refer the vsdoc file in js file, it will load that file into memory and set the meta data for the Jquery methods and properties. If you refer the vsdoc file in ASPX pages, then it will set the metadata as follows.
First, Visual studio will look for the JQuery file, example jquery-1.3.2.js. And then it will look for the file which has the format jquery-1.3.2-vsdoc.js. If it matches then only visual studio loads the meta data and intellisense will work, otherwise not. So, your jquery file and documentation file should be having the same name with –vsdoc at end of the documentation file name.
Note: Jquery file: jquery-1.3.2.js and Jquery visual studio documentation file name: jquery-1.3.2-vsdoc.js
Lastly, I want to explain about the load time from above mentioned bullet. If you observe the code I have given, it has some server-side code integrated in it. I wrote if condition which always fails to execute the code inside the if block because I am passing false always to it. So, it never runs the code inside the if block and nothing loads on the client side related to vsdoc file. At the time of development, server-side code won't run but all the meta data will load because there is a script tag on the page. So, at development time, the vsdoc file will load, but when you browse the page, vsdoc file won’t render.
That's it!!! I hope this will give nice idea of how Jquery documentation work in visual studio and how to add the reference to your files. Isn’t it? Please give your valuable feedback or comments on this post.

Tuesday, September 22, 2009

Check/Uncheck all checkboxes in Jquery

This is simple, but want to show you how to get it working in simple and efficient way. Usually we have a parent check box and then some child checkboxes. Depends on the parent check box selection, all the child checkboxes should behave exactly same. So, below is the Jquery function which will do that magic for you.
function CheckUncheckAllCheckBoxes(objID, checkedValue) {
if (objID == null || objID == undefined )
return;

$(objID + " input[type=checkbox]").each(function() {
this.checked = checkedValue;
});
}
If you observe, I am using two parameters for the function named objID and checkedValue. objID is the parameter for knowing which checkbox group or list we need to check or uncheck? Like, on a page we may have many checkboxes and groups or lists. So, we need a way to find out which group or list we need to check or uncheck? For this reason I added a parameter for the function to check only the checkboxes under that ID or Class. Possible values for the objID are
  1. #parent Control ID of the element which has the check boxes declared. Example: #ageList
  2. .parent control class of the element under which all the check boxes defined. Example: .edit
And second parameter, it is for passing the parent selected check box value. If it is ON, then logic will loop through and set the each checkbox to checked otherwise unchecked.

Usage - How to call this method:
Code for check/Uncheck all in ASP.NET
$("#<%=cbAllStates.ClientID %>").click(function() {
   CheckUncheckAllCheckBoxes("#<%=cblState.ClientID %>", this.checked);
});
Note: cblAllStates is the parent ASP.NET check box which is controlling child. cblState is the asp.net checkboxlist and in our terms child check boxes.

Code for Check/Uncheck all in HTML:
$("#cbAllStates").click(function() {
   CheckUncheckAllCheckBoxes("#divChilds", this.checked);
});
Note: cbAllStates is the parent check box control and divChilds is the division <DIV< tag which has all the child check boxes present in it.

**UPDATED** 06/22/2010
This is the small update for the check/uncheck the all check box depends on the child check box selection. If any of the child check box is unchecked or the all child check boxes are selected then the all check box will toggle depends on it. Below is the work around.

Example:
Code for  Toggling the all check box depends on the child check boxes:
function ToggleSelectAllCheckBox(allCheckBox, checkedValue, obj) {
    if (allCheckBox == null || allCheckBox == undefined)
        return;
    if (!checkedValue) 
        $(allCheckBox).attr("checked", false);
    else {
        var areAllChecked = true;
        $(obj + " input[type=checkbox]").each(function() {
            if (!this.checked) {
                areAllChecked = false;                
            }
        });
        $(allCheckBox).attr("checked", areAllChecked);
    }
}
In the above function param1 is the all child check boxes, param2 is the current child check box selection and param3 is the all check box selector.

How to use:
ASP.NET Checkbox list:
$("#<%=cblAge.ClientID %> input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox("#<%=cbAllAges.ClientID %>", this.checked, "#<%=cblAge.ClientID %>");
 });
Note: cblAges is the check box list id and the cblAge is the all check box for the age group. So, the click event is for the all check boxes inside the check box list.

HTML Check boxes:
$(".ageGroup  input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox(".ageGroup", this.checked,  "#allAgeCheckbox");
 });
Note: ".ageGroup" is the div or some parent element which holds all the checkboxes in HTML. "#allAgeCheckbox" is the id of the all checkbox for that age group.

**End of Update**

Hope this will help you to understand how to write code in efficient way and which helps for us in multiple scenarios. Always welcome your valuable comments.

ASP.NET Checkboxlist get values in client side [JQuery]

See my other post, which explains "how to set the value attribute for a single check box through c# code" before proceed to this post.

I know, this is the question most of the ASP.NET developers will ask or look for an answer on why there is no value attribute set for check box when it generates from the ASP.NET checkbox list? Where as the Radio button list, Drop down list and other controls has this value attribute set when you set the data source for them. But why there is no value attribute set for check box list control. Below is the nice explanation and will help you to understand the concept well.

If we assign some data source to the check box list control, then the HTML output is with two controls for each check box as input control with type checkbox and another is label with the text. So, This is the problem. How to get the value of the checkbox in client side using some javascript library? Here we need to think a way of how to set a attribute which holds the value for each checkbox and how to get it.

Below is the solution I found. In your C# code, after you bind the data source for the checkbox list, then need to add extra piece of code below to get our problem solved.

C# code:

foreach (ListItem li in checkBoxList.Items)
li.Attributes.Add("someValue", li.Value);

So, What happening here is, I am just adding extra attribute "someValue" for each check box in a check box list[checkBoxList] and looping through them and assign the actual value to that custom attribute. So that HTML for each checkbox on the page will render like this.

HTML rendered output:


If you observe, there is an extra parent control for each check box control named <SPAN> with the attribute we have set in c# code for each checkbox. Now you have some value set with each checkbox and you can get it on client side easily. [There is no change in C# code accessing values.]

How to access the values on client side?

I am using JQuery, so I will give an example of how to get the values using the JQuery.

To get all checkboxes which are checked under a checkbox list are accessed as follows.

JQuery code:

$("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {
var currentValue= $(this).parent().attr('someValue');
if(currentValue != '')
values += currentValue + ",";
});

So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated. I think, now you got an idea of how to access the values in client-side. Hope it will help you to understand what I am trying to say. Please add your valuable comments on it.

Sunday, September 13, 2009

Detect asynchronous postback in ASP.NET

Everyone need to know about this. When no Ajax implementation in ASP.NET [older versions] asp.net developers know about only one post back. That is full page postback. We have a property to detect it in c# code with Page.IsPostBack. But, day to day technology is growing and we need to know/follow everything up to date. This is not new one or I didn't find it just recent. All these posts are my experience and part of sharing information.

Now a days everyone knows what is Ajax and how it will work. Everything is Asynchronous calls. So, in developing Ajax integrated applications in ASP.NET we need to know which is page full post back and which is asynchronous partial post back. So, This post will help you to understand it well.

As we know, ASP.NET Page Object has a property named IsPostBack, ScriptManager class also has a property named IsInAsyncPostBack and which returns true if page raised the async partial postback event.

Now, take a look at the usage of both.

//Checking for page postback
if (IsPostBack)
{
if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
//Aynchronous postback raised.
}
else
{
//Normal page full postback.
}
}

Remember, Here whatever postback raised like full page postback or async partial postback IsPostBack set to true in both cases.

Hope you understood well about the both postback types and how to know which one raised. Please add your valuable comments.

Cross page postback in ASP.NET

This is the blog post I want to present you something that you need to know. When I was new to IT industry and ASP.NET programming, I believe the ways to access the page1 variables on page2 are as follows.

  • Querystring parameters
  • Session management using session etc..

So, when I want to access the values of page1 on page2, I will store them in a session by creating session variable and will use it in the page2. And another method is, by passing values to page2 in query string parameters from page1. But this need some extra processing on server side to redirect them to that page.

After got little bit experience and when I came to the same situation where I need to pass the parameters from one page to another page, there cross page post back option helped me. So, I want to share the feature with you. This is the third way of passing values from one page to another page.

ASP.NET framework default supports it. There are some parameters to the Page object which helps us to get the logic work.

  • PreviousPage
  • IsCrossPagePostBack

When you want to call server side programming, usually we will write server side control with click event or command event which does the postback and execute server side logic for that event. But when you want to call different page in click event, then you need to use a special property called "PostBackUrl" and to it you need to set the url of the destination page. So, that post back event call that page. This is what the concept called Cross page PostBack.

In programming point of view how to implement this?

ASPX Code: [Page1.aspx]

<asp:TextBox runat="server" ID="tbCrossPageTest"></asp:TextBox>
<asp:Button runat="server" Text="Submit" PostBackUrl="~/Page2.aspx" />

C# Code: [Page2.aspx]

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            TextBox tb = (TextBox)PreviousPage.FindControl("tbCrossPageTest");
        }

Here, we need to check for some conditions as best practice. One is for whether to know PreviousPage object is null or not and second, is current page from cross page post back. PreviousPage is the object which holds the page1 object and from it, you can find any control on the page and access the values. I know, we don’t use this in many times, but you need to know this option is available in ASP.NET. Please let me know you ideas on it and provide your feedback. Hope this will help you better in understanding the cross page post back.

Note: This cross page post back won't change any of current page properties. For example, page2.IsPostBack is false only, when cross page post back is raised on page1. So, don't confuse.

Monday, September 7, 2009

Access IFrame content using Jquery

This is really helpful post for so many people who are using frames in their pages and want to access content inside it from main[parent] page. I really faced so many problems to read the data inside a frame and use it on the current page. So, it's simple and nice to know this tip for JQuery lovers.

HTML:

In Parent file, for example iFrame is declared as below.

<iframe id="uploadIFrame" scrolling="no" frameborder="0" hidefocus="true" style="text-align: center;vertical-align: top; border-style: none; margin: 0px; width: 100%; height: 60px;" src="IFrameExample.htm"></iframe>

In IFrameExample.htm, assume there is a hidden control as shown below.

<input type="hidden" id="hiddenExample" name="hiddenExample" />

So, now I will tell you how to set the "hiddenExample" hidden control value from the parent file. Because, we can’t directly access it through java script/HTML. We need to use below logic to get it working.

var $currentIFrame = $('#uploadIFrame');
$currentIFrame.contents().find("body #hiddenExample").val("Value from parent file.");

That's it!!! You are done with assigning some value to hidden variable inside IFrame. And in that iFrame you can access this hidden control on server side[C# or VB etc..] too. For it, you need to follow my other post. Very simple, but hard to find. Below is the nice explanation of above code. [How it will work.]

So, we are using Jquery, you know how to define JQuery object and use it in DOM. I created a variable[Object] currentIFrame which holds the whole IFrame reference. And in the second line, I am using the contents() method, which actually returns me all the HTML code of the frame. So, as we already know, find is the method we need to use to find out any element in a given scope/context. So, it tries to find out the occurrence of given criteria in current frame. I think you understood well how it works. If you are having multiple IFrames then you can define class for <iframe> instead of id and you can catch it in Jquery by using "." operator instead of "#". Is it a new and good find? Please let me know, if this helps you or any questions if you have.

Sunday, September 6, 2009

How to write your own functions in JQuery

This post is also part of learning jquery. When I was new to learn Jquery, I was facing lot of problems in creating my own functions in JQuery. Because I want to create one function at one place and use it everywhere by calling directly JqueryObject.function(). After got some experience then I started writing my own Jquery functions and using them in my projects.

Syntax of how we can create a new function is as below.
jQuery.fn.myownfunction = function() {
var currentObject = $(this) ; //currentObject holds the current object.
};

Example function for centering an element is shown below.

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / $(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / $(window).scrollLeft() + "px");
return this;
}

How to call it?
$("#popupDiv").center();

Ok, now you are good at how to write your own functions in JQuery. Enjoy by learning.

Jquery making synchronous call

These days I am completely concentrating on JQuery, I want to share the knowledge I am gaining with you. In this post, I want to tell you how can we make synchronous calls. Everyone knows all the ajax calls are asynchronous. Whatever we are making calls in Jquery to server through clientproxy are the asynchronous calls. So, how to make synchronous calls? That is why I am posting here.

$.ajax({
type: "POST",
url: "url of the page",
processData: false,
success: function(msg) {alert("success")},
async:false
});

If you see the last line, the attribute declaration async:false which is the key for the telling the Jquery client proxy to make asynchronous call or not. If it is true then asynchronous otherwise synchronous.
Hope this helps you to understand it well.

Jquery $ and how to declare variables

Today, I got little bit of time and want to share with you small things I learn in JQuery. I know, most of the people who are new to Jquery don't know what is $ in JQuery.

$ is the symbol which is the initialization of Jquery object. You can pass selector, function, string etc to execute or implement some functionality. So, $("#idOfElement") or JQuery("#idOfElement") both are same.

I saw many people are declaring the Jquery variables as shown below.
var currentObject = null;
currentObject = $("#someID");

So, I don't say this is the best practice to use it. Instead you can do the below.
var $currentObject = null;
$currentObject = $("#someID");
And if you want to use it, you can directly use it as shown below.
$currentObject.val() or any other function supported for the current object.

So, the advantage here is, for easily identifying the Jquery variables. If you are working on a project where it needs lot of Jquery coding, then you must use this practice. Hope this helps!

Thursday, September 3, 2009

Jquery datepicker problem on date select in IE - 'length' is null or not an object

I am working on a project which includes the technologies like ASP.NET, Jquery, Sql server. I solved so many problems in Jquery and posted on my blog some. Now, I am posting a wonderful post on Jquery datepicker.
Because I am using Jquery in ASP.NET application, I added a regular expression for date to validate whether user entered date is valid or not. Because of adding the validation on the text box, whenever I select a date from datepicker, the datepicker events are firing like onselect, change etc.. So, generally what validation framework is doing, whenever some event fires on the page, validations will execute. The same thing happening here. Whenever I change or select date from the date picker, it will fire some events and at the same time validation framework trying to validate the validations. But, it is not the right event to do validations. So, always we will get the exception at "vals.length" in a for loop of the built-in code. vals is the object of all the validators on the page. It always fails to load in Jquery date picker event trigger, because it is not the right event for validation. And the result is vals is undefined, you always get exception at vals.length as "length is null or not an object". I think now you got very clear idea of why it is happening. Now, move to the next step i.e. solution for it.

Solution is very simple, I read all the documentation of Jquery datepicker and found an event named onSelect. So, whenever I select date this is the event firing. So, there I got a clue and started thinking towards it. And below is the result.

$(".datepicker").datepicker({ onSelect:function(){}});

In your datepicker initialization statement add onSelect event which don't do anything means empty function as shown above. There problem solved. Isn't a good find? Please let me know your thoughts on this.