Monday, November 24, 2008

JavaScript Tutorials Part-III

  • Script for Closing window if opened Independently:


window.onload=function()

{

if(!window.opener)

window.close();

}


  • Script for Clear Authentication Cookie:

function _spBosyOnLoad()

{

try

{

document.execCommand(“ClearAuthenticationCache”);

window.close();

}

catch(e){}

}

JavaScript Tutorials Part-II

  • Script for watercolor logo:


<script language="JavaScript1.2">

if (document.all||document.getElementById)

document.body.style.background="url('logo1.jpg') white center no-repeat fixed"

script>

With in the body tag code.

  • Script for Domain Info:


<script type="text/javascript">

document.write(document.domain+'
'
);

document.write(document.referrer +'
'
);

document.write(document.URL +'
'
);

document.write("This document contains: " + document.forms.length + " forms."+'
'
);

document.write("This document contains: " + document.images.length + " images."+'
'
);

document.write("This document contains: " +document.anchors.length+ " anchors."+'
'
);

document.write(document.title);

script>

  • Script for Say about mouse click:


<body onmousedown="whichButton(event);">

<script type="text/javascript">

function whichButton(event)

{

if (event.button==2)

{

alert("You clicked the right mouse button!");

}

else

{

alert("You clicked the left mouse button!");

}

}

script>

  • Script for Ctrl+C:


<script language="javascript" type="text/javascript">

function onKeyDown() {

// current pressed key

var pressedKey = String.fromCharCode(event.keyCode).toLowerCase();

if ((event.ctrlKey && (pressedKey == "c")) )

{ // disable key press porcessing

event.returnValue = false;

}

} // onKeyDown

script>


  • Script for Disable Right Click:


<script language="javascript" type="text/javascript">

document.onmousedown=disableclick;

status="Right Click Disabled";

function disableclick(e)

{

if(event.button==2)

{

alert(status);

return false;

}

}

script>


  • Script for Disable Selection in WEB Page:


<body onkeydown="onKeyDown()" oncontextmenu="return false" ondragstart="return false" onselectstart="return false">


  • Script for BookMark:


function addBookmark(title, url) {

if (window.sidebar) { // firefox

window.sidebar.addPanel(title, url,"");

}

else if( document.all ) { //MSIE

window.external.AddFavorite( url, title);

}

else {

alert("Sorry, your browser doesn't support this");

}

}

JavaScript Tutorials

HTML clipboardHTML clipboard
  • Script for No Enter Action:
JavaScript function for No Action when enter button is pressed in the page.

function noenter()
{
var key;
if(window.event)
key = window.event.keyCode; //IE
return (key!= 13); //13 ASCII code
}

the page_load event call this method as:

this.Form.Attributes.Add("onkeypress", "return noenter()");

  • Script for Browser Back Disable & Browser Back:
<scripttype ="text/javascript">
javascript:window.history.forward(1);<script>

javascript:history.back(1)and also for Browser back.

  • Script for Right Click Disable:
<body onContextmenu = "alert('Right Click not Allowed!');return false;">

  • Script for alert message while closing (Unloading) the Page:
<body onbeforeunload="alert('You are about to close the window');">

Wednesday, June 25, 2008

What ASP.NET Programmers Should Know About Application Domains

A process contains the executable code and data of a program inside memory it has reserved from the operating system. There will be at least one thread executing instructions inside of the process, and in most cases there are multiple threads. If the program opens any files or other resources, those resources will belong to the process.
A process is also boundary. Erroneous code inside of a process cannot corrupt areas outside of the current process. It is easy to communicate inside of a process, but special techniques are required to communicate from one process to another. Each process also runs under a specific security context which can dictate what the process can do on the machine and network.
A process is the smallest unit of isolation available on the Windows operating system. This could pose a problem for an ISP who wants to host hundreds of ASP.NET applications on a single server. The ISP will want to isolate each ASP.NET application to prevent one application from interfering with another company’s application on the same server, but the relative cost of launching and executing a process for hundreds of applications may be prohibitive.

Introducing the Application Domain
.NET introduces the concept of an application domain, or AppDomain. Like a process, the AppDomain is both a container and a boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside of a secure boundary.
Note, however, that the application domain is not a secure boundary when the application runs with full trust. Applications running with full trust can execute native code and circumvent all security checks by the .NET runtime. ASP.NET applications run with full trust by default.
An AppDomain belongs to only a single process, but single process can hold multiple AppDomains. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomains can exist inside of a single process – a cost savings.

AppDomains And You
You’ve created two ASP.NET applications on the same server, and have not done any special configuration. What is happening?
A single ASP.NET worker process will host both of the ASP.NET applications. On Windows XP and Windows 2000 this process is named aspnet_wp.exe, and the process runs under the security context of the local ASPNET account. On Windows 2003 the worker process has the name w3wp.exe and runs under the NETWORK SERVICE account by default.
An object lives in one AppDomain. Each ASP.NET application will have it’s own set of global variables: Cache, Application, and Session objects are not shared. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain. If there are classes with shared or static members, and those classes exist in both applications, each AppDomain will have it’s own copy of the static fields – the data is not shared. The code and data for each application is safely isolated and inside of a boundary provided by the AppDomain
In order to communicate or pass objects between AppDomains, you’ll need to look at techniques in .NET for communication across boundaries, such as .NET remoting or web services.
Note again: the one caveat to the idea of an AppDomain as a boundary is that ASP.NET applications will run with full trust by default. Fully trusted code can execute native code, and native code can essentially have access to anything inside the process. You’ll need to run applications with partial trust to restrict access to unmanged code and verify all managed code to secure AppDomains.

Shadow Copies and Restarts
Once an assembly is loaded into an AppDomain, there is no way to remove the assembly from the AppDomain. It is possible, however, to remove an AppDomain from a process.
If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.
Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.
The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.

Master Of Your Domain
Application domains replace the OS process as the unit of isolation for .NET code. An understanding of application domains will give you an idea of the work taking place behind the scenes of an ASP.NET application. Using the CurrentDomain property of the AppDomain class you can inspect properties about the AppDomain your code is executing in, including the Shadow Copy settings we discussed in this article.
Summary
The logical and physical boundary created around every .NET application by the Common Language Runtime (CLR). The CLR can allow multiple .NET applications to be run in a single process by loading them into separate application domains. The CLR isolates each application domain from all other application domains and prevents the configuration, security, or stability of a running .NET applications from affecting other applications. Objects can only be moved between application domains by the use of remoting.
Reference : Scott Allen Post

Friday, May 30, 2008

IsNumeric in C# without try parse or try catch

This is something that has bothered me for a long while now. Why doesn't C# have a IsNumeric(string num) function like VB.NET?
I have used every kind of IsNumeric code you can think of... This is what I started with.

public bool IsNumeric(string s)
{
try
{
Int32.Parse(s);
}
catch
{
return false;
}
return true;
}

But we all no the unspoken rule, NEVER use try, catch for functionality... So I tried this.

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i < ca.Length;i++)
{
if (ca[i] > 57 || ca[i] < 48)
return false;
}
return true;
}

Then I found char.IsNumber: (Why do they have a char.IsNumber, but no string.IsNumeric???)

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i < ca.Length;i++)
{
if (!char.IsNumber(ca[i]))
return false;
}
return true;
}

With the help of some friend (Thanks Dawid), I finally got this. What do you think?

public static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}

Monday, May 12, 2008

What are the Differences Between SQL Server 2000 and SQL Server 2005?

I've been asked this question every time that there's a new version and yet I've never been able to give what I think is a nice, concise, logical answer that satisfies the asker. Probably it's a lack of my ability to easily form words in my mouth and get them out in the proper order, so I decided it might make some sense to do this on paper (metaphorically speaking) and help others out.

Like many of you, I usually get this question from someone outside of SQL Server. A windows admin, a network guy, etc., someone who has little contact with SQL Server. Or maybe it's someone who's been stuck with admin'ing a SQL Server instance.

In any case, I wanted to try and explain this concisely for the non-DBAs. As I began this project, however I soon realized that it's not easy to just give a good general answer. As with everything else in SQL Server it seems that "it depends" is the best general answer, so I broke this up into a few areas. This part will look at the administrative differences and the next will cover more of the development differences.
The Administrative Differences

Administering a SQL Server instance to me means making sure the server service runs efficiently and is stable and allows clients to access the data. The instance should keep data intact and function according to the rules of the code implemented while being well maintained.

Or for the non-DBAs, it means that you are the sysadmin and it just works.

The overall differences are few. Sure we use Management Studio instead of Enterprise Manager, but that's not really a big deal. Really many of the changes, like being able to change connections for a query, are superficial improvements that don't really present a substantial change. If you think they do, you might be in the wrong job.

Security is one area that is a very nice improvement. The separation of the schema from the owner makes administrative changes easier, but that is a big deal because it greatly increases the chances you won't keep an old account active because it's a pain to change owners on objects. There's also more granularity and ease of administration using the schema as another level of assigning permissions.

Another big security change is the ability to secure your web services using certificates instead of requiring authentication using a name and password. Add to that the capability to encrypt data, and manage the keys, can make a big difference in the overall security of your data. You have to carefully ensure your application and access is properly secured, but just the marketing value of encryption when you have credit card, financial, or medical data is huge. SQL Server 2000 had no real security features for data, allowing an administrator to see all data. You could purchase a third party add-on, but it was expensive and required staff training. Not that you don't need to learn about SQL Server 2005, but it should be a skill that most DBAs will learn and be able to bring to your organization over time.

High availability is becoming more and more important to all sizes of businesses. In the past, clustering or log shipping were your main choices, but both were expensive and required the Enterprise Edition. This put these features out of the reach of many companies, or at least, out of many DBAs' budgets. With SQL Server 2005, you can now implement clustering, log shipping, or the new Database Mirroring with the Standard edition. With the ability of Database Mirroring to use commodity hardware, even disparate hardware between the primary and mirror databases, this is a very reasonable cost solution for almost any enterprise.

There are also online indexes, online restores, and fast recovery in the Enterprise Edition that can help ensure that you take less downtime. Fast recovery especially can be an important feature, allowing the database to be accessed as the undo operations start. With a log of open transactions when a database is restarted, this can really add up to significant amounts of time. In SQL Server 2000, you had to have a complete, intact database before anyone could access it. With redo/undo operations sometimes taking a significant amount of time, this could delay the time from Windows startup to database availability by minutes.

Data sizes always grow and for most companies, performance is always an issue on some server. With SQL Server 2000, you were limited to using 2GB of RAM and 4 CPUs on the Standard Edition. The number of CPUs hasn't changed, but you can now use as much RAM as the OS allows. There also is no limit to the database size, not that the 1,048,516 TB in SQL Server 2000. Since RAM is usually a limiting factor in the performance of many databases, upgrading to SQL Server 2005 could be something you can take advantage of. SQL Server 2005 also has more options and capabilities on the 64-bit platform than SQL Server 2000.
Why Upgrade?

This is an interesting question and one I've been asked quite a bit over the last 18 months since SQL Server 2005 has been released. The short answer is that if SQL Server 2000 meets your needs, then there's no reason to upgrade. SQL Server 2000 is a strong, stable platform that has worked well for millions of installations. If it meets your needs, you are not running up against the limits of the platform, and you are happy with your system, then don't upgrade.

However, there is a caveat to this. First the support timeline for SQL Server 2000 shows mainstream support ending next year, in April 2008. I can't imagine that Microsoft wouldn't extend that given the large number of installations of SQL Server 2000, but with the next version of SQL Server likely to come out next year, I can see this being the point at which you cannot call for regular support. The extended support timeline continues through 2013, but that's an expensive option.

The other consideration is that with a new version coming out next year, you might want to just start making plans to upgrade to that version even if you're happy with SQL Server 2000. If the plan is to release a new version every 2-3 years, you'll need to upgrade at least every 5-6 years to maintain support options.

Be sure that in any case you are sure the application you are upgrading, if it's a third party, is supported on SQL Server 2005.

Lastly, if you have multiple servers and are considering new hardware for more than 1 of them, it might make some sense to be sure to look at buying one large 64-bit server and performing some consolidations. I might recommend that you wait for the next version of SQL Server if you are worried about conflicts as I have heard rumors of switches to help govern the resource usage in Katmai (SQL Server 2008).

A quick summary of the differences:

Feature SQL Server 2000 SQL Server 2005
Security Owner = Schema, hard to remove old users at times Schema is separate. Better granularity in easily controlling security. Logins can be authenticated by certificates.
Encryption No options built in, expensive third party options with proprietary skills required to implement properly. Encryption and key management build in.
High Availability Clustering or Log Shipping require Enterprise Edition. Expensive hardware. Clustering, Database Mirroring or Log Shipping available in Standard Edition. Database Mirroring can use cheap hardware.
Scalability Limited to 2GB, 4CPUs in Standard Edition. Limited 64-bit support. 4 CPU, no RAM limit in Standard Edition. More 64-bit options offer chances for consolidation.
Conclusion

These seem to be the major highlights from my perspective as an administrator. While there are other improvements, such as the schema changes flowing through replication, I'm not sure that they represent compelling changes for the non-DBA.

In the next article, I'll examine some of the changes from a developer perspective and see if any of those give you a reason to upgrade.

And I welcome your comments and thoughts on this as well. Perhaps there are some features I've missed in my short summary.

Friday, May 9, 2008

Know- Knowledge or No Knowledge About DataSources

AccessDataSource
Provides binding to a Microsoft Access database file that has the .mdb extension.

SqlDataSource
Provides binding to an Open Database Connectivity (ODBC), Object Linking and Embedding Database (OLEDB), SQL Server, Oracle, or other database that uses Structured Query Language (SQL). You can even attach to a SQL Server database file by simply including it in your project.

XmlDataSource
Provides binding to an XML file in your project folder. You can specify a transform file that can be used to modify the XML file before it is bound to a control. You can also provide an XPath expression to retrieve a subset of the data in the XML file.

ObjectDataSource
Provides binding to an object. The ObjectDataSource can connect to a middle-tier business object or DataSet object in the Bin or App_Code directory of your application.
When using this option, you can select a class that you have access to, and an instance of the class is created for you each time that data is required. In addition to selecting a class, you must choose the methods you want to execute to select, insert, update, and delete. The select method should return a single object that implements IEnumerable, IListSource, IDataSource, or IHierarchicalDatasource. This means that a DataTable object, a DataSet object, or a collection object can be used. If the select method returns a DataSet object, the first DataTable object in the DataSet is used.

SitemapDataSource
You can connect to the site navigation tree for your application.
This option requires a valid sitemap file at the application root.

A server control is a control that is programmable by writing server-side code to respond to events from the control.

Server controls contain the runat="server" attribute.

HTML server controls are useful when ASP Web pages need to be migrated to ASP.NET 2.0 pages.

HTML server controls are also useful when the server control has a lot of client-side JavaScript.

Web server controls are much more powerful than HTML controls because a single
Web server control can render as many HTML elements and JavaScript code blocks.

ViewState is the mechanism by which Web page object and child control object data can be maintained between page requests.

Post From,
Mansoor Ali

Wednesday, April 23, 2008

Usefull Tips for Interview Questions for Experienced

1. Tell me about yourself and your past experience?
This is one of the most commonly asked interview questions and it is generally used as an icebreaker. Unfortunately, people tend too talk too long and too much. You should try to allow 1-3 minutes for this question. You should cover your background, what you currently do, your assets, your education- subjects studied, choice of university, degree, and current relevant studies, a summary of your career to date, and key achievements.
2. What are your strengths and weaknesses?
Pick a weakness that could also be consider strength. "Sometimes I'm overly concerned with doing a good job and my boss tells me I drive myself too hard." Then mention your strengths: your ability to get the job done efficiently and on time; your pride in your work. Or also you can tell, my strength is my flexibility. As director of operations at a startup company, I've had to deal with and handle changes and new policies constantly. As far as weaknesses, I really enjoy my work, and sometimes I put in too much time on some projects. But by being aware of my tendency, I have learned to work smarter.
3. Why are you leaving your current job?
Forget about the fact that you hate your boss and your co-workers drive you crazy. Instead, say, "I'm ready to take on more responsibilities and learn more, but the opportunities at my current job are limited. Or I've set some goals for myself and my career, and unfortunately I'm at a standstill in my current situation. I have begun to explore options available before I spend too much time in a job where I can't advance. My goal is to continue to take on new responsibilities and be a key contributor to the success of an online venture."
4. Why do you change jobs so often?
"Mainly to learn and advance. I understand there's a lot of room for growth here, and I hope to stay a long time if I'm offered the job."
5. Did you get along with your previous boss?
If you didn't, and know you can't use her as a reference, be candid but not bitter or complaining. "She's very professional and taught me a lot, and I'm grateful for that. But I would have liked more responsibilities than I was offered.
6. What did you like/dislike about your previous manager?
The interviewer is trying to establish how you interact with authority, what characteristics you admire and what you dislike in line managers. Managers have a job to do and staff that acknowledges authority is more likely to fit in than those who don't. The interviewer will be able to judge from your response if you can carry out reasonable requests and understand the role of a line manager. You should emphasise good traits such as the ability to give clear direction, inspire staff, act as a mentor, always encourages staff to do their best and overcome obstacles, and stands up for staff when right. Dislikes should be avoided and you can actually say that you didn’t really dislike anything but you do understand that managers do have to make unpopular decisions sometimes.
7. If we phoned your previous employer/manager, what would they tell us about you?
A common question asked at interviews. It puts you on the spot and first reactions are interesting. The interviewer would like to hear that the former employer would re-employ you and you were reliable, dependable, got on well with others, and could work unsupervised. Other comments would indicate that you were flexible with hours, had a good attitude, and picked up new things quickly. He doesn't want to hear that there were personality clashes, that you didn't get on, was unreliable, lacked integrity, or needed close supervision.
8. What do you know about our company?
Nothing impresses an interviewer more than detailed answers to this question. It shows you have taken initiative to research the people and company. Discussing details of the Board of Directors, company subsidiaries, countries in which the company operates, its products, its key people, as well as statistics relating to turnover, number of employees, trends in the industry, and profitability will score points with even the most stubborn recruiters. These details are on record in the company’s portfolio or your local library. You can request any general information and brochures from the company secretary prior to the interview. Your local library will hold industry surveys or “Key Notes” reports on the industry. You can request a company prospectus or its last annual accounts if the company is listed on any of the stock exchanges. See if the company has a web site and visit it for more information. Follow any links to similar sites to view competitors or get an industry overview. If you know someone who has worked there, ask him about the company and its culture. If you used an agency to find you the position, their staff will probably have information about the company on file or they can find out about it or its key officers for you. If the recruitment agency has placed candidates with the target company before, they could advise you about the recruitment process and interview style. You may be offered the opportunity to be shown around the company on an open day or as part of recruitment fair or a pre-interview tour. Use this opportunity to talk to people and gather other intelligence that may be useful in the interview.
9. If you lack experience, what do you have to offer?
Quite often a candidate may be new to a role as in a graduate trainee or a school leaver applying for the job for the first time. It's catch 22- you have no experience so why should they hire you? If you have good grades, talk about how they are indicative of your potential to learn quickly and achieve results. You can change the ballpark and talk about any transferable skills or characteristics you may have from your last job. Be prepared to justify the characteristics with examples of how you have demonstrated them in the past. You can select what's appropriate out of the following: passion, loyalty, dedication, good communication skills, ability to deal with a wide range of people, initiative, independence, drive, good oral and written skills, literacy, numeracy, presentation skills, ability to close deals, ability to make openings, ability to learn quickly, ability to adapt, flexibility, and computer literacy - both hardware and software.
10. How would your boss describe you and your work style?
"First, she'd say I have a lot of initiative - I see a big picture and do what has to be done to achieve results. Secondly, that I have business savvy - I know the business side as well as the technical side. And thirdly, I have a high work ethic - if I say I'm going to do something, I do it."
11. Why didn't you go further in school?
"At the time, earning a living was more important. But I'm thinking of furthering my education now."
12. What do you do in your spare time?
Say you keep up with current events and have been reading a best-selling business book (do it). Talk about any community activities you're involved in, but stress that those commitments won't interfere with work.
13. What interests you most about this position?
Stress the opportunity you'll have to grow, learn and acquire new skills.
14. What interests you least about this position?
Even if you hate filing, don't say so. Say, "I really don't see any major negatives. I can use the skills I already have and also learn new ones."
15. Why should we hire you?
This is a tough question and should be treated as if you were being asked about your strengths. Relate your strengths to the requirements of the job and pull it all together. Response to this should be that you think it is a job that you will be good at and give examples of skills, past experience, and accomplishments that will be useful for the position. Give examples of your network of contacts that you can bring to the company, talk about the heavy investment in your training and development that your past employers have made in you and that your new employer will get this relatively for no additional cost (emotional intelligence). You can say that you have already made some of your biggest mistakes and learned from them and now can bring the years of experience to your new employers and hit the floor running. You can say that you’re a source of “new blood” and can bring new ideas and alternative ways of looking at things and tackling problems to complement the team within the hiring company. If you are articulate, state that you can communicate at all levels of management. Add commitment, tenacity, computer literacy, and flexibility, to these other factors. Eg:"I love a challenge and I'm a fast learner. I have experience in this area, so I'll be able to start with some idea of what I'm doing. Everything I know about this company makes me feel we'd be a good match."
16. What experience have you had that qualifies you for this position?
"I have experience working with e-commerce companies on the consulting side. I've managed teams and have strong experience with HTML and ASP. My communication skills and business acumen are my strengths. I can wear many hats and believe I can bring added value to a team effort."
17. What attracted you to this job?
"I've been searching for a while now to find a company that had a business model and corporate philosophy like yours. I am interested in working for a company that provides products and services to the K-12 education market. My background is in this field, and my strength is in building relationships and solving problems. I am excited and interested in the idea of developing business relationships through e-commerce."
18. What are your salary expectations?
"I really need more information about the job before we start to discuss salary. I'd like to postpone that discussion until later. Could you tell me what is budgeted for the position?"
19. What qualities do you think are important to this position?
"To have a combination of technical and business knowledge and to be very results-oriented. My past record shows that I have those qualities and more. Because of my business acumen and technical know-how, the teams I have managed accomplished outstanding results, including booking more than $50 million in online revenue."
20. When have you been most motivated?
"My first job in a Software Eng. I had to undergo some rigorous training to understand the product and customer. At the same time, we were actually working with the customer. It required a lot of self-direction and motivation. I thrived on the whole experience - the discipline, the planning and the deadlines. It was a pressure cooker, but I got through it."
21. How long do you see yourself with us?
I see myself here as long as we both think that I am contributing to the vitality (life) of the company while still being grown through challenges.
22. Do you have any questions?
(This is usually asked by the interviewer at the end of the interview.). "Yes, I do. Who are your financial backers? Who are the key competitors? Does the company have a plan for the IPO? What would you say is the best thing about your product/service?"

Difference between Datagrid , Datalist, FormView

All these controls are ASP.NET data-bound controls

The DataGrid control renders a tabular, data-bound grid. This control allows you to define various types of columns to control the layout of the cell contents of the grid (bound columns, template columns) and add specific functionality (such as edit button columns, hyperlink columns, and so on). The control also supports a variety of options for paging through data.

FormView class provides a standard MMC Windows Forms view. It allows the result pane to be populated with a Windows Forms control.


The DataList control displays rows of database information in customizable format. The format in which the data is displayed is defined in item, alternating item, selected item, and edit item templates. Header, footer, and separator templates are also available to let you customize the overall appearance of the DataList. By including Button Web server controls in the templates, you can connect the list items to code that allows users to switch between display, selection, and editing modes.

PostFrom,
Mansoor Ali

Tuesday, April 8, 2008

The ASP.NET Page Life Cycle

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. When we try to build ASP.NET pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. However, when used and manipulated correctly, a page's execution cycle can be an effective and powerful tool. Many developers are realizing that understanding what happens and when it happens is crucial to effectively writing ASP.NET pages or user controls. So let's examine in detail the ten events of an ASP.NET page, from creation to disposal. We will also see how to tap into these events to implant our own custom code.
I'll set the stage with a simple submission form written in ASP.NET with C#. The page is loaded for the first time and has several server-side Web controls on it. When the Web server receives a request for the page, it will process our Web controls and we will eventually get rendered HTML. The first step in processing our page is object initialization.

. 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.



Fig-1

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 < input > 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.



Figure 2 - When LoadViewState is fired, controls are populated with the appropriate viewstate data.

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 (see below).
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. The Load event can be overridden by calling OnLoad as shown in Figure 3.




Figure 3 - The OnLoad event is an ideal location to place logic.

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. The RaisePostBackEvent can be trapped by catching RaisePostBackEvent, as in Figure 4.




Figure 4 - The RaisePostDataChanged and RaisePostBackEvent events are defined by the IPostBackDataHandler interface.

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 < input > 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. You can override this step by using SaveViewState, as shown Figure 5.



Figure 5 - Values are set for controls in OnPreRender. During the SaveViewState event, values are set for the ViewState object.

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. The Render event can be overridden, as shown in Figure 6 (below).
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, as shown in Figure 6.



Figure 6 - The Render event will output custom HTML to the browser through the HtmlTextWriter object.

Conclusion
Each time we request an ASP.NET page, we run through the same process from initialization to disposal. By understanding the inner workings of the ASP.NET page process, writing and debugging our code will be much easier and effective (not to mention less frustrating).