<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Jay Harris is Cpt. LoadTest - Dev Basics</title>
    <link>http://www.cptloadtest.com/</link>
    <description>a .net developers blog on improving user experience of humans and coders</description>
    <language>en-us</language>
    <copyright>Jason Harris</copyright>
    <lastBuildDate>Tue, 26 Apr 2011 23:45:23 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.12105.0</generator>
    <managingEditor>jharris@harrisdesigns.com</managingEditor>
    <webMaster>jharris@harrisdesigns.com</webMaster>
    <item>
      <trackback:ping>http://www.cptloadtest.com/Trackback.aspx?guid=245e0356-23d5-4212-99bf-583840b1e904</trackback:ping>
      <pingback:server>http://www.cptloadtest.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.cptloadtest.com/PermaLink,guid,245e0356-23d5-4212-99bf-583840b1e904.aspx</pingback:target>
      <dc:creator>Jay Harris</dc:creator>
      <wfw:comment>http://www.cptloadtest.com/CommentView,guid,245e0356-23d5-4212-99bf-583840b1e904.aspx</wfw:comment>
      <wfw:commentRss>http://www.cptloadtest.com/SyndicationService.asmx/GetEntryCommentsRss?guid=245e0356-23d5-4212-99bf-583840b1e904</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The first three parts of this series discuss the events that make up the ASP.NET Page
Life Cycle, the order that these events execute on the page and on the controls, and
that necessary evil called Data Binding, through which you add dynamic content to
your new ASP.NET page. Raising those events happens automatically, without any developer
oversight, but tapping in to those events—making them work for you—requires wiring
special methods called Event Handlers to those events. This wiring can happen automatically
by the system if you follow a few simple steps, or it can happen manually, with developers
connecting each appropriate event to its handler. Both sides have their advantages
as well as their drawbacks, but learning the nuances of event wiring can only strengthen
your ASP.NET repertoire.
</p>
        <blockquote>
          <h3>About the Series
</h3>
          <p>
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a "Hello, World!"
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
</p>
          <p>
Part 1: <a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx" target="_blank">Events
of the ASP.NET Page Life Cycle</a><br />
Part 2: <a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx">ASP.NET
Page &amp; WebControl Event Execution Order</a><br />
Part 3: <a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx">Getting
Started with ASP.NET DataBinding</a><br />
Part 4: Wiring Events to your Page
</p>
        </blockquote>
        <h3>Automatic Event Wireup
</h3>
        <p>
Page events can be automatically wired to their event handlers. That is, the code
to assign the event handler to your event can be made optional, with the system automatically
making the connection for the page, and thus, saving the developer a little bit of
work. Automatic event wiring is enabled through a boolean property called AutoEventWireup
on the ASP.NET Page Directive.
</p>
        <pre class="xml:nocontrols" name="code">&lt;%@ Page AutoEventWireup="true" %&gt;</pre>
        <p>
With this attribute set in the page directive, ASP.NET will automatically search for
and wire up any event handlers that match the specific naming convention of Page_<em>EventName</em>,
such as Page_Init or Page_Load. These methods can exist with or without the sender
and EventArgs method arguments, though do note they must both be absent or both be
present from the method signature; you cannot have one without the other.
</p>
        <pre class="csharp:nocontrols" name="code">protected void Page_Init()
{
  //Do some stuff
}

protected void Page_Load(object sender, EventArgs e)
{
  //Do some stuff
}</pre>
        <h3>Drawbacks to Event Auto-Wire
</h3>
        <p>
There is no fancy compiler magic to wire these event handlers to the event; under
AutoEventWireup, ASP.NET wires each event at run time when executing the page. This
means that for every event in the ASP.NET Page Life Cycle, the runtime engine reflects
through your code to search for an appropriate method for that event, just in case
it happens to exist, whether you create a handler method or not. To make matters worse,
it is reflecting for each event twice, once for a method with handler method arguments
(object sender, EventArgs e), and once for a method without the arguments.
</p>
        <p>
There are ten Life Cycle events on the Page that are eligible for auto-wire (counting
the Pre-and Post-Events such as PreInit and InitComplete) and four on the Control;
for a single page with five user controls, .NET Reflection is searching for up to
60 different methods. That is a lot of run-time overhead! Needless to say, AutoEventWireup
can have a significant negative impact on page performance.
</p>
        <h3>Manual Event Wireup
</h3>
        <p>
Page events can also be wired manually. This is similar to wiring up any other .NET
event. Using manual wire, you must explicitly wire the events you need to the appropriate
event handler. However, since you controls the wiring, this allows you to follow any
naming convention you wish and if needed, to wire multiple handlers to an event. Just
remember to turn AutoEventWireup off.
</p>
        <pre class="xml:nocontrols" name="code">&lt;%@ Page AutoEventWireup="false" %&gt;</pre>
        <p>
Page Events can be wired to their handler within your page's constructor.
</p>
        <pre class="csharp:nocontrols" name="code">public MyPageClass()
{
	Init += InitializePage;
	Load += LoadPage;
}

protected void InitializePage(object sender, EventArgs e)
{
  //Do some stuff
}

protected void LoadPage(object sender, EventArgs e)
{
  //Do some stuff
}</pre>
        <h3>Disadvantages to Manual Event Wireup
</h3>
        <p>
There is a little extra work involved to manually wire events. For the two events
from the auto-wire example, add a constructor and two lines of code. However, this
can be a bit of a daunting task if performed against an existing ASP.NET application
with dozens of pages and dozens more user controls. Even on new applications, it can
be easy to forget to wire the event, though it is easily identified in testing since
without the wireup, the handler does not execute, and in most cases, the page does
not function properly.
</p>
        <p>
Another disadvantage is that AutoEventWireup is enabled by default in C# (it is turned
off by default in Visual Basic). Even if you manually wire the events to handlers
in the page constructor, you must remember to disable wireup in the Page Directive.
Fail to do so will cause ASP.NET to wire up the events automatically in addition to
the manual hookup, and the event handler will be executed twice. So, again, don't
forget to turn off AutoEventWireup.
</p>
        <h3>Balancing Effort with Performance
</h3>
        <p>
Using AutoEventWireup essentially comes down to the value of developer effort versus
end-user performance. Auto-wire will save developers from one line of code per event,
but at the cost of system performance due to the reflection that occurs to have the
system wire the events rather than the developer. For a small utility web site or
a demo for a presentation, I can understand using auto-wire. However, being a performance
guy, I want to extract every ounce of horsepower I can out of my web applications,
so I will always opt for manual wiring; with it only costing me one line of code,
I feel that it is a good habit to have.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:8f035b16-2463-44d0-b6aa-1c67e951fb4c" class="wlWriterSmartContent">Technorati
Tags: <a href="http://technorati.com/tags/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag">Page
Life Cycle</a>,<a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag">Event
Life Cycle</a>,<a href="http://technorati.com/tags/Dev+Basics" rel="tag">Dev Basics</a>,<a href="http://technorati.com/tags/Back+to+Basics" rel="tag">Back
to Basics</a></div>
        <img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=245e0356-23d5-4212-99bf-583840b1e904" />
      </body>
      <title>Dev Basics: ASP.NET Page Life Cycle, Part 4 [Event Wireup]</title>
      <guid isPermaLink="false">http://www.cptloadtest.com/PermaLink,guid,245e0356-23d5-4212-99bf-583840b1e904.aspx</guid>
      <link>http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx</link>
      <pubDate>Tue, 26 Apr 2011 23:45:23 GMT</pubDate>
      <description>&lt;p&gt;
The first three parts of this series discuss the events that make up the ASP.NET Page
Life Cycle, the order that these events execute on the page and on the controls, and
that necessary evil called Data Binding, through which you add dynamic content to
your new ASP.NET page. Raising those events happens automatically, without any developer
oversight, but tapping in to those events—making them work for you—requires wiring
special methods called Event Handlers to those events. This wiring can happen automatically
by the system if you follow a few simple steps, or it can happen manually, with developers
connecting each appropriate event to its handler. Both sides have their advantages
as well as their drawbacks, but learning the nuances of event wiring can only strengthen
your ASP.NET repertoire.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;h3&gt;About the Series
&lt;/h3&gt;
&lt;p&gt;
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a &amp;quot;Hello, World!&amp;quot;
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
&lt;/p&gt;
&lt;p&gt;
Part 1: &lt;a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx" target="_blank"&gt;Events
of the ASP.NET Page Life Cycle&lt;/a&gt; 
&lt;br /&gt;
Part 2: &lt;a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx"&gt;ASP.NET
Page &amp;amp; WebControl Event Execution Order&lt;/a&gt; 
&lt;br /&gt;
Part 3: &lt;a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx"&gt;Getting
Started with ASP.NET DataBinding&lt;/a&gt; 
&lt;br /&gt;
Part 4: Wiring Events to your Page
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;h3&gt;Automatic Event Wireup
&lt;/h3&gt;
&lt;p&gt;
Page events can be automatically wired to their event handlers. That is, the code
to assign the event handler to your event can be made optional, with the system automatically
making the connection for the page, and thus, saving the developer a little bit of
work. Automatic event wiring is enabled through a boolean property called AutoEventWireup
on the ASP.NET Page Directive.
&lt;/p&gt;
&lt;pre class="xml:nocontrols" name="code"&gt;&amp;lt;%@ Page AutoEventWireup=&amp;quot;true&amp;quot; %&amp;gt;&lt;/pre&gt;
&lt;p&gt;
With this attribute set in the page directive, ASP.NET will automatically search for
and wire up any event handlers that match the specific naming convention of Page_&lt;em&gt;EventName&lt;/em&gt;,
such as Page_Init or Page_Load. These methods can exist with or without the sender
and EventArgs method arguments, though do note they must both be absent or both be
present from the method signature; you cannot have one without the other.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;protected void Page_Init()
{
  //Do some stuff
}

protected void Page_Load(object sender, EventArgs e)
{
  //Do some stuff
}&lt;/pre&gt;
&lt;h3&gt;Drawbacks to Event Auto-Wire
&lt;/h3&gt;
&lt;p&gt;
There is no fancy compiler magic to wire these event handlers to the event; under
AutoEventWireup, ASP.NET wires each event at run time when executing the page. This
means that for every event in the ASP.NET Page Life Cycle, the runtime engine reflects
through your code to search for an appropriate method for that event, just in case
it happens to exist, whether you create a handler method or not. To make matters worse,
it is reflecting for each event twice, once for a method with handler method arguments
(object sender, EventArgs e), and once for a method without the arguments.
&lt;/p&gt;
&lt;p&gt;
There are ten Life Cycle events on the Page that are eligible for auto-wire (counting
the Pre-and Post-Events such as PreInit and InitComplete) and four on the Control;
for a single page with five user controls, .NET Reflection is searching for up to
60 different methods. That is a lot of run-time overhead! Needless to say, AutoEventWireup
can have a significant negative impact on page performance.
&lt;/p&gt;
&lt;h3&gt;Manual Event Wireup
&lt;/h3&gt;
&lt;p&gt;
Page events can also be wired manually. This is similar to wiring up any other .NET
event. Using manual wire, you must explicitly wire the events you need to the appropriate
event handler. However, since you controls the wiring, this allows you to follow any
naming convention you wish and if needed, to wire multiple handlers to an event. Just
remember to turn AutoEventWireup off.
&lt;/p&gt;
&lt;pre class="xml:nocontrols" name="code"&gt;&amp;lt;%@ Page AutoEventWireup=&amp;quot;false&amp;quot; %&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Page Events can be wired to their handler within your page's constructor.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;public MyPageClass()
{
	Init += InitializePage;
	Load += LoadPage;
}

protected void InitializePage(object sender, EventArgs e)
{
  //Do some stuff
}

protected void LoadPage(object sender, EventArgs e)
{
  //Do some stuff
}&lt;/pre&gt;
&lt;h3&gt;Disadvantages to Manual Event Wireup
&lt;/h3&gt;
&lt;p&gt;
There is a little extra work involved to manually wire events. For the two events
from the auto-wire example, add a constructor and two lines of code. However, this
can be a bit of a daunting task if performed against an existing ASP.NET application
with dozens of pages and dozens more user controls. Even on new applications, it can
be easy to forget to wire the event, though it is easily identified in testing since
without the wireup, the handler does not execute, and in most cases, the page does
not function properly.
&lt;/p&gt;
&lt;p&gt;
Another disadvantage is that AutoEventWireup is enabled by default in C# (it is turned
off by default in Visual Basic). Even if you manually wire the events to handlers
in the page constructor, you must remember to disable wireup in the Page Directive.
Fail to do so will cause ASP.NET to wire up the events automatically in addition to
the manual hookup, and the event handler will be executed twice. So, again, don't
forget to turn off AutoEventWireup.
&lt;/p&gt;
&lt;h3&gt;Balancing Effort with Performance
&lt;/h3&gt;
&lt;p&gt;
Using AutoEventWireup essentially comes down to the value of developer effort versus
end-user performance. Auto-wire will save developers from one line of code per event,
but at the cost of system performance due to the reflection that occurs to have the
system wire the events rather than the developer. For a small utility web site or
a demo for a presentation, I can understand using auto-wire. However, being a performance
guy, I want to extract every ounce of horsepower I can out of my web applications,
so I will always opt for manual wiring; with it only costing me one line of code,
I feel that it is a good habit to have.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:8f035b16-2463-44d0-b6aa-1c67e951fb4c" class="wlWriterSmartContent"&gt;Technorati
Tags: &lt;a href="http://technorati.com/tags/ASP.NET" rel="tag"&gt;ASP.NET&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag"&gt;Page
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag"&gt;Event
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Dev+Basics" rel="tag"&gt;Dev Basics&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Back+to+Basics" rel="tag"&gt;Back
to Basics&lt;/a&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=245e0356-23d5-4212-99bf-583840b1e904" /&gt;</description>
      <comments>http://www.cptloadtest.com/CommentView,guid,245e0356-23d5-4212-99bf-583840b1e904.aspx</comments>
      <category>ASP.Net</category>
      <category>Dev Basics</category>
    </item>
    <item>
      <trackback:ping>http://www.cptloadtest.com/Trackback.aspx?guid=6682b44d-7660-4b5e-8746-bdcfdae81f84</trackback:ping>
      <pingback:server>http://www.cptloadtest.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.cptloadtest.com/PermaLink,guid,6682b44d-7660-4b5e-8746-bdcfdae81f84.aspx</pingback:target>
      <dc:creator>Jay Harris</dc:creator>
      <wfw:comment>http://www.cptloadtest.com/CommentView,guid,6682b44d-7660-4b5e-8746-bdcfdae81f84.aspx</wfw:comment>
      <wfw:commentRss>http://www.cptloadtest.com/SyndicationService.asmx/GetEntryCommentsRss?guid=6682b44d-7660-4b5e-8746-bdcfdae81f84</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The previous installments of this series cover the core events of the ASP.NET Page
class, of the ASP.NET Controls, and how the page and controls work together to co-exist
in the same sandbox. We've gotten to the point where we know how these controls will
interact with the page so that we can make our page more than just a sea of crazy
peach gradient backgrounds, but that still isn't enough. Static content is so 1999,
and that party broke up long ago. The next step in a quality, modern web site is creating
dynamic content, and rendering it to the page. To do this, we need Data Binding.
</p>
        <blockquote>
          <h3>About the Series
</h3>
          <p>
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a "Hello, World!"
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
</p>
          <p>
Part 1: <a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx">Events
of the ASP.NET Page Life Cycle</a><br />
Part 2: <a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx">ASP.NET
Page &amp; WebControl Event Execution Order</a><br />
Part 3: Getting Started with ASP.NET Data Binding 
<br />
Part 4: <a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx">Wiring
Events to your Page</a></p>
        </blockquote>
        <h3>Getting Started with ASP.NET Data Binding
</h3>
        <p>
When we load up data from the database, we could use a for-each loop to iterate through
the data, manually create every new control, such as a table row, and manually write
our data as the content for each new control, but that would be a lot of useless,
repetitive, and senseless <a title="Boilerplate Code (Wikipedia)" href="http://en.wikipedia.org/wiki/Boilerplate_(text)#Boilerplate_code">boilerplate
code</a>. Instead, we should use functionality that is built in to the ASP.NET framework,
and allow the framework to do a lot of the work for us. This process of using the
framework for binding dynamic data to the page, or to controls within the page, is
called Data Binding.
</p>
        <p>
As we've discussed before, there are several events that handle the processing and
rendering of a page. Similarly, there are several events that handle the process of
binding data to a page (and its child controls). Each of these events handle a very
specific sub-set of the process. And as before, knowing the execution order of these
events will make you more proficient at ASP.NET development.
</p>
        <p>
For our examples, we will have a page for displaying Company data. The page will host
a TextBox control containing the name of the company, and a repeater for departments
within the company. Each repeater item will display the name of the department and
a DropDownList containing the names of employees within the department.
</p>
        <pre class="csharp:nocontrols" name="code">public partial class CompanyInformation : Page
{
  private Repeater _deparmentsRepeater;
  private TextBox _companyNameTextbox;

  public _Default()
  {
    Init += Page_Init;
    Load += Page_Load;
  }

  void Page_Init(object sender, EventArgs e)
  {
    var container = new Panel();
    _companyNameTextbox = new TextBox();
    _companyNameTextbox.ID = "companyNameTextbox";
    _companyNameTextbox.DataBinding += TBox_DataBinding;
    container.Controls.Add(_companyNameTextbox);
    myForm.Controls.Add(container);

    _deparmentsRepeater = new Repeater();
    _deparmentsRepeater.ID = "departmentsRepeater";
    _deparmentsRepeater.ItemCreated += Rpt_ItemCreated;
    _deparmentsRepeater.ItemDataBound += Rpt_ItemDataBound;
    myForm.Controls.Add(_deparmentsRepeater);
  }
}</pre>
        <h3>ASP.NET Data Binding Events
</h3>
        <h4>Page.DataBind() / Control.DataBind()
</h4>
        <p>
The first "Event" of ASP.NET's Data Binding Life Cycle is not an event at
all; it is a method that gets everything started. The DataBind method initiates the
process of binding all controls on the page, attaching your dynamic loaded classes
or lists to the areas of your page where the data will be displayed. DataBind can
be executed at the Page level, or on any bindable Control. Whenever it is executed,
DataBind also cascades through all child controls of the execution point. If you have
an ASP.NET Panel Control that contains several TextBox controls, executing DataBind
on the panel will run the method on the Panel first, then all of the child text boxes.
If you execute on the Page, it will fire first on the page, then on the panel, then
on all of the text boxes. The cascading rules are the same as the event execution
order discussed in <a title="Dev Basics: ASP.NET Page Life Cycle, Part 2 [WebControl Execution Order]" href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx" target="_blank">Part
2</a> of this series.
</p>
        <p>
Traditionally, DataBind is executed from within the Page Load event, though it can
be executed from other places instead, as long as you keep the rest of the page life
cycle in mind. For example, do not run DataBind on your page in PreInit; none of your
controls have been instantiated, yet. Also, as my personal preference, I put all of
my data retrieval logic in an override of the DataBind method, keeping all of my binding
logic in a centralized location, though this can also occur elsewhere providing that
it is prior to the execution of the base Page.DataBind() or Control.DataBind() method.
</p>
        <pre class="csharp:nocontrols" name="code">void Page_Load(object sender, EventArgs e)
{
  DataBind();
}
public override void DataBind()
{
  Trace.Write("Beginning to bind all controls");
  _myRepeater.DataSource = MyCompany.Departments();
  base.DataBind();
}</pre>
        <p>
Here, the Page Load event kicks off our override of the DataBind method. This override
retrieves a list of Departments for the company, and assigns the required properties
from the company class instance to controls as needed, which includes all controls
with a DataSource property. DataSource is usually a collection of objects to be used
for binding collections to list-based controls from DropDownLists to Repeaters, though
some other controls may have different needs and uses for DataSource. Above, we assign
the Departments list to the repeater's DataSource property, so that later on in the
binding process, the repeater can pass appropriate Department information on to each
of its RepeaterItems and child controls. With the DataSource defined, the base DataBind
method is executed to initiate binding to all controls on the page.
</p>
        <h4>DataBinding Event
</h4>
        <p>
DataBinding is the first actual event that fires in the DataBinding series, and it
will fire for every bindable control and child control from the point where the DataBind
method was executed, top-down. When the event executes, binding has not yet been executed,
but the data to be bound is available for manipulation. As such, binding has also
not yet executed on any of the child controls of the event target. With the exception
of list-based container controls like a DataGrid, GridView, or Repeater, during the
DataBinding event would be where any dynamic child controls are created and their
DataSources assigned.
</p>
        <pre class="csharp:nocontrols" name="code">// Use with: _companyNameTextbox.DataBinding += TBox_DataBinding;
void TBox_DataBinding(object sender, EventArgs e)
{
  ((TextBox) sender).Text = MyCompany.Name;
}</pre>
        <p>
Above, we bind our TextBox control to the name of our company. TextBox does not have
a DataSource property, so the company name is manually assigned directly to the TextBox's
Text property.
</p>
        <h4>RowCreated / ItemCreated Event
</h4>
        <p>
Note: RowCreated is used for GridView Control, only. ItemCreated is used for DataGrid,
ListView, Repeater, and all other list-based container controls. 
<br />
The RowCreated and ItemCreated events are very similar in nature to the DataBinding
event, and are used for list-based container controls like a DataGrid, GridView, or
Repeater. This event will execute once for each item in the DataSource collection,
and correspond to one Row or Item in the control. On execution, the individual Row
or Item in your control has been created, any child controls specified in your markup
have been initialized and loaded, and the individual data item is available for manipulation.
However, Data Binding has not yet been executed on the row or any of its child controls.
This event cannot be dependent upon any control data since the binding has yet to
occur. An example scenario that would use this event would be if your data item contained
another list, such as our Department class instance that contains a list of Employees,
and the Employees will display in a dropdown. During Created, the dropdown's DataSource
can be assigned to the list contained within the Employees property. After the Created
event finished for the Row or Item, ASP.NET will automatically execute the DataBind
method on the Employees dropdown, binding the list data to populate the control. This
automatic execution of DataBind applies to all child controls of the Row or Item,
including controls defined in the Code-In-Front markup or those that were manually
created in the code-behind.
</p>
        <p>
Be aware that any code in the Created events cannot be dependent upon Control data.
Even if you specify the DataSource property of a child dropdown, the DropDownList.Items
list property is still empty. Executing code dependant upon control data, such as
setting the selected item, will fail.
</p>
        <pre class="csharp:nocontrols" name="code">// Use with: _myRepeater.ItemCreated += Rpt_ItemCreated;
void Rpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  //Preparing another Repeater Item for binding
  var dataItem = (Department) e.Item.DataItem;

  var departmentLabel = new Label();
  departmentLabel.Text = dataItem.Name;
  e.Item.Controls.Add(departmentLabel);

  var dropdownOfEmployees = new DropDownList();
  dropdownOfEmployees.DataSource = dataItem.Employees;
  dropdownOfEmployees.DataTextField = "Name";
  e.Item.Controls.Add(dropdownOfEmployees);

  e.Item.Controls.Add(new LiteralControl("<br />
")); }</pre>
        <p>
The ItemCreated event creates a label for the name of the department, assigning the
name, and a DropDownList of Employees, assigning only the list's DataSource. ItemCreated
is repeated for every item in the repeater's DataSource collection, or in other words,
every department associated with our company. Because DataBinding has not yet executed
for any child control, none of the Employee ListItems exist in our DropDownList, but
because it has not yet executed, we also do not need to manually create the ListItems
or manually re-execute DropDownList.DataBind().
</p>
        <h4>RowDataBound / ItemDataBound
</h4>
        <p>
Note: RowDataBound is used for GridView Control, only. ItemDataBound is used for DataGrid,
ListView, Repeater, and all other list-based container controls. 
<br />
The final event in the Data Binding Life Cycle is the Bound events, RowDataBound and
ItemDataBound. This event fires when the data binding process has completed for all
child controls within the Row or Item. All controls within the row have their data,
and code that is dependant upon control data, such as setting a selected item, can
now be executed. It is strongly advised that this event contains no modifications
to the item data that would require a DataBind method to be executed; this sort of
data manipulation should occur instead in the Created events, prior to Data Binding
the child control tree. If DataBind were to be executed again on this control, the
Data Binding process for this control and all children is restarted and re-executed,
causing controls to be Data Bound two or more times and potentially leading to an
unknown state and adverse outcomes in your application.
</p>
        <p>
The DataBound events indicate that binding has been completed for this item and all
child controls; for us, this means our DropDownList of employees has been fully bound,
and that a ListItem exists for each Employee. We can use this post-binding event to
perform any data-dependent logic. In this case, we now set the SelectedIndex of our
DropDownList; the method would fail if it was executed during ItemCreated. As with
ItemCreated, this event will execute for each item in our repeater's DataSource collection.
</p>
        <pre class="csharp:nocontrols" name="code">// Use with: _myRepeater.ItemDataBound += Rpt_ItemDataBound;
void Rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
  var dropdownOfEmployees = (DropDownList) e.Item.Controls[1];
  dropdownOfEmployees.SelectedIndex = 2;
}</pre>
        <h3>Proper Data Binding
</h3>
        <p>
This is the essence of Data Binding within ASP.NET Web Forms: one method and three
events. When done properly, the DataBind method should only be called once on a control
tree. Execute DataBind directly on the page, or execute it once on individual controls
such as each of your top-level Repeaters, but whatever path you follow, make sure
that the method is not executed twice on any single control. Use the binding events
to make this happen. Failure to do so can cause unfortunate side effects and extensive
pain.
</p>
        <ul>
          <li>
DataSources should be assigned prior to execution of a control's DataBind method. 
</li>
          <li>
Controls without a DataSource property can be manually bound using the controls DataBinding
event, after executing DataBind. 
</li>
          <li>
For collection-based container controls, define child controls and assign their DataSource
using the RowCreated/ItemCreated events. 
</li>
          <li>
For collection-based container controls, perform data-dependent logic on child controls
in the RowDataBound/ItemDataBound event. 
</li>
        </ul>
        <p>
The ASP.NET Page Life Cycle may seem like a monotonous mess, but it is a useful tool
if you understand the events, their order, and their relationship to each other. If
you missed them, go back and review <a title="Dev Basics: ASP.NET Page Life Cycle, Part 1 [Events]" href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx">Part
1</a> for the core Page Life Cycle events and to <a title="Dev Basics: ASP.NET Page Life Cycle, Part 2 [WebControl Execution Order]" href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx">Part
2</a> for the Event Execution Order between a page and its controls. Once you have
these down, there still are some oddities to look out for (and some tricks to help
you out). <a title="Dev Basics: ASP.NET Page Life Cycle, Part 4 [Event Wireup]" href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx">As
the series continues</a>, we discuss some of these tips, tricks, and traps to help
you unleash the full power of your ASP.NET applications.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:233f1d3b-6345-4d60-a6cb-b67b55265237" class="wlWriterEditableSmartContent">Technorati
Tags: <a href="http://technorati.com/tags/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag">Page
Life Cycle</a>,<a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag">Event
Life Cycle</a>,<a href="http://technorati.com/tags/Dev+Basics" rel="tag">Dev Basics</a>,<a href="http://technorati.com/tags/Back+to+Basics" rel="tag">Back
to Basics</a>,<a href="http://technorati.com/tags/Data+Binding" rel="tag">Data Binding</a></div>
        <img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=6682b44d-7660-4b5e-8746-bdcfdae81f84" />
      </body>
      <title>Dev Basics: ASP.NET Page Life Cycle, Part 3 [Data Binding]</title>
      <guid isPermaLink="false">http://www.cptloadtest.com/PermaLink,guid,6682b44d-7660-4b5e-8746-bdcfdae81f84.aspx</guid>
      <link>http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx</link>
      <pubDate>Wed, 24 Mar 2010 00:32:53 GMT</pubDate>
      <description>&lt;p&gt;
The previous installments of this series cover the core events of the ASP.NET Page
class, of the ASP.NET Controls, and how the page and controls work together to co-exist
in the same sandbox. We've gotten to the point where we know how these controls will
interact with the page so that we can make our page more than just a sea of crazy
peach gradient backgrounds, but that still isn't enough. Static content is so 1999,
and that party broke up long ago. The next step in a quality, modern web site is creating
dynamic content, and rendering it to the page. To do this, we need Data Binding.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;h3&gt;About the Series
&lt;/h3&gt;
&lt;p&gt;
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a &amp;quot;Hello, World!&amp;quot;
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
&lt;/p&gt;
&lt;p&gt;
Part 1: &lt;a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx"&gt;Events
of the ASP.NET Page Life Cycle&lt;/a&gt; 
&lt;br /&gt;
Part 2: &lt;a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx"&gt;ASP.NET
Page &amp;amp; WebControl Event Execution Order&lt;/a&gt; 
&lt;br /&gt;
Part 3: Getting Started with ASP.NET Data Binding 
&lt;br /&gt;
Part 4: &lt;a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx"&gt;Wiring
Events to your Page&lt;/a&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;h3&gt;Getting Started with ASP.NET Data Binding
&lt;/h3&gt;
&lt;p&gt;
When we load up data from the database, we could use a for-each loop to iterate through
the data, manually create every new control, such as a table row, and manually write
our data as the content for each new control, but that would be a lot of useless,
repetitive, and senseless &lt;a title="Boilerplate Code (Wikipedia)" href="http://en.wikipedia.org/wiki/Boilerplate_(text)#Boilerplate_code"&gt;boilerplate
code&lt;/a&gt;. Instead, we should use functionality that is built in to the ASP.NET framework,
and allow the framework to do a lot of the work for us. This process of using the
framework for binding dynamic data to the page, or to controls within the page, is
called Data Binding.
&lt;/p&gt;
&lt;p&gt;
As we've discussed before, there are several events that handle the processing and
rendering of a page. Similarly, there are several events that handle the process of
binding data to a page (and its child controls). Each of these events handle a very
specific sub-set of the process. And as before, knowing the execution order of these
events will make you more proficient at ASP.NET development.
&lt;/p&gt;
&lt;p&gt;
For our examples, we will have a page for displaying Company data. The page will host
a TextBox control containing the name of the company, and a repeater for departments
within the company. Each repeater item will display the name of the department and
a DropDownList containing the names of employees within the department.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;public partial class CompanyInformation : Page
{
  private Repeater _deparmentsRepeater;
  private TextBox _companyNameTextbox;

  public _Default()
  {
    Init += Page_Init;
    Load += Page_Load;
  }

  void Page_Init(object sender, EventArgs e)
  {
    var container = new Panel();
    _companyNameTextbox = new TextBox();
    _companyNameTextbox.ID = &amp;quot;companyNameTextbox&amp;quot;;
    _companyNameTextbox.DataBinding += TBox_DataBinding;
    container.Controls.Add(_companyNameTextbox);
    myForm.Controls.Add(container);

    _deparmentsRepeater = new Repeater();
    _deparmentsRepeater.ID = &amp;quot;departmentsRepeater&amp;quot;;
    _deparmentsRepeater.ItemCreated += Rpt_ItemCreated;
    _deparmentsRepeater.ItemDataBound += Rpt_ItemDataBound;
    myForm.Controls.Add(_deparmentsRepeater);
  }
}&lt;/pre&gt;
&lt;h3&gt;ASP.NET Data Binding Events
&lt;/h3&gt;
&lt;h4&gt;Page.DataBind() / Control.DataBind()
&lt;/h4&gt;
&lt;p&gt;
The first &amp;quot;Event&amp;quot; of ASP.NET's Data Binding Life Cycle is not an event at
all; it is a method that gets everything started. The DataBind method initiates the
process of binding all controls on the page, attaching your dynamic loaded classes
or lists to the areas of your page where the data will be displayed. DataBind can
be executed at the Page level, or on any bindable Control. Whenever it is executed,
DataBind also cascades through all child controls of the execution point. If you have
an ASP.NET Panel Control that contains several TextBox controls, executing DataBind
on the panel will run the method on the Panel first, then all of the child text boxes.
If you execute on the Page, it will fire first on the page, then on the panel, then
on all of the text boxes. The cascading rules are the same as the event execution
order discussed in &lt;a title="Dev Basics: ASP.NET Page Life Cycle, Part 2 [WebControl Execution Order]" href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx" target="_blank"&gt;Part
2&lt;/a&gt; of this series.
&lt;/p&gt;
&lt;p&gt;
Traditionally, DataBind is executed from within the Page Load event, though it can
be executed from other places instead, as long as you keep the rest of the page life
cycle in mind. For example, do not run DataBind on your page in PreInit; none of your
controls have been instantiated, yet. Also, as my personal preference, I put all of
my data retrieval logic in an override of the DataBind method, keeping all of my binding
logic in a centralized location, though this can also occur elsewhere providing that
it is prior to the execution of the base Page.DataBind() or Control.DataBind() method.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;void Page_Load(object sender, EventArgs e)
{
  DataBind();
}
public override void DataBind()
{
  Trace.Write(&amp;quot;Beginning to bind all controls&amp;quot;);
  _myRepeater.DataSource = MyCompany.Departments();
  base.DataBind();
}&lt;/pre&gt;
&lt;p&gt;
Here, the Page Load event kicks off our override of the DataBind method. This override
retrieves a list of Departments for the company, and assigns the required properties
from the company class instance to controls as needed, which includes all controls
with a DataSource property. DataSource is usually a collection of objects to be used
for binding collections to list-based controls from DropDownLists to Repeaters, though
some other controls may have different needs and uses for DataSource. Above, we assign
the Departments list to the repeater's DataSource property, so that later on in the
binding process, the repeater can pass appropriate Department information on to each
of its RepeaterItems and child controls. With the DataSource defined, the base DataBind
method is executed to initiate binding to all controls on the page.
&lt;/p&gt;
&lt;h4&gt;DataBinding Event
&lt;/h4&gt;
&lt;p&gt;
DataBinding is the first actual event that fires in the DataBinding series, and it
will fire for every bindable control and child control from the point where the DataBind
method was executed, top-down. When the event executes, binding has not yet been executed,
but the data to be bound is available for manipulation. As such, binding has also
not yet executed on any of the child controls of the event target. With the exception
of list-based container controls like a DataGrid, GridView, or Repeater, during the
DataBinding event would be where any dynamic child controls are created and their
DataSources assigned.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;// Use with: _companyNameTextbox.DataBinding += TBox_DataBinding;
void TBox_DataBinding(object sender, EventArgs e)
{
  ((TextBox) sender).Text = MyCompany.Name;
}&lt;/pre&gt;
&lt;p&gt;
Above, we bind our TextBox control to the name of our company. TextBox does not have
a DataSource property, so the company name is manually assigned directly to the TextBox's
Text property.
&lt;/p&gt;
&lt;h4&gt;RowCreated / ItemCreated Event
&lt;/h4&gt;
&lt;p&gt;
Note: RowCreated is used for GridView Control, only. ItemCreated is used for DataGrid,
ListView, Repeater, and all other list-based container controls. 
&lt;br /&gt;
The RowCreated and ItemCreated events are very similar in nature to the DataBinding
event, and are used for list-based container controls like a DataGrid, GridView, or
Repeater. This event will execute once for each item in the DataSource collection,
and correspond to one Row or Item in the control. On execution, the individual Row
or Item in your control has been created, any child controls specified in your markup
have been initialized and loaded, and the individual data item is available for manipulation.
However, Data Binding has not yet been executed on the row or any of its child controls.
This event cannot be dependent upon any control data since the binding has yet to
occur. An example scenario that would use this event would be if your data item contained
another list, such as our Department class instance that contains a list of Employees,
and the Employees will display in a dropdown. During Created, the dropdown's DataSource
can be assigned to the list contained within the Employees property. After the Created
event finished for the Row or Item, ASP.NET will automatically execute the DataBind
method on the Employees dropdown, binding the list data to populate the control. This
automatic execution of DataBind applies to all child controls of the Row or Item,
including controls defined in the Code-In-Front markup or those that were manually
created in the code-behind.
&lt;/p&gt;
&lt;p&gt;
Be aware that any code in the Created events cannot be dependent upon Control data.
Even if you specify the DataSource property of a child dropdown, the DropDownList.Items
list property is still empty. Executing code dependant upon control data, such as
setting the selected item, will fail.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;// Use with: _myRepeater.ItemCreated += Rpt_ItemCreated;
void Rpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  //Preparing another Repeater Item for binding
  var dataItem = (Department) e.Item.DataItem;

  var departmentLabel = new Label();
  departmentLabel.Text = dataItem.Name;
  e.Item.Controls.Add(departmentLabel);

  var dropdownOfEmployees = new DropDownList();
  dropdownOfEmployees.DataSource = dataItem.Employees;
  dropdownOfEmployees.DataTextField = &amp;quot;Name&amp;quot;;
  e.Item.Controls.Add(dropdownOfEmployees);

  e.Item.Controls.Add(new LiteralControl(&amp;quot;&lt;br /&gt;
&amp;quot;)); }&lt;/pre&gt;
&lt;p&gt;
The ItemCreated event creates a label for the name of the department, assigning the
name, and a DropDownList of Employees, assigning only the list's DataSource. ItemCreated
is repeated for every item in the repeater's DataSource collection, or in other words,
every department associated with our company. Because DataBinding has not yet executed
for any child control, none of the Employee ListItems exist in our DropDownList, but
because it has not yet executed, we also do not need to manually create the ListItems
or manually re-execute DropDownList.DataBind().
&lt;/p&gt;
&lt;h4&gt;RowDataBound / ItemDataBound
&lt;/h4&gt;
&lt;p&gt;
Note: RowDataBound is used for GridView Control, only. ItemDataBound is used for DataGrid,
ListView, Repeater, and all other list-based container controls. 
&lt;br /&gt;
The final event in the Data Binding Life Cycle is the Bound events, RowDataBound and
ItemDataBound. This event fires when the data binding process has completed for all
child controls within the Row or Item. All controls within the row have their data,
and code that is dependant upon control data, such as setting a selected item, can
now be executed. It is strongly advised that this event contains no modifications
to the item data that would require a DataBind method to be executed; this sort of
data manipulation should occur instead in the Created events, prior to Data Binding
the child control tree. If DataBind were to be executed again on this control, the
Data Binding process for this control and all children is restarted and re-executed,
causing controls to be Data Bound two or more times and potentially leading to an
unknown state and adverse outcomes in your application.
&lt;/p&gt;
&lt;p&gt;
The DataBound events indicate that binding has been completed for this item and all
child controls; for us, this means our DropDownList of employees has been fully bound,
and that a ListItem exists for each Employee. We can use this post-binding event to
perform any data-dependent logic. In this case, we now set the SelectedIndex of our
DropDownList; the method would fail if it was executed during ItemCreated. As with
ItemCreated, this event will execute for each item in our repeater's DataSource collection.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;// Use with: _myRepeater.ItemDataBound += Rpt_ItemDataBound;
void Rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
  var dropdownOfEmployees = (DropDownList) e.Item.Controls[1];
  dropdownOfEmployees.SelectedIndex = 2;
}&lt;/pre&gt;
&lt;h3&gt;Proper Data Binding
&lt;/h3&gt;
&lt;p&gt;
This is the essence of Data Binding within ASP.NET Web Forms: one method and three
events. When done properly, the DataBind method should only be called once on a control
tree. Execute DataBind directly on the page, or execute it once on individual controls
such as each of your top-level Repeaters, but whatever path you follow, make sure
that the method is not executed twice on any single control. Use the binding events
to make this happen. Failure to do so can cause unfortunate side effects and extensive
pain.
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
DataSources should be assigned prior to execution of a control's DataBind method. 
&lt;/li&gt;
&lt;li&gt;
Controls without a DataSource property can be manually bound using the controls DataBinding
event, after executing DataBind. 
&lt;/li&gt;
&lt;li&gt;
For collection-based container controls, define child controls and assign their DataSource
using the RowCreated/ItemCreated events. 
&lt;/li&gt;
&lt;li&gt;
For collection-based container controls, perform data-dependent logic on child controls
in the RowDataBound/ItemDataBound event. 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The ASP.NET Page Life Cycle may seem like a monotonous mess, but it is a useful tool
if you understand the events, their order, and their relationship to each other. If
you missed them, go back and review &lt;a title="Dev Basics: ASP.NET Page Life Cycle, Part 1 [Events]" href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx"&gt;Part
1&lt;/a&gt; for the core Page Life Cycle events and to &lt;a title="Dev Basics: ASP.NET Page Life Cycle, Part 2 [WebControl Execution Order]" href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx"&gt;Part
2&lt;/a&gt; for the Event Execution Order between a page and its controls. Once you have
these down, there still are some oddities to look out for (and some tricks to help
you out). &lt;a title="Dev Basics: ASP.NET Page Life Cycle, Part 4 [Event Wireup]" href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx"&gt;As
the series continues&lt;/a&gt;, we discuss some of these tips, tricks, and traps to help
you unleash the full power of your ASP.NET applications.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:233f1d3b-6345-4d60-a6cb-b67b55265237" class="wlWriterEditableSmartContent"&gt;Technorati
Tags: &lt;a href="http://technorati.com/tags/ASP.NET" rel="tag"&gt;ASP.NET&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag"&gt;Page
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag"&gt;Event
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Dev+Basics" rel="tag"&gt;Dev Basics&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Back+to+Basics" rel="tag"&gt;Back
to Basics&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Data+Binding" rel="tag"&gt;Data Binding&lt;/a&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=6682b44d-7660-4b5e-8746-bdcfdae81f84" /&gt;</description>
      <comments>http://www.cptloadtest.com/CommentView,guid,6682b44d-7660-4b5e-8746-bdcfdae81f84.aspx</comments>
      <category>ASP.Net</category>
      <category>Dev Basics</category>
    </item>
    <item>
      <trackback:ping>http://www.cptloadtest.com/Trackback.aspx?guid=1d359ae8-9825-413f-92dc-2b533314f154</trackback:ping>
      <pingback:server>http://www.cptloadtest.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.cptloadtest.com/PermaLink,guid,1d359ae8-9825-413f-92dc-2b533314f154.aspx</pingback:target>
      <dc:creator>Jay Harris</dc:creator>
      <wfw:comment>http://www.cptloadtest.com/CommentView,guid,1d359ae8-9825-413f-92dc-2b533314f154.aspx</wfw:comment>
      <wfw:commentRss>http://www.cptloadtest.com/SyndicationService.asmx/GetEntryCommentsRss?guid=1d359ae8-9825-413f-92dc-2b533314f154</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The first installment of this series goes back to the beginning and describes each
of the events within ASP.NET Page Life Cycle. Understanding the basic fundamentals
of the ASP.NET Page Life Cycle, including the order and scope of influence for each
of the Page Life Cycle events, will help ensure that you are executing your custom
code at the right time, and in the right order, rather than stepping on yourself by
conflicting with core ASP.NET framework functionality. But this is only part of the
story, since there is more to the ASP.NET Page Life Cycle than just the page, itself.
</p>
        <h3>ASP.NET Page &amp; WebControl Event Execution Order
</h3>
        <p>
Pages would be nothing but a sea of crazy peach gradient backgrounds without the controls
to display content and to interact with the user. In addition to the order of the
various page events, it is often helpful to know the order in which a page and its
controls execute a single event. Does Page.Load execute before Control.Load? Does
Page.Init execute before Control.Init? Does myTextBox.TextChanged fire before myButton.Click?
And what about myTextBox1.TextChanged versus myTextBox2.TextChanged?
</p>
        <p>
Knowing the execution order of events within the control tree will make you a better
ASP.NET developer. If you cannot answer each of those questions above (and maybe even
if you can), keep reading.
</p>
        <blockquote>
          <h3>About the Series
</h3>
          <p>
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a "Hello, World!"
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
</p>
          <p>
Part 1: <a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx">Events
of the ASP.NET Page Life Cycle</a><br />
Part 2: ASP.NET Page &amp; WebControl Event Execution Order 
<br />
Part 3: <a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx">Getting
Started with ASP.NET Data Binding</a><br />
Part 4: <a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx">Wiring
Events to your Page</a></p>
        </blockquote>
        <h3>Event Execution Order within the Control Hierarchy 
</h3>
        <p>
At the core of the control-level event execution order is where the events fire with
respect to the page. The majority of the events in the ASP.NET Page Life Cycle execute
from the top, down, which is also referred to as outside-in. That is, the event is
first executed on the page, such as Page.Load, then executed recursively through each
of the page's controls, Control.Load, to the controls within controls, and so on.
The two exceptions to this rule are Initialization and Unload. With these two events,
the event is fired first on the child control, then on the container control, and
finally on the page, known as a bottom-up or inside-out order.
</p>
        <p>
But what if a control is dynamically added to the page during a later event? In this
case, a control will fire events to catch up to the page (though a control will never
exceed beyond what Page Event is currently executing). In other words, if a control
is dynamically added during the PreInit page event, the control will immediately fire
its own PreInit. However, if a control is dynamically added during the PreLoad event,
it will fire PreInit, Init, InitComplete, and PreLoad, all in quick succession.
</p>
        <pre class="csharp:nocontrols" name="code">private void Page_PreInit(object sender, EventArgs e)
{
    Trace.Write("Executing Page PreInitialization");
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += "TextBoxFromPreInit";
    form1.Controls.Add(textbox);
}

private void Page_Init(object sender, EventArgs e)
{
    Trace.Write("Executing Page Initialization (Should occur after controls)");
}

private void Page_Load(object sender, EventArgs e)
{
    Trace.Write("Executing Page Load (Should occur before controls)");
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += "TextBoxFromLoad";
    form1.Controls.Add(textbox);
}

private void Control_Init(object sender, EventArgs e)
{
    Trace.Write("Executing Control Init for " + ((Control)sender).UniqueID);
}

private void Control_Load(object sender, EventArgs e)
{
    Trace.Write("Executing Control Load for " + ((Control)sender).UniqueID);
}

/*
Output: 

Begin PreInit		
Executing Page PreInitialization
End PreInit
Begin Init
Executing Control Init for TextBoxFromPreInit
Executing Page Initialization (Should occur after controls)
End Init
Begin Load
Executing Page Load (Should occur before controls)
Executing Control Init for TextBoxFromLoad
Executing Control Load for TextBoxFromPreInit
Executing Control Load for TextBoxFromLoad
End Load
*/</pre>
        <h3>Event Execution Order for Sibling WebControls
</h3>
        <p>
The event execution order of parent and child controls is simple and straightforward.
As if to maintain balance in The Force, the event execution order for sibling controls
is a bit complicated. For siblings, this order is governed by three main and cascading
criteria: the type of event that is being executed, the Page Event executing when
the control was added to the page, and the index of the control within the parent's
(or page's) Controls collection.
</p>
        <p>
First, the event type is the primary governor of when an event is fired. Just like
the order of Page Events, Initialize events always occur before Load events, and Load
events always occur before Render events. The complication surrounds the several control-specific
"PostBack Events," such as Click or TextChanged, as there are three PostBack
event types: Changed Events, Validation Events, and actual PostBack Events. The first
that fire are Changed Events, which include any event where the value changes, such
as TextBox.TextChanged or DropDownList.SelectedIndexChanged. Changed events should
include any custom Value manipulation for each of your form controls. Once the values
are defined, Validation events are executed to assist with ensuring data integrity.
Finally, once all values are defined and validated, PostBack Events, such as Button.Command
or Button.Click, are executed. In most cases, these PostBack events will include the
form submission logic, such as sending the email, transmitting data through a Web
Service, or saving data to a database. The Changed Events type of events always fire
before Validation events, which always fire before the PostBack Events types; TextBox.TextChanged
before Validator.Validate before Button.Click.
</p>
        <p>
If the events are the same, such as two TextBox controls that are both executing TextChanged,
the second criteria to determine sibling event execution is when the control was added
to the page. If a control was added in any of the Initialization events (PreInit,
Init, InitComplete), it is executed first. If a control was added in any of the Load
events, it is executed second. So, for the two TextBoxes, the TextChanged event for
the TextBox added during Initialization will be fired before the same event for the
TextBox added during Load. (txtAddedDuringInit.TextChanged will fire before txtAddedDuringLoad.TextChanged.)
</p>
        <p>
If the executing event is the same, and the controls were added during the same Page
Event, the final criterion for sibling execution is the index within the Controls
collection. After the above two criteria are considered, events that still have equal
weight are executed according to their index in their parent's Controls collection.
</p>
        <pre class="csharp:nocontrols" name="code">private void Page_Init(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit1";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit2";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit3At0";
    form1.Controls.AddAt(0, textbox);
}

private void Page_Load(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad1";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad2";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad3At0";
    form1.Controls.AddAt(0, textbox);
}

private void Control_TextChanged(object sender, EventArgs e)
{
    Trace.Write("Executing Control TextChanged for " + ((Control) sender).UniqueID
                + " / Position: " + form1.Controls.IndexOf((Control) sender));
}

/*
Trace Output: 

Begin Raise ChangedEvents
Executing Control TextChanged for TextBoxFromInit3At0 / Position: 1
Executing Control TextChanged for TextBoxFromInit1 / Position: 2
Executing Control TextChanged for TextBoxFromInit2 / Position: 3
Executing Control TextChanged for TextBoxFromLoad3At0 / Position: 0
Executing Control TextChanged for TextBoxFromLoad1 / Position: 4
Executing Control TextChanged for TextBoxFromLoad2 / Position: 5
End Raise ChangedEvents
*/</pre>
        <p>
So, to address the questions from above: Page.Load does execute before Control.Load,
as the Load event is executed outside-in, however, Page.Init executes after Control.Init,
as the Init event is executed inside-out. The TextChanged event on myTextBox is fired
prior to myButton.Click, as control ChangedEvents are executed before control PostBackEvents.
And finally, regarding myTextBox1.TextChanged versus myTextBox2.TextChanged, it depends;
the order is dependent upon where the controls exist within the entire hierarchy,
when the controls were created, and upon their position within the Controls collection.
</p>
        <p>
The execution order of control events within the page life cycle is a complicated
mess, and fortunately does not come in to play often. But for when it does, it is
important to know how everything plays together. I find that most often, the order
is important when dynamically adding controls to the page outside of DataBinding (though
I would consider this a design smell), when creating custom WebControls, or when working
with control Changed Events and validation. Still, as with before, committing this
to memory (or at least a link to a reference, such as this post) will help with making
you a better ASP.NET developer and with creating higher quality applications.
</p>
        <p>
So what's next? <a title="Dev Basics: ASP.NET Page Life Cycle, Part 1 [Events]" href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx">Part
1</a> covered the base ASP.NET Page Life Cycle, and this post covers the execution
order of events on the page. <a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx">As
this series continues</a>, we will discuss the details of the DataBinding events,
and will dig in to some tips, tricks, and traps when developing ASP.NET applications. 
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:8f035b16-2463-44d0-b6aa-1c67e951fb4c" class="wlWriterEditableSmartContent">Technorati
Tags: <a href="http://technorati.com/tags/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag">Page
Life Cycle</a>,<a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag">Event
Life Cycle</a>,<a href="http://technorati.com/tags/Dev+Basics" rel="tag">Dev Basics</a>,<a href="http://technorati.com/tags/Back+to+Basics" rel="tag">Back
to Basics</a></div>
        <img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=1d359ae8-9825-413f-92dc-2b533314f154" />
      </body>
      <title>Dev Basics: ASP.NET Page Life Cycle, Part 2 [WebControl Execution Order]</title>
      <guid isPermaLink="false">http://www.cptloadtest.com/PermaLink,guid,1d359ae8-9825-413f-92dc-2b533314f154.aspx</guid>
      <link>http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx</link>
      <pubDate>Tue, 14 Jul 2009 22:26:15 GMT</pubDate>
      <description>&lt;p&gt;
The first installment of this series goes back to the beginning and describes each
of the events within ASP.NET Page Life Cycle. Understanding the basic fundamentals
of the ASP.NET Page Life Cycle, including the order and scope of influence for each
of the Page Life Cycle events, will help ensure that you are executing your custom
code at the right time, and in the right order, rather than stepping on yourself by
conflicting with core ASP.NET framework functionality. But this is only part of the
story, since there is more to the ASP.NET Page Life Cycle than just the page, itself.
&lt;/p&gt;
&lt;h3&gt;ASP.NET Page &amp;amp; WebControl Event Execution Order
&lt;/h3&gt;
&lt;p&gt;
Pages would be nothing but a sea of crazy peach gradient backgrounds without the controls
to display content and to interact with the user. In addition to the order of the
various page events, it is often helpful to know the order in which a page and its
controls execute a single event. Does Page.Load execute before Control.Load? Does
Page.Init execute before Control.Init? Does myTextBox.TextChanged fire before myButton.Click?
And what about myTextBox1.TextChanged versus myTextBox2.TextChanged?
&lt;/p&gt;
&lt;p&gt;
Knowing the execution order of events within the control tree will make you a better
ASP.NET developer. If you cannot answer each of those questions above (and maybe even
if you can), keep reading.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;h3&gt;About the Series
&lt;/h3&gt;
&lt;p&gt;
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a &amp;quot;Hello, World!&amp;quot;
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
&lt;/p&gt;
&lt;p&gt;
Part 1: &lt;a href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx"&gt;Events
of the ASP.NET Page Life Cycle&lt;/a&gt; 
&lt;br /&gt;
Part 2: ASP.NET Page &amp;amp; WebControl Event Execution Order 
&lt;br /&gt;
Part 3: &lt;a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx"&gt;Getting
Started with ASP.NET Data Binding&lt;/a&gt; 
&lt;br /&gt;
Part 4: &lt;a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx"&gt;Wiring
Events to your Page&lt;/a&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;h3&gt;Event Execution Order within the Control Hierarchy 
&lt;/h3&gt;
&lt;p&gt;
At the core of the control-level event execution order is where the events fire with
respect to the page. The majority of the events in the ASP.NET Page Life Cycle execute
from the top, down, which is also referred to as outside-in. That is, the event is
first executed on the page, such as Page.Load, then executed recursively through each
of the page's controls, Control.Load, to the controls within controls, and so on.
The two exceptions to this rule are Initialization and Unload. With these two events,
the event is fired first on the child control, then on the container control, and
finally on the page, known as a bottom-up or inside-out order.
&lt;/p&gt;
&lt;p&gt;
But what if a control is dynamically added to the page during a later event? In this
case, a control will fire events to catch up to the page (though a control will never
exceed beyond what Page Event is currently executing). In other words, if a control
is dynamically added during the PreInit page event, the control will immediately fire
its own PreInit. However, if a control is dynamically added during the PreLoad event,
it will fire PreInit, Init, InitComplete, and PreLoad, all in quick succession.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;private void Page_PreInit(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Page PreInitialization&amp;quot;);
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += &amp;quot;TextBoxFromPreInit&amp;quot;;
    form1.Controls.Add(textbox);
}

private void Page_Init(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Page Initialization (Should occur after controls)&amp;quot;);
}

private void Page_Load(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Page Load (Should occur before controls)&amp;quot;);
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += &amp;quot;TextBoxFromLoad&amp;quot;;
    form1.Controls.Add(textbox);
}

private void Control_Init(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Control Init for &amp;quot; + ((Control)sender).UniqueID);
}

private void Control_Load(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Control Load for &amp;quot; + ((Control)sender).UniqueID);
}

/*
Output: 

Begin PreInit		
Executing Page PreInitialization
End PreInit
Begin Init
Executing Control Init for TextBoxFromPreInit
Executing Page Initialization (Should occur after controls)
End Init
Begin Load
Executing Page Load (Should occur before controls)
Executing Control Init for TextBoxFromLoad
Executing Control Load for TextBoxFromPreInit
Executing Control Load for TextBoxFromLoad
End Load
*/&lt;/pre&gt;
&lt;h3&gt;Event Execution Order for Sibling WebControls
&lt;/h3&gt;
&lt;p&gt;
The event execution order of parent and child controls is simple and straightforward.
As if to maintain balance in The Force, the event execution order for sibling controls
is a bit complicated. For siblings, this order is governed by three main and cascading
criteria: the type of event that is being executed, the Page Event executing when
the control was added to the page, and the index of the control within the parent's
(or page's) Controls collection.
&lt;/p&gt;
&lt;p&gt;
First, the event type is the primary governor of when an event is fired. Just like
the order of Page Events, Initialize events always occur before Load events, and Load
events always occur before Render events. The complication surrounds the several control-specific
&amp;quot;PostBack Events,&amp;quot; such as Click or TextChanged, as there are three PostBack
event types: Changed Events, Validation Events, and actual PostBack Events. The first
that fire are Changed Events, which include any event where the value changes, such
as TextBox.TextChanged or DropDownList.SelectedIndexChanged. Changed events should
include any custom Value manipulation for each of your form controls. Once the values
are defined, Validation events are executed to assist with ensuring data integrity.
Finally, once all values are defined and validated, PostBack Events, such as Button.Command
or Button.Click, are executed. In most cases, these PostBack events will include the
form submission logic, such as sending the email, transmitting data through a Web
Service, or saving data to a database. The Changed Events type of events always fire
before Validation events, which always fire before the PostBack Events types; TextBox.TextChanged
before Validator.Validate before Button.Click.
&lt;/p&gt;
&lt;p&gt;
If the events are the same, such as two TextBox controls that are both executing TextChanged,
the second criteria to determine sibling event execution is when the control was added
to the page. If a control was added in any of the Initialization events (PreInit,
Init, InitComplete), it is executed first. If a control was added in any of the Load
events, it is executed second. So, for the two TextBoxes, the TextChanged event for
the TextBox added during Initialization will be fired before the same event for the
TextBox added during Load. (txtAddedDuringInit.TextChanged will fire before txtAddedDuringLoad.TextChanged.)
&lt;/p&gt;
&lt;p&gt;
If the executing event is the same, and the controls were added during the same Page
Event, the final criterion for sibling execution is the index within the Controls
collection. After the above two criteria are considered, events that still have equal
weight are executed according to their index in their parent's Controls collection.
&lt;/p&gt;
&lt;pre class="csharp:nocontrols" name="code"&gt;private void Page_Init(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromInit1&amp;quot;;
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromInit2&amp;quot;;
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromInit3At0&amp;quot;;
    form1.Controls.AddAt(0, textbox);
}

private void Page_Load(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromLoad1&amp;quot;;
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromLoad2&amp;quot;;
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += &amp;quot;TextBoxFromLoad3At0&amp;quot;;
    form1.Controls.AddAt(0, textbox);
}

private void Control_TextChanged(object sender, EventArgs e)
{
    Trace.Write(&amp;quot;Executing Control TextChanged for &amp;quot; + ((Control) sender).UniqueID
                + &amp;quot; / Position: &amp;quot; + form1.Controls.IndexOf((Control) sender));
}

/*
Trace Output: 

Begin Raise ChangedEvents
Executing Control TextChanged for TextBoxFromInit3At0 / Position: 1
Executing Control TextChanged for TextBoxFromInit1 / Position: 2
Executing Control TextChanged for TextBoxFromInit2 / Position: 3
Executing Control TextChanged for TextBoxFromLoad3At0 / Position: 0
Executing Control TextChanged for TextBoxFromLoad1 / Position: 4
Executing Control TextChanged for TextBoxFromLoad2 / Position: 5
End Raise ChangedEvents
*/&lt;/pre&gt;
&lt;p&gt;
So, to address the questions from above: Page.Load does execute before Control.Load,
as the Load event is executed outside-in, however, Page.Init executes after Control.Init,
as the Init event is executed inside-out. The TextChanged event on myTextBox is fired
prior to myButton.Click, as control ChangedEvents are executed before control PostBackEvents.
And finally, regarding myTextBox1.TextChanged versus myTextBox2.TextChanged, it depends;
the order is dependent upon where the controls exist within the entire hierarchy,
when the controls were created, and upon their position within the Controls collection.
&lt;/p&gt;
&lt;p&gt;
The execution order of control events within the page life cycle is a complicated
mess, and fortunately does not come in to play often. But for when it does, it is
important to know how everything plays together. I find that most often, the order
is important when dynamically adding controls to the page outside of DataBinding (though
I would consider this a design smell), when creating custom WebControls, or when working
with control Changed Events and validation. Still, as with before, committing this
to memory (or at least a link to a reference, such as this post) will help with making
you a better ASP.NET developer and with creating higher quality applications.
&lt;/p&gt;
&lt;p&gt;
So what's next? &lt;a title="Dev Basics: ASP.NET Page Life Cycle, Part 1 [Events]" href="http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx"&gt;Part
1&lt;/a&gt; covered the base ASP.NET Page Life Cycle, and this post covers the execution
order of events on the page. &lt;a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx"&gt;As
this series continues&lt;/a&gt;, we will discuss the details of the DataBinding events,
and will dig in to some tips, tricks, and traps when developing ASP.NET applications. 
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:8f035b16-2463-44d0-b6aa-1c67e951fb4c" class="wlWriterEditableSmartContent"&gt;Technorati
Tags: &lt;a href="http://technorati.com/tags/ASP.NET" rel="tag"&gt;ASP.NET&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag"&gt;Page
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag"&gt;Event
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Dev+Basics" rel="tag"&gt;Dev Basics&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Back+to+Basics" rel="tag"&gt;Back
to Basics&lt;/a&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=1d359ae8-9825-413f-92dc-2b533314f154" /&gt;</description>
      <comments>http://www.cptloadtest.com/CommentView,guid,1d359ae8-9825-413f-92dc-2b533314f154.aspx</comments>
      <category>ASP.Net</category>
      <category>Dev Basics</category>
    </item>
    <item>
      <trackback:ping>http://www.cptloadtest.com/Trackback.aspx?guid=d08d861c-a8fb-487e-9ead-0f64b80640ff</trackback:ping>
      <pingback:server>http://www.cptloadtest.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.cptloadtest.com/PermaLink,guid,d08d861c-a8fb-487e-9ead-0f64b80640ff.aspx</pingback:target>
      <dc:creator>Jay Harris</dc:creator>
      <wfw:comment>http://www.cptloadtest.com/CommentView,guid,d08d861c-a8fb-487e-9ead-0f64b80640ff.aspx</wfw:comment>
      <wfw:commentRss>http://www.cptloadtest.com/SyndicationService.asmx/GetEntryCommentsRss?guid=d08d861c-a8fb-487e-9ead-0f64b80640ff</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a "Hello, World!"
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
</p>
        <blockquote>
          <h3>Posts in this Series
</h3>
          <p>
Part 1: Events of the ASP.NET Page Life Cycle 
<br />
Part 2: <a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx">ASP.NET
Page &amp; WebControl Event Execution Order</a><br />
Part 3: <a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx">Getting
Started with ASP.NET Data Binding</a><br />
Part 4: <a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx">Wiring
Events to your Page</a></p>
        </blockquote>
        <p>
A little help on the Page Life Cycle is never a bad thing. In this series, I will
go over the events that make up the ASP.NET Page Life Cycle, as well as some tips
and tricks on how to get the most out of this event structure while avoiding the traps
and pitfalls. Rather than pursuing broad coverage of the entire ASP.NET Framework,
we'll dive deeply into the "small" portion that is the ASP.NET Page Life
Cycle.
</p>
        <h3>Events of the ASP.NET Page Life Cycle
</h3>
        <p>
I want to start at the beginning. The primary make-up of the Page Life Cycle is the
events that process any ASP.NET requests. Unlike the public static void main of a
WinForms application, where everything based on methods, the execution of a page request
is the execution of these events. These events, which execute in a particular order,
handle the entire request, including loading all of the controls, processing all of
the form data, handling all user-initiated actions, and rendering the page to the
web browser. Knowing the order in which these events are executed, as well as the
responsibility of each event in processing your request, is important for developing
solid, quality ASP.NET applications.
</p>
        <h4>Start
</h4>
        <p>
This is where the page object is instantiated, and where the initial properties of
the page are set. Page properties such as Response and Request, UICulture (similar
to the UICulture property within a WinForms thread), and the value of IsPostBack are
all determined and assigned. No controls are available at this time, so do not try
to set the value of that TextBox control, as it doesn't exist, yet. Fortunately, no
event handlers can be attached to this event, anyway, so there isn't much you can
do to customize this processing or to access that TextBox's value property; "Move
along. There is nothing to see here." But, be aware that this event does occur
after the Constructor, so if you try to access properties such as IsPostBack prior
to the Start event, they have yet to be assigned, and will likely be incorrect.
</p>
        <h4>Page Initialization
</h4>
        <p>
During page initialization, the controls are created, initialized, and added to the
Page's controls collection. This is the first time that you can access a control by
its UniqueID. Do note that all control properties are set to their code values, be
it from code-behind or code-in-front, regardless of what may be available in ViewState
and Form Post values. Control state has yet to be restored, so ViewState and Form
Post values have not yet been pushed to the controls. Finally, Initialization (specifically,
PreInit) is the only time that the Theme and Master Page can be programmatically modified.
</p>
        <h4>Page Load
</h4>
        <p>
Page Load is where control state is restored. If the request is a PostBack, rather
than a new request, all available property values are restored from ViewState and
Form Post data and pushed to the applicable controls. Under most scenarios, this is
where you're going to get what you need from the Database, such as pulling a value
from the query string and loading an item with the matching identity.
</p>
        <h4>Validation
</h4>
        <p>
The Validation event only applies to PostBack requests, and only when Validators are
present in the control collection. The Validate method is executed for each Validator
present, through which the IsValid property is set for each Validator. These IsValid
property values are then cascaded up to the Page's IsValid property. Be aware that
even if all Validators on the page are disabled, the Validation event will still fire;
if a Validator is present, Validate is executed, without regard to any other property.
Also, note that the Validation event is a child of the Page's Load event, so it is
executed within the Page Load event chain, after Page Load, but prior to PostBack
Events and LoadComplete.
</p>
        <h4>PostBack Events
</h4>
        <p>
Once Validation is complete (if applicable), all PostBack events are executed, including
the OnChange event of a DropDownList and the OnClick event of a command button. Post
Back Events are also a child of the Page's Load event, executing after Validation
and before LoadComplete.
</p>
        <h4>Render
</h4>
        <p>
Finally, once all of the data is processed and Post Back events handled, the Page
is rendered within the Web Browser. The Render event consists of saving all control
property data to ViewState, processing the Page and each Control into HTML, and writing
the HTML to the output stream. This is the last opportunity to modify the HTML output.
</p>
        <blockquote>
          <h4>Remembering the Order
</h4>
          <p>
If you are having trouble remembering the order, instead try and remember this simple
mnemonic: <strong>SILVER</strong>; Start, Initialize, Load, Validation, Events, Render.
</p>
        </blockquote>
        <p>
If you are doing a lot of ASP.NET programming, or anticipate that you will be in the
near future, try to commit to memory the order of each of these events, and their
scope of influence. Understanding these basic fundamentals of the ASP.NET Page Life
Cycle will help ensure that you are executing your custom code at the right time,
and in the right order, rather than stepping on yourself by conflicting with the core
functionality.
</p>
        <p>
Now that we know the order of execution on Page Events, what is the order of the Controls?
Does Page.Load execute before Control.Load? How about the order of sibling controls?
What is the order of myTextBox1.TextChanged versus myTextBox2.TextChanged? Also, what
are some things to look out for? <a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx">As
this series continues</a>, we will discuss the details of event execution order within
the ASP.NET Page Life Cycle, as well as some tips, trick, and traps when developing
ASP.NET applications.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f31df0e8-d581-43ef-94f3-a3ebdce80ce6" class="wlWriterEditableSmartContent">Technorati
Tags: <a href="http://technorati.com/tags/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag">Page
Life Cycle</a>,<a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag">Event
Life Cycle</a>,<a href="http://technorati.com/tags/Dev+Basics" rel="tag">Dev Basics</a>,<a href="http://technorati.com/tags/Back+to+Basics" rel="tag">Back
to Basics</a></div>
        <img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=d08d861c-a8fb-487e-9ead-0f64b80640ff" />
      </body>
      <title>Dev Basics: ASP.NET Page Life Cycle, Part 1 [Events]</title>
      <guid isPermaLink="false">http://www.cptloadtest.com/PermaLink,guid,d08d861c-a8fb-487e-9ead-0f64b80640ff.aspx</guid>
      <link>http://www.cptloadtest.com/2009/06/23/Dev-Basics-ASPNET-Page-Life-Cycle-Part-1-Events.aspx</link>
      <pubDate>Tue, 23 Jun 2009 03:53:57 GMT</pubDate>
      <description>&lt;p&gt;
When a request occurs for an ASP.NET page, the response is processed through a series
of events before being sent to the client browser. These events, known as the ASP.NET
Page Life Cycle, are a complicated headache when used improperly, manifesting as odd
exceptions, incorrect data, performance issues, and general confusion. It seems simple
when reading yet-another-book-on-ASP.NET, but never when applied in the real world.
What is covered in a few short pages in many ASP.NET books (and sometimes even just
a few short paragraphs), is much more complicated outside of a &amp;quot;Hello, World!&amp;quot;
application and inside of the complex demands of the enterprise applications that
developers create and maintain in their day-to-day work life. As close to the core
as the life cycle is to any ASP.NET web application, the complications and catches
behind this system never seems to get wide coverage on study guides or other documentation.
But, they should.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;h3&gt;Posts in this Series
&lt;/h3&gt;
&lt;p&gt;
Part 1: Events of the ASP.NET Page Life Cycle 
&lt;br /&gt;
Part 2: &lt;a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx"&gt;ASP.NET
Page &amp;amp; WebControl Event Execution Order&lt;/a&gt; 
&lt;br /&gt;
Part 3: &lt;a href="http://www.cptloadtest.com/2010/03/24/Dev-Basics-ASPNET-Page-Life-Cycle-Part-3-Data-Binding.aspx"&gt;Getting
Started with ASP.NET Data Binding&lt;/a&gt; 
&lt;br /&gt;
Part 4: &lt;a href="http://www.cptloadtest.com/2011/04/26/Dev-Basics-ASPNET-Page-Life-Cycle-Part-4-Event-Wireup.aspx"&gt;Wiring
Events to your Page&lt;/a&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
A little help on the Page Life Cycle is never a bad thing. In this series, I will
go over the events that make up the ASP.NET Page Life Cycle, as well as some tips
and tricks on how to get the most out of this event structure while avoiding the traps
and pitfalls. Rather than pursuing broad coverage of the entire ASP.NET Framework,
we'll dive deeply into the &amp;quot;small&amp;quot; portion that is the ASP.NET Page Life
Cycle.
&lt;/p&gt;
&lt;h3&gt;Events of the ASP.NET Page Life Cycle
&lt;/h3&gt;
&lt;p&gt;
I want to start at the beginning. The primary make-up of the Page Life Cycle is the
events that process any ASP.NET requests. Unlike the public static void main of a
WinForms application, where everything based on methods, the execution of a page request
is the execution of these events. These events, which execute in a particular order,
handle the entire request, including loading all of the controls, processing all of
the form data, handling all user-initiated actions, and rendering the page to the
web browser. Knowing the order in which these events are executed, as well as the
responsibility of each event in processing your request, is important for developing
solid, quality ASP.NET applications.
&lt;/p&gt;
&lt;h4&gt;Start
&lt;/h4&gt;
&lt;p&gt;
This is where the page object is instantiated, and where the initial properties of
the page are set. Page properties such as Response and Request, UICulture (similar
to the UICulture property within a WinForms thread), and the value of IsPostBack are
all determined and assigned. No controls are available at this time, so do not try
to set the value of that TextBox control, as it doesn't exist, yet. Fortunately, no
event handlers can be attached to this event, anyway, so there isn't much you can
do to customize this processing or to access that TextBox's value property; &amp;quot;Move
along. There is nothing to see here.&amp;quot; But, be aware that this event does occur
after the Constructor, so if you try to access properties such as IsPostBack prior
to the Start event, they have yet to be assigned, and will likely be incorrect.
&lt;/p&gt;
&lt;h4&gt;Page Initialization
&lt;/h4&gt;
&lt;p&gt;
During page initialization, the controls are created, initialized, and added to the
Page's controls collection. This is the first time that you can access a control by
its UniqueID. Do note that all control properties are set to their code values, be
it from code-behind or code-in-front, regardless of what may be available in ViewState
and Form Post values. Control state has yet to be restored, so ViewState and Form
Post values have not yet been pushed to the controls. Finally, Initialization (specifically,
PreInit) is the only time that the Theme and Master Page can be programmatically modified.
&lt;/p&gt;
&lt;h4&gt;Page Load
&lt;/h4&gt;
&lt;p&gt;
Page Load is where control state is restored. If the request is a PostBack, rather
than a new request, all available property values are restored from ViewState and
Form Post data and pushed to the applicable controls. Under most scenarios, this is
where you're going to get what you need from the Database, such as pulling a value
from the query string and loading an item with the matching identity.
&lt;/p&gt;
&lt;h4&gt;Validation
&lt;/h4&gt;
&lt;p&gt;
The Validation event only applies to PostBack requests, and only when Validators are
present in the control collection. The Validate method is executed for each Validator
present, through which the IsValid property is set for each Validator. These IsValid
property values are then cascaded up to the Page's IsValid property. Be aware that
even if all Validators on the page are disabled, the Validation event will still fire;
if a Validator is present, Validate is executed, without regard to any other property.
Also, note that the Validation event is a child of the Page's Load event, so it is
executed within the Page Load event chain, after Page Load, but prior to PostBack
Events and LoadComplete.
&lt;/p&gt;
&lt;h4&gt;PostBack Events
&lt;/h4&gt;
&lt;p&gt;
Once Validation is complete (if applicable), all PostBack events are executed, including
the OnChange event of a DropDownList and the OnClick event of a command button. Post
Back Events are also a child of the Page's Load event, executing after Validation
and before LoadComplete.
&lt;/p&gt;
&lt;h4&gt;Render
&lt;/h4&gt;
&lt;p&gt;
Finally, once all of the data is processed and Post Back events handled, the Page
is rendered within the Web Browser. The Render event consists of saving all control
property data to ViewState, processing the Page and each Control into HTML, and writing
the HTML to the output stream. This is the last opportunity to modify the HTML output.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;h4&gt;Remembering the Order
&lt;/h4&gt;
&lt;p&gt;
If you are having trouble remembering the order, instead try and remember this simple
mnemonic: &lt;strong&gt;SILVER&lt;/strong&gt;; Start, Initialize, Load, Validation, Events, Render.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
If you are doing a lot of ASP.NET programming, or anticipate that you will be in the
near future, try to commit to memory the order of each of these events, and their
scope of influence. Understanding these basic fundamentals of the ASP.NET Page Life
Cycle will help ensure that you are executing your custom code at the right time,
and in the right order, rather than stepping on yourself by conflicting with the core
functionality.
&lt;/p&gt;
&lt;p&gt;
Now that we know the order of execution on Page Events, what is the order of the Controls?
Does Page.Load execute before Control.Load? How about the order of sibling controls?
What is the order of myTextBox1.TextChanged versus myTextBox2.TextChanged? Also, what
are some things to look out for? &lt;a href="http://www.cptloadtest.com/2009/07/14/Dev-Basics-ASPNET-Page-Life-Cycle-Part-2-WebControl-Execution-Order.aspx"&gt;As
this series continues&lt;/a&gt;, we will discuss the details of event execution order within
the ASP.NET Page Life Cycle, as well as some tips, trick, and traps when developing
ASP.NET applications.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f31df0e8-d581-43ef-94f3-a3ebdce80ce6" class="wlWriterEditableSmartContent"&gt;Technorati
Tags: &lt;a href="http://technorati.com/tags/ASP.NET" rel="tag"&gt;ASP.NET&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Page+Life+Cycle" rel="tag"&gt;Page
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Event+Life+Cycle" rel="tag"&gt;Event
Life Cycle&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Dev+Basics" rel="tag"&gt;Dev Basics&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Back+to+Basics" rel="tag"&gt;Back
to Basics&lt;/a&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=d08d861c-a8fb-487e-9ead-0f64b80640ff" /&gt;</description>
      <comments>http://www.cptloadtest.com/CommentView,guid,d08d861c-a8fb-487e-9ead-0f64b80640ff.aspx</comments>
      <category>ASP.Net</category>
      <category>Dev Basics</category>
    </item>
    <item>
      <trackback:ping>http://www.cptloadtest.com/Trackback.aspx?guid=e1276750-40c4-46ca-9045-c0e3d7573fb5</trackback:ping>
      <pingback:server>http://www.cptloadtest.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.cptloadtest.com/PermaLink,guid,e1276750-40c4-46ca-9045-c0e3d7573fb5.aspx</pingback:target>
      <dc:creator>Jay Harris</dc:creator>
      <wfw:comment>http://www.cptloadtest.com/CommentView,guid,e1276750-40c4-46ca-9045-c0e3d7573fb5.aspx</wfw:comment>
      <wfw:commentRss>http://www.cptloadtest.com/SyndicationService.asmx/GetEntryCommentsRss?guid=e1276750-40c4-46ca-9045-c0e3d7573fb5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Scheduled Integration is hard. I remember being involved in projects where developers
would get a copy of the latest source code and a task, and race off like horses at
the track while they spent a few weeks implementing their assigned feature. At the
end of these many weeks was a scheduled integration, where all developers in the team
would reconvene with their code modifications, and try to get their respective code
to play well in a single sandbox. Project managers always seemed to expect that this
would be a quick and painless process, but, of course, it never was. Reintegration
of the code sometimes took just as long as the implementation, itself. Even if developers
are all working in one big room throughout the project, the code remains isolated,
never shared or reintegrated. Fortunately, Continuous Integration specifically focuses
on this problem by reducing (and often eliminating) the end-of-project reintegration
cycle through a continuous constant integration process.
</p>
        <h3>Continuously Integrating your Mind
</h3>
        <p>
For a moment, compare  the process of software development with the process of
learning new technologies in your field. In the past few years of Microsoft's .NET
platform, we've seen .NET 2.0, Windows Communication Foundation, Windows Presentation
Foundation, Workflow Foundation, Extension Methods, Generics, Linq, Dynamic Data,
ASP.NET MVC, and more. For a developer that has not kept up with the latest trends,
to suddenly and quickly catch up with the bleeding edge would be a major undertaking,
and psychologically intimidating. This Scheduled Integration approach to learning
can be overwhelming; the learning process is isolated, and only occasionally reconnects
to the latest technologies. However, a developer that has kept up with the trends,
learning through a continuous integration process, has been constantly updating, constantly
learning the Next Big Thing over these past few years; this developer is already long
familiar with .NET 2.0, WF, WCF, WPF, Generics, and Linq, and is now working on only
Dynamic Data and MVC. The Continuous Integration process ensures that those involved
are current with the latest developments in their project, and that the overwhelming
burden of integration at the end of a project is instead simplified by distributing
it throughout the course of the timeline.
</p>
        <h3>Core Continuous Integration
</h3>
        <p>
At its core, Continuous Integration, or CI, is a development model where developers
regularly commit and update against their source control repository. By committing
(giving everyone else access to your code changes) and updating (getting code changes
from everyone else), the scheduled, tedious integration process at the end of the
project is eliminated. Added on top of this single fundamental, is ensuring the code
works: Automating the build through scripting frameworks like Make, MSBuild, or NAnt
helps developers validate their status quickly, by invoking a validation step that
not only compiles, but executes a suite of unit tests against the code base. Validation
results, along with the latest valid code, are then made easily accessible to anyone
on the team.
</p>
        <p>
The ten tenets of Continuous Integration are:
</p>
        <ol>
          <li>
            <strong>Maintain a Source Code Repository</strong>
            <br />
Use a code repository, such as Subversion, Bazaar, or even Visual Source Safe. This
allows a central point-of-truth for the development team, against which code can be
committed or updated. This even applies to a development team consisting of only one
person, as a local hard drive alone cannot provide change logs, revision differences,
rollback capability, and other benefits of source management. 
</li>
          <li>
            <strong>Commit Frequently</strong>
            <br />
As other developers commit code changes, your local version of the code will get further
and further from the revision head, thus increasing the likelihood of a conflicting
change that will need manual resolution. By committing often (and by association,
updating even more often), everyone can stay very close to the revision head, reducing
the likelihood of conflicts, and reducing time to integrate code and functionality. 
</li>
          <li>
            <strong>Self-Testing Code<br /></strong>"It compiles" is not sufficient criteria for determining if a project is
ready for delivery or deployment to the client. Some level of testing must be conducted
against each compile to measure application quality. Using unit tests, functional
tests, or some other form of automated acceptance tests, the code can evaluate itself
against expected outcome, providing a much more accurate and granular metric for readiness. 
</li>
          <li>
            <strong>Automate the Build</strong>
            <br />
Using Make, NAnt, MSBuild, or similar frameworks, consolidate execution of your full
build into a single command, or a single icon on your desktop. These scripts should
execute a full compile, and run your full suite of testing and evaluation tools against
the compile. 
</li>
          <li>
            <strong>Build Fast, Fail Fast<br /></strong>Even if your build is automated, no one wants to wait 30 minutes for the
build to complete. Building your code should not just be a lunch-break activity. Keep
the build fast to enable developers to do so as often as possible. And if there is
a problem, fail immediately. 
</li>
          <li>
            <strong>Build Every Mainline Commit on an Integration Machine<br /></strong>We all have applications on our local desktops that will not be present in
Production. Instant Messenger, iTunes, Visual Studio, and Office are all common for
us, but rare in Production. However, these applications can conflict or distort build
results, such as a reference to an Office assembly that is not included in your deployment
package. By executing the automated build on an integration machine (iTunes free,
and using a CI suite like Hudson or CruiseControl), you can increase confidence in
your application and eliminate "it works on my box!" 
</li>
          <li>
            <strong>Automate the Deployment<br /></strong>Manual code deployment is a mundane, highly repetitive, error-prone, and
time-consuming process that is ripe for automation. The time commitment adds to the
stress when QA requests yet another deployment to the testing environment, particularly
when all of the developers are in 80-hour-week crunch mode. In turn, this stress reduces
deployment quality; environments often have configuration differences, such as different
database connection strings, credentials, or web service URLs, and often only one
configuration change needs to be overlooked to cause the entire system to malfunction.
Automate this task, so that it can be executed easily, dependably, and often. 
</li>
          <li>
            <strong>Test in a Clone of the Production Environment<br /></strong>In addition to Office and iTunes not being a part of the production server
build, there are aspects of the production environment that are not a part of the
desktop environment. Server farms, federated databases, and load balancing are examples
of things that <em>do not</em> exist on the developer desktop, but <em>do</em> exist
in production, and can cause surprises if they are not considered during development
and testing. Consider the <em>haves</em> and the <em>have-nots</em> in your test environment,
and eliminate these surprises. And if the cost of another production environment is
out of reach, consider Virtual Machines. VMs have significantly reduced the cost of
creating a <a href="http://www.cptloadtest.com/2005/05/25/AWateredDownTestEnvironment.aspx">watered
down test environment</a> that still has things like server farms or database clusters;
even if you cannot exactly replicate your production configuration, mitigate your
risk by reducing the differences between your test and production environments. 
</li>
          <li>
            <strong>Everyone Can View the Latest Build Results<br /></strong>The underlying driver behind Continuous Integration is transparency and visibility.
Communication enables both transparency and visibility by allowing everyone on the
team to know the full status of the build. Did it compile? Did the unit tests pass?
Which unit tests failed? Did the deployment work? How many seconds did it take to
compile the application? Who broke the build? Continuous Integration suites, such
as Hudson or CruiseControl, provide reporting mechanisms on build status. Make this
status available to anyone, including project managers, and even the sales guy. 
</li>
          <li>
            <strong>Everyone Can Get the Latest Executable<br /></strong>On a software development project, communication is more than just green
icons (successful builds) and red icons (failed builds). Communicate the ones and
zeros, in the form of your compiled application, to your team. By allowing other developers,
testers, and even the sales guy (perhaps for a demo) to get the latest bits for themselves,
developers can focus on writing code.</li>
        </ol>
        <h3>Benefits of Continuous Integration
</h3>
        <p>
By continuously integrating all new code and feature sets, development teams can eliminate
that long and tedious scheduled integration effort, which reduces overall effort,
time line, and budget. Through self-testing code and building every mainline commit,
code is continuously tested against a full suite of tests, allowing quick analysis
and identification of breaking changes. Through the easy accessibility of the latest
bits, the team can test early and often, allowing quick identification of broken functionality,
and for early identification of features that don't quite align with what the client
had in mind. And finally, the immediate and public feedback on the success or failure
of the build provides incentives for developers to write code in smaller increments
and perform more pre-commit testing, resulting in higher quality code.
</p>
        <p>
I consider Continuous Integration to be an essential, required part of any development
effort, every time. I started using CI in 2004, and I have since become dependent
on it. I even have a Continuous Integration box at home, validating home projects
for my development-team-of-one, and I am comforted by having a Continuous Integration
server analyzing and validating every code change that I make. I break unit tests
as often as anyone else does, and there still continues to be plenty of times that
I even break the compile. At least once, every developer among us has checked in the
project file while forgetting to add <em>myNewClass.cs</em> to Source Control. It
will break the compile every time. Fortunately, Continuous Integration is always watching
my code commits; it will let me know that it could not find <em>myNewClass.cs</em>,
every time. And my application's quality is remarkably better for it. Every time.
</p>
        <div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f66bf28d-3c0c-4374-a537-abb6c7571de2" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati
Tags: <a href="http://technorati.com/tags/CI" rel="tag">CI</a>,<a href="http://technorati.com/tags/Continuous%20Integration" rel="tag">Continuous
Integration</a>,<a href="http://technorati.com/tags/Developer%20Basics" rel="tag">Developer
Basics</a></div>
        <img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=e1276750-40c4-46ca-9045-c0e3d7573fb5" />
      </body>
      <title>Dev Basics: What is Continuous Integration?</title>
      <guid isPermaLink="false">http://www.cptloadtest.com/PermaLink,guid,e1276750-40c4-46ca-9045-c0e3d7573fb5.aspx</guid>
      <link>http://www.cptloadtest.com/2009/04/02/Dev-Basics-What-Is-Continuous-Integration.aspx</link>
      <pubDate>Thu, 02 Apr 2009 00:25:01 GMT</pubDate>
      <description>&lt;p&gt;
Scheduled Integration is hard. I remember being involved in projects where developers
would get a copy of the latest source code and a task, and race off like horses at
the track while they spent a few weeks implementing their assigned feature. At the
end of these many weeks was a scheduled integration, where all developers in the team
would reconvene with their code modifications, and try to get their respective code
to play well in a single sandbox. Project managers always seemed to expect that this
would be a quick and painless process, but, of course, it never was. Reintegration
of the code sometimes took just as long as the implementation, itself. Even if developers
are all working in one big room throughout the project, the code remains isolated,
never shared or reintegrated. Fortunately, Continuous Integration specifically focuses
on this problem by reducing (and often eliminating) the end-of-project reintegration
cycle through a continuous constant integration process.
&lt;/p&gt;
&lt;h3&gt;Continuously Integrating your Mind
&lt;/h3&gt;
&lt;p&gt;
For a moment, compare&amp;nbsp; the process of software development with the process of
learning new technologies in your field. In the past few years of Microsoft's .NET
platform, we've seen .NET 2.0, Windows Communication Foundation, Windows Presentation
Foundation, Workflow Foundation, Extension Methods, Generics, Linq, Dynamic Data,
ASP.NET MVC, and more. For a developer that has not kept up with the latest trends,
to suddenly and quickly catch up with the bleeding edge would be a major undertaking,
and psychologically intimidating. This Scheduled Integration approach to learning
can be overwhelming; the learning process is isolated, and only occasionally reconnects
to the latest technologies. However, a developer that has kept up with the trends,
learning through a continuous integration process, has been constantly updating, constantly
learning the Next Big Thing over these past few years; this developer is already long
familiar with .NET 2.0, WF, WCF, WPF, Generics, and Linq, and is now working on only
Dynamic Data and MVC. The Continuous Integration process ensures that those involved
are current with the latest developments in their project, and that the overwhelming
burden of integration at the end of a project is instead simplified by distributing
it throughout the course of the timeline.
&lt;/p&gt;
&lt;h3&gt;Core Continuous Integration
&lt;/h3&gt;
&lt;p&gt;
At its core, Continuous Integration, or CI, is a development model where developers
regularly commit and update against their source control repository. By committing
(giving everyone else access to your code changes) and updating (getting code changes
from everyone else), the scheduled, tedious integration process at the end of the
project is eliminated. Added on top of this single fundamental, is ensuring the code
works: Automating the build through scripting frameworks like Make, MSBuild, or NAnt
helps developers validate their status quickly, by invoking a validation step that
not only compiles, but executes a suite of unit tests against the code base. Validation
results, along with the latest valid code, are then made easily accessible to anyone
on the team.
&lt;/p&gt;
&lt;p&gt;
The ten tenets of Continuous Integration are:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Maintain a Source Code Repository&lt;/strong&gt;
&lt;br&gt;
Use a code repository, such as Subversion, Bazaar, or even Visual Source Safe. This
allows a central point-of-truth for the development team, against which code can be
committed or updated. This even applies to a development team consisting of only one
person, as a local hard drive alone cannot provide change logs, revision differences,
rollback capability, and other benefits of source management. 
&lt;li&gt;
&lt;strong&gt;Commit Frequently&lt;/strong&gt;
&lt;br&gt;
As other developers commit code changes, your local version of the code will get further
and further from the revision head, thus increasing the likelihood of a conflicting
change that will need manual resolution. By committing often (and by association,
updating even more often), everyone can stay very close to the revision head, reducing
the likelihood of conflicts, and reducing time to integrate code and functionality. 
&lt;li&gt;
&lt;strong&gt;Self-Testing Code&lt;br&gt;
&lt;/strong&gt;"It compiles" is not sufficient criteria for determining if a project is
ready for delivery or deployment to the client. Some level of testing must be conducted
against each compile to measure application quality. Using unit tests, functional
tests, or some other form of automated acceptance tests, the code can evaluate itself
against expected outcome, providing a much more accurate and granular metric for readiness. 
&lt;li&gt;
&lt;strong&gt;Automate the Build&lt;/strong&gt;
&lt;br&gt;
Using Make, NAnt, MSBuild, or similar frameworks, consolidate execution of your full
build into a single command, or a single icon on your desktop. These scripts should
execute a full compile, and run your full suite of testing and evaluation tools against
the compile. 
&lt;li&gt;
&lt;strong&gt;Build Fast, Fail Fast&lt;br&gt;
&lt;/strong&gt;Even if your build is automated, no one wants to wait 30 minutes for the
build to complete. Building your code should not just be a lunch-break activity. Keep
the build fast to enable developers to do so as often as possible. And if there is
a problem, fail immediately. 
&lt;li&gt;
&lt;strong&gt;Build Every Mainline Commit on an Integration Machine&lt;br&gt;
&lt;/strong&gt;We all have applications on our local desktops that will not be present in
Production. Instant Messenger, iTunes, Visual Studio, and Office are all common for
us, but rare in Production. However, these applications can conflict or distort build
results, such as a reference to an Office assembly that is not included in your deployment
package. By executing the automated build on an integration machine (iTunes free,
and using a CI suite like Hudson or CruiseControl), you can increase confidence in
your application and eliminate "it works on my box!" 
&lt;li&gt;
&lt;strong&gt;Automate the Deployment&lt;br&gt;
&lt;/strong&gt;Manual code deployment is a mundane, highly repetitive, error-prone, and
time-consuming process that is ripe for automation. The time commitment adds to the
stress when QA requests yet another deployment to the testing environment, particularly
when all of the developers are in 80-hour-week crunch mode. In turn, this stress reduces
deployment quality; environments often have configuration differences, such as different
database connection strings, credentials, or web service URLs, and often only one
configuration change needs to be overlooked to cause the entire system to malfunction.
Automate this task, so that it can be executed easily, dependably, and often. 
&lt;li&gt;
&lt;strong&gt;Test in a Clone of the Production Environment&lt;br&gt;
&lt;/strong&gt;In addition to Office and iTunes not being a part of the production server
build, there are aspects of the production environment that are not a part of the
desktop environment. Server farms, federated databases, and load balancing are examples
of things that &lt;em&gt;do not&lt;/em&gt; exist on the developer desktop, but &lt;em&gt;do&lt;/em&gt; exist
in production, and can cause surprises if they are not considered during development
and testing. Consider the &lt;em&gt;haves&lt;/em&gt; and the &lt;em&gt;have-nots&lt;/em&gt; in your test environment,
and eliminate these surprises. And if the cost of another production environment is
out of reach, consider Virtual Machines. VMs have significantly reduced the cost of
creating a &lt;a href="http://www.cptloadtest.com/2005/05/25/AWateredDownTestEnvironment.aspx"&gt;watered
down test environment&lt;/a&gt; that still has things like server farms or database clusters;
even if you cannot exactly replicate your production configuration, mitigate your
risk by reducing the differences between your test and production environments. 
&lt;li&gt;
&lt;strong&gt;Everyone Can View the Latest Build Results&lt;br&gt;
&lt;/strong&gt;The underlying driver behind Continuous Integration is transparency and visibility.
Communication enables both transparency and visibility by allowing everyone on the
team to know the full status of the build. Did it compile? Did the unit tests pass?
Which unit tests failed? Did the deployment work? How many seconds did it take to
compile the application? Who broke the build? Continuous Integration suites, such
as Hudson or CruiseControl, provide reporting mechanisms on build status. Make this
status available to anyone, including project managers, and even the sales guy. 
&lt;li&gt;
&lt;strong&gt;Everyone Can Get the Latest Executable&lt;br&gt;
&lt;/strong&gt;On a software development project, communication is more than just green
icons (successful builds) and red icons (failed builds). Communicate the ones and
zeros, in the form of your compiled application, to your team. By allowing other developers,
testers, and even the sales guy (perhaps for a demo) to get the latest bits for themselves,
developers can focus on writing code.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Benefits of Continuous Integration
&lt;/h3&gt;
&lt;p&gt;
By continuously integrating all new code and feature sets, development teams can eliminate
that long and tedious scheduled integration effort, which reduces overall effort,
time line, and budget. Through self-testing code and building every mainline commit,
code is continuously tested against a full suite of tests, allowing quick analysis
and identification of breaking changes. Through the easy accessibility of the latest
bits, the team can test early and often, allowing quick identification of broken functionality,
and for early identification of features that don't quite align with what the client
had in mind. And finally, the immediate and public feedback on the success or failure
of the build provides incentives for developers to write code in smaller increments
and perform more pre-commit testing, resulting in higher quality code.
&lt;/p&gt;
&lt;p&gt;
I consider Continuous Integration to be an essential, required part of any development
effort, every time. I started using CI in 2004, and I have since become dependent
on it. I even have a Continuous Integration box at home, validating home projects
for my development-team-of-one, and I am comforted by having a Continuous Integration
server analyzing and validating every code change that I make. I break unit tests
as often as anyone else does, and there still continues to be plenty of times that
I even break the compile. At least once, every developer among us has checked in the
project file while forgetting to add &lt;em&gt;myNewClass.cs&lt;/em&gt; to Source Control. It
will break the compile every time. Fortunately, Continuous Integration is always watching
my code commits; it will let me know that it could not find &lt;em&gt;myNewClass.cs&lt;/em&gt;,
every time. And my application's quality is remarkably better for it. Every time.
&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f66bf28d-3c0c-4374-a537-abb6c7571de2" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;Technorati
Tags: &lt;a href="http://technorati.com/tags/CI" rel="tag"&gt;CI&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Continuous%20Integration" rel="tag"&gt;Continuous
Integration&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Developer%20Basics" rel="tag"&gt;Developer
Basics&lt;/a&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.cptloadtest.com/aggbug.ashx?id=e1276750-40c4-46ca-9045-c0e3d7573fb5" /&gt;</description>
      <comments>http://www.cptloadtest.com/CommentView,guid,e1276750-40c4-46ca-9045-c0e3d7573fb5.aspx</comments>
      <category>Continuous Integration</category>
      <category>Dev Basics</category>
    </item>
  </channel>
</rss>