Friday, November 30, 2007

ASP.NET Page Life Cycle

1. Object Initialization

A page’s controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file (see Figure 1), the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

2. Load Viewstate Data

After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated. Figure 2 shows an example of overriding and setting viewstate at the LoadViewState event.

3. LoadPostData Processes Postback Data

During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page. After the LoadPostData event triggers, the RaisePostDataChanged event is free to execute.

4. Object Load

Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens.

5. Raise PostBack Change Events

As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object’s data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data.

6. Process Client-Side PostBack Event

After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser.
Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page.

7. Prerender the Objects

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender .

8. ViewState Saved

The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not.

9. Render To HTML

The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render themselves into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only.

10. Disposal

After the page’s HTML is rendered, the objects are disposed of. During the Dispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. You can override Dispose.

Reference : -

Tuesday, November 27, 2007

Alternate text for images for different browsers

To show any picture or image on the webpage either img tag is used or <asp:Image> tag is used. We also put some alternate text for the image. Alternate text can be used to show some details on the screen related to the image. Alternate text is displayed when mouse is over the image. Internet explorer shows a cross sign which means that image is not available on the server where FireFox shows the alternate text on the screen instead of cross sign.

To show alternate text on the image we use
"alt" attribute for img tag .
"Alternatetext" attribute for asp:Image.

But the funny side of these attributes is they are not supported by Firefox. If you use any of these attribute to show alternate text then alternate text is not displayed in Firefox.

After some hard work I found a common solution which is supported by most browsers. Solution is to use " title" attribute instead of "alt" attribute. This attribute is supported by all the browsers.
<img src="sunset.jpg" title="Image1"> </img>

So if you are making an application for different browser stop using alt attribute and switch to title attribute.


Wednesday, November 14, 2007

TOP WITH TIES clause in SELECT queries

The SELECT TOP N query always returns exactly N records, and randomly drops any record that have the same value as the last record in the group.

SELECT TOP 5 price, Booktitle FROM BookTitles ORDER BY price DESC

This query will give 5 records from table BookTitles in descending order by price. Problem over here is Suppose the last book title has a price tag of $19.99. The BookTitles table contains two more books with the same price, but they are ignored by the TOP clause.

To see those recrods add the WITH TIES clause...

SELECT TOP 5 WITH TIES price, Booktitle FROM BookTitles ORDER BY price DESC

**WITH TIES will only work with Order by Clause.

Tuesday, November 13, 2007

How to display your own logo in the address bar?

If you need to put your website logo in the top address bar instead of browser's logo then follow these steps.
1. Add a file called "favicon.ico" (an icon file of your website logo) to your website root directory.
2.Insert the following HTML tag inside the <head> ... </head> section of your web page.
<link rel="shortcut icon" href="favicon.ico" >

**If you are working with master pages then put this code in head section of master page otherwise you have to put this code in every page.


Sunday, November 04, 2007

Asp.Net 2.0 File Upload Control

ASP.Net 2.0 comes up with a completely new File Upload Control. This is how you can declare the file upload control.
<asp:FileUpload id="FileUpload1" runat="server" />

Here are some useful properties:-
FileUpload1.FileName :- Will give File Name with the full Path. FileUpload1.PostedFile.FileName :- Will give only the file name. FileUpload1.PostedFile.ContentLength :- will give size of the file in Bytes. FileUpload1.PostedFile.ContentType :- will give MIME type of uploaded file, i.e. "image/gif".

**Don't use file upload control within Update Panel as it is not supported by update panel.

By Default, maximum allowed size for file is 4MB. To allow files larger than the default of 4MB, one need to change the web.config.There is a parameter called maxRequestLength which takes value in the KB.

<httpRuntime executionTimeout="1000" maxRequestLength="1048576"/>

The maxRequestLength property dictates the size of the request made to the Web server.When you upload files, the file is included in the request.

This example changes the maxRequestLength property's value to 1048576KB (around 1GB). With this setting in place, end users can upload 1Gb file to the server.

There is a one more property named "executionTimeout".This property sets the time (in seconds) for a request to attempt to execute to the server before ASP.NET shuts down the request (whether or not it is finished). The default setting is 90 seconds.
The end user receives a timeout error notification in the browser if the time limit is exceeded. If you are going to permit larger requests, remember that they take longer to execute than smaller ones. If you increase the size of the maxRequestLength property, you should examine whether to increase the executionTimeout property as well.

Uploading files in ASP.NET is very inefficient.When you pick a file and submit your form, IIS needs to suck it all in and only then you have access to the properties of uploaded file(s).You can not do about the fact that you have to sit through a long upload and wait. Neither can you display a meaningful progress bar because there’s no way to know how much is transmitted at any given time.Once IIS buffers your upload, ASP.NET takes it from there.

You might receive errors when your end users upload files to your Web server through the FileUpload control in your application. These might occur because the destination folder on the server is not writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder's properties.

Monday, October 22, 2007

How Data Grid rendered in FireFox

It is very surprising that how Data Grid is rendered in FireFox. Black lines for rows and columns are drawn which is not the case with IE. It is like a table which is having border color set to black. If any style or themes is applied then also it is of no use. If you try to see the source of the page you will not find anything which is causing this problem.

I have also encountered the same problem when my QA engineer reported me that some black lines are appearing when I try to open page X in FireFox. I tried to find am I doing anything wrong with the CSS file or with my Skin file but that was not the problem.

After some googling, I found the solution but not the cause. The solution is set style property of Data Grid to “border-collapse: separate”. When I applied the same style to my page, no black color lines were appearing on the page with FireFox.

I am still wondering about the cause and how this particular style solves my problem.
Well, this world is full of strange things.

Happy Programming…

Thursday, October 18, 2007

To refresh Parent Window from Pop Up Window

Sometimes it is required to refresh your Parent Window through Child Window, Here is a small piece of java script code which will solve your problem.


Put this code in any function of Child Window. When that function is called parent window will be reloaded.

How to send Mail From Sql

This is a very common situation when it is required to send mails. There are so many ways to send mail.

The very common is Sql mail. Through Sql server 2005 you can send mail.

There are two methods available
1.DataBase Mail
2. Thorugh OLE

Here is the Stored Procedure to send mail through OLE.

Just copy this prodedure and run it in your database...

--WSA_sp_SendEmail 'virendra@mailserver.local','virendra@mailserver.local','Hi','Test Mail From CDO'
CREATE PROCEDURE [dbo].[WSA_sp_SendEmail]
@From varchar(100),
@To varchar(1000),
@Subject varchar(250),
@Body varchar(max),
@CC varchar(1000) = null
Declare @iMsg int
Declare @hr int
Declare @source varchar(255)
Declare @description varchar(500)
Declare @output varchar(1000)
EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT
Print @From
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("").Value','2'
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("").Value', ''
EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null
--Print @To
EXEC @hr = sp_OASetProperty @iMsg, 'To', @To
EXEC @hr = sp_OASetProperty @iMsg, 'From', @From
if (@Cc <> '')
EXEC @hr = sp_OASetProperty @iMsg, 'Cc', @Cc
EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject
EXEC @hr = sp_OASetProperty @iMsg, 'HtmlBody', @Body
EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL
IF @hr <>0
select @hr
--print @hr
EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT
Print @hr
IF @hr = 0
SELECT @output = ' Source: ' + @source
PRINT 'hi'
PRINT @output
SELECT @output = ' Description: ' + @description
PRINT @output
PRINT ' sp_OAGetErrorInfo failed.'
EXEC @hr = sp_OADestroy @iMsg

*Please change the SMTP server address in the Procedure. Currently it is set to, Change this address according to your SMTP server Address.

To send the mail one have to "Enable OLE Automation".

Go to Sql server source configuration area and enable OLE Automation from the options list.

Sql server Source Configuration area is under Start->Microsoft Sql Server-> Configuaration Tools..

Enjoy Mailing

Sunday, October 14, 2007

Difference between theme and stylesheetTheme attribute.

The Page directive includes the attribute Theme and StylesheetTheme.You can use both to apply themes to a page. So, the question is: If you have a Theme attribute and a StylesheetTheme attribute for the Page directive, what is the difference between the two?

<%@ Page Language=”VB” StylesheetTheme=”Theme1” %>

The StylesheetTheme attribute works the same as the Theme attribute in that it can be used to apply a theme to a page. The difference is that the when attributes are set locally on the page within a particular control, the attributes are overridden by the theme if you use the Theme attribute. They are kept in place, however, if you apply the page’s theme using the StylesheetTheme attribute. Suppose you have a text box control like the following:

<asp:Textbox ID=”TextBox1” Runat=”server”
ForeColor=”#ffffff” />

In this example, the ForeColor settings is overridden by the theme if you have
applied it using the Theme attribute in the Page directive. If, instead, you applied the theme using the StylesheetTheme attribute in the Page directive, the ForeColor settings remain in
place, even if they are explicitly defined in the theme.

Thursday, October 11, 2007

ref and out in C#

When we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable.

Even the variable passed as out parameter is similar to ref, but there are few implementation differences when you use it in C# .

Argument passed as ref must be initialized before it is passed to the method, where as in case of out its is not necessary,but after a call to the method as an out parameter the variable must be initialized.

When to use ref and out parameter. out parameter can be used when we want to return more than one value from a method.


Change Url of Popup without closing it

On one of my project, I encountered a problem.I have 2 buttons on the page and on click of any button i have to open a pop up window.
Let's say on click of button 1 -> pop up window should open with Page1.aspx
and on click of button 2 -> pop up window should open with Page2.aspx.

But the problem was I have to use only one instance of pop up window.One way is I can close the existing pop up window and open another will other Url.But this is not I want.

I want to use the same window and if it is open just change the Url.

After some googling I Found a solution:-

var childRef = null;

function openpopup(page)
if (childRef == null childRef.closed)
childRef = , '');
return false;

This Java Script function was called onClientClick event of the button and respective page value was passed as parameter.

ChildWindowObject.Location.href = Some Url does the trick for me.It will change the Url of popup.

One thing to notice here..

If I dont use childRef.focus(); this code then what is going to happen If the pop up window is open (not Minimized) and when childRef.location.href=page; this gets excuted pop up window will be minimized automatically.

To keep it not minimized I used childRef.focus();. This will set the focus again on the window.


Happy Programming...

Parse and TryParse

Parse method is used to parse any value to specified data type.
For example

string test = "42";
int32 Result;
Result = Int32.Parse(test);

This will work fine bt what if when you are aware about the value of string variable test.

if test="abc"....

In that case if u try to use above method, .NET will throw an exception as you are trying to convert string data to integer.

TryParse is a good method if the string you are converting to an interger is not always numeric.

if(!Int32.TryParse(test,out iResult))
//do something

he TryParse method returns a boolean to denote whether the conversion has been successfull or not, and returns the converted value through an out parameter.

**declare variable iResult of Int32.


Wednesday, October 03, 2007

ASP.NET 2.0 Features: app_offline.htm

There is a simple way to bring down your ASP.NET 2.0 application. The only thing you have to do is to create simple html file called App_offline.htm and deploy it to your ASP.NET 2.0 web application root directory. The rest is handled by ASP.NET runtime internal routines.

The way app_offline.htm works is that you put the file in the root directory of the application. When ASP.NET sees it, it will shut-down the app-domain for the application (and not restart it for requests) and instead send back the contents of the App_offline.htm file in response to all new dynamic requests for the application. When you are done updating the site, just delete the file and it will come back online.

Friday, September 07, 2007

Assign Value to Asp.Net TextBox with mode="Password"

ASP.NET server control doesn't want toadd/display the value in a password textbox because of security concerns.
you have to add it yourself using an attribute.

Add this following line of code when you want set the value

TextBox1.Attributes.Add("value", "thePassword")
*( TextBox1 is a password textbox.)

While given solution will work, if a user does a view source onthe form, the password is visible as plain text and that is never goodfrom a security standpoint.

Rather, I would use Viewstate to hold the password value and if the userdoesn't change it then retrieve the value from view state.

Other Scenario is:-

On most of the web sites at the time of registration password is asked.You must have noticed after submitting the page if you are again redirected to the page due to unsuccessful registration value of password field is lost.

This is due to security concerns as everything is gets rendered on the client side So when you view the source in the browser password value will be there.

But if explicitly you want to set the value of password text box again then use following method in .NET 2.0
txtPassword.Attributes["value"] = Request.Form[txtPassword.ClientID]; //in C#.Net 2.0


Thursday, August 30, 2007

Avoid Cross Threaded Calls..

I was developing a TCP/IP based Chat Application.

When i was sending the data from the server to the client using send method of Socket Class Object and on the client side i was receiving the data using the BeginReceive andEndReceive method of socket class.
Till here it's functioning properly but when i assigned the content sent by the server to the textbox .NET throws an exception
*Cross Threaded call are not allowed. ThisText box is defined in some other thread.*

I searched a lot on this to find the solution.

Finally I got the solution.

The solution is :-

The solution is to write
Control.CheckForIllegalCrossThreadCalls =false;
in Page Load
CheckForIllegalCrossThreadCalls is a static propertyin the load event handler of the main form.

(Don't worry if this property doesn't appear in the intellisense menu )

This problem happens because a thread other than the one who created a control is attempting to modify its properties.


Difference Between RegisterClientScript & RegisterStartupScript

The main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing /form element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page.

Both of these methods take two strings as input. The second parameter, script , is the client-side script-including the opening and closing script tags. The first parameter, key , serves as a unique identifier for the inserted client-side script.

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's <form runat="server"> element.

The code cannot access any of the form's elements because, at that time, the elements haven't been instantiated yet. This explains why hdnView variable had a null value in my case. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's <form runat="server"> element.

The code can access any of the form's elements because, at that time, the elements have been instantiated. The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

As for example if you have declared a hidden variable and want to use in your java script by any of these method then java script method registred with RegisterClientScriptBlock method won't be able to find the hidden variable as the form elements are not instantiated yet.


Wednesday, August 29, 2007

Retrieve Table Name from all the Procedures of any database

In Sql Server 2000 or later versions,

Suppose you have deleted one of the column of any table and now you have to change all your procedures where this column is used.

1. One way is to open every procedure and look for the table and the cloumn name.

2. Second solution is the

Select * from information_Schema.Routines where Routine_Definition like '%table1%'

This Query will allow to find out whether table name specified in where conditoin exists in which Procedures.

INFORMATION_SCHEMA.ROUTINES view is used to retrieve information about stored procedures. This view contains one row for each stored procedure accessible to the current user in the current database.

The INFORMATION_SCHEMA.ROUTINES view was introduced in SQL Server 2000. This view is based on the sysobjects, syscomments and other system tables.


Tuesday, August 28, 2007

Java Script For IE and FireFox

Currently many browsers are available in the market that is making life hell for programmers.

If syntax A is supported by Browser A then this syntax is not supported by Browser B.

The one very interesting I encountered when I was working on one of my project that is how java script supported by browsers.

There is a slight difference how the HTML tags are rendered by IE and FireFox.

Look at this scenario

<Child>Contnet of Child</Child>

This is interpreted in different ways by FireFox and IE.

How IE interprets

IE considers <parent>has a single child node called <child>

How FireFox interprets

On every new line, FireFox inserts empty text node. In the above case FireFox considers there are 3 child nodes.

This is how these tags will be rendered in FireFox

<Empty Text node 1>
<Child>Contnet of Child</Child>
<Empty Text node 2>

So, you see, first Child is the for IE, but an Empty text Node for FireFox.

The solutions may be:-

1. Put Everything in a single line:- <parent> <Child>Contnet of Child</Child> </parent>

But it is very impractical solution.

2. Change the ways you access the nodes.

First of all determine the browser used by the user.

function checkBrowser()
var browser=navigator.appName;
if (browser == "Microsoft Internet Explorer" )
return 0;
else if (browser == "Netscape")
return 1;

Once the browser is determined then return respectively value of the index variable from the function.

Now this index variable will be used to access the control in Java Script.

function checkValue()
var index;
var rowNo = 1;
index = checkBrowser();
var o = document.getElementById('<%=dgSystemList.ClientID%>');
var chk1= o.rows[rowNo].cells[0].childNodes[index];

Note:-This function is just for sample.

One thing to notice there are two ways to access child nodes.

1. children
2. childNodes

The Problem with the first method is that it is not compatible with firefox. It is working fine for IE.

Second method works fine for both the browsers.

To make your code compatible with both the browsers use childNodes method.
Hope this helps…

back to top