NEWS

Thursday, June 28, 2012

Page Processing and events in asp.net


Processing Page Requests
When an initial request for a page (a Web Form) is received by ASP.NET, it locates and loads the requested Web Form (and if necessary compiles the code). It is important to understand the sequence of events that occurs when a Web Forms page is processed. This knowledge will help you program your Web Forms pages and Web applications more effectively.
As described before, initial page requests are relatively simple. The real work gets done when a page is submitted to itself - and a postback request is generated. Here are a few notes on postback requests:
  • The current value of every control on a Web Form is contained in the postback request. This is referred to as the Post Data
  • The content of the ViewState is also contained in the Post Data. ViewState holds theoriginal property values of every control on a Web Form - before the user made any changes
  • If a postback was caused, for example, by a button click, Post Data is used to identify the button that caused the postback
Postback Event Processing Sequence
Here are the events (and the order) that are raised when a Button is clicked and a postback occurs:
  1. Page.Init + Control.Init for every control on the Web Form
    The first stage in the page life cycle is initialization. After the page's control tree is populated with all the statically declared controls in the .aspx source the Init event is fired. First, the Init event for the Page object occurs, then Init event occurs for each control on the Page. Viewstate information is not available at this stage.
  2. Page.LoadViewState
    After initialization, ASP.NET loads the view state for the page. ViewState contains the state of the controls the last time the page was processed on the server.
  3. Page.ProcessPostData
    Post Data gets read from the request and control values are applied to control initalized in stage 1.
  4. Page.Load + Control.Load for each control on the Page
    If this is the first time the page is being processed (Page.IsPostback property), initial data binding is performed here.
  5. "Change" events are fired for controls (TextChanged, SelectedIndexChanged, and similar)
    The current value (from Post Data) is compared to the original value located in the ViewState. If there is a difference "Changed" events are raised.
  6. Server-side events are fired for any validation controls
  7. Button.Click + Button.Command
    The Click and Command events are fired for the button that caused the postback
  8. Page.PreRender + Control.PreRender
  9. Page.SaveViewState
    New values for all the controls are saved to the view state for another round-trip to the server.
  10. Page.Render
A more detailed explanation of the postback processing can be found in the "The ASP.NET Page Object Model - One Day in the Life of an ASP.NET Web Page" article.
"Learn about the eventing model built around ASP.NET Web pages and the various stages that a Web page experiences on its way to HTML. The ASP.NET HTTP run time governs the pipeline of objects that transform the requested URL into a living instance of a page class first, and into plain HTML text next. Discover the events that characterize the lifecycle of a page and how control and page authors can intervene to alter the standard behavior"
ViewState - the all mighty!
As you can see from the postback steps, the ViewState has a major role in ASP.NET. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests.
"Understanding ASP.NET View State" looks at how an ASP.NET page maintains its state changes across postbacks, examining:
  • The ASP.NET Page Life Cycle
  • The Role of View State
  • The Cost of View State
  • How View State is Serialized/Deserialized
  • Specifying Where to Store the View State Information (see how to store it in a file on the Web server rather than as a bloated hidden form field)
  • Programmatically Parsing the View State
  • View State and Security Implications
Note: if you need to examine the ViewState while debugging, try the Page ViewState Parsers

Show Page Load Time in Web Pages

When testing performance for an individual ASP.NET page, it's often useful to be able to see how long the page took to render.  The bar-none easiest way to achieve this is to simply add Trace="true" to the <%@ Page %> directive, which will yield results like this:
However, often times this won't play nicely with CSS on the page, so you can achieve similar results on a separate URL by adding to your web.config's section.  Then, simply navigate to your web application folder path and add /trace.axd to the request and you'll be able to choose from a list of requests.
In addition to the timings, the trace output also shows a ton of other stuff, which sometimes is more than you need and can be distracting if all you really care about is how fast the page loaded.  To achieve something "good enough" for most purposes, you can add something like the following to your base page class or master page:
DateTime startTime = DateTime.Now;
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    this.LoadTime.Text = (DateTime.Now - startTime).TotalMilliseconds.ToString();
    this.ServerTime.Text = DateTime.Now.ToString();
}

This example is from a master page that includes the following in its markup:
<div id="footer">Load Time: <asp:Literal runat="server" ID="LoadTime" /> ms<br />
Server Time:  <asp:Literal runat="server" ID="ServerTime" /><br />

This approach doesn't include some of the time spent on rendering logic, but does include everything else the page is doing, such as expensive calls to web services, the file system, or the database, and so it does a good job of showing whether or not changes to such access are improving the overall page load time (or not).
Phil Haack has an alternative approach that uses an HttpModule to insert the page load time into the page's HTML.  The code as written can have some issues with JSON callbacks from UpdatePanels, but some of the comments on the post describe techniques to avoid this.  The nice thing about an HttpModule is that you don't need to duplicate the code in other projects or pages.  Once you have your own HttpModule for doing page timing, you can add it to any projects you like, and it's easily included in developer builds and not in production builds through the use of separate web.config files in each environment (which in all likelihood is already in place).
It's also worth noting that Phil's example uses the System.Diagnostics.Stopwatch class, which provides greater accuracy than simply comparing DateTimes directly.  For something like this, where we're looking at full page load times, the extra accuracy is typically not needed, but it's an important class to know about for when you're timing small bits of code to try and determine which is faster down to a few milliseconds (or less).  On some systems the Stopwatch may not be any faster - you can check if the currently running environment supports higher resolution timing by using the IsHighResolution property.


Friday, June 15, 2012

Simulating ItemCommand Event


Simulating ListView’s ItemCommand Event

Data controls in asp.net like GridView, DataList, Repeater, ListView,… are having an event called ItemCommand.
This event will raise whenever any button, linkbutton,… are clicked.
But my requirement is to call the ItemCommand event whenever the ListView.Databind() is done.
Below is the procedure I followed for that.
System.Web.UI.WebControls.LinkButton lnkbtn = (System.Web.UI.WebControls.LinkButton)lvMyAlbums.Items[0].FindControl("lnkAlbum");
            ListViewCommandEventArgs ev = newListViewCommandEventArgs(lvMyAlbums.Items[0], lnkbtn, newCommandEventArgs(lnkbtn.CommandName, lnkbtn.CommandArgument));
            // Call ItemCommand handler
            lvMyAlbums_OnItemCommand(lvMyAlbums, ev);

Similary we can simulate grid ItemCommand as shown below:

LinkButton lnk = (LinkButton)RadGridPeople.Items[0].FindControl("lnkPeopleName");
                     GridCommandEventArgs ev = new GridCommandEventArgs(RadGridPeople.Items[0], lnk, new CommandEventArgs(lnk.CommandName, lnk.CommandArgument));
                     RadGridPeople_ItemCommand(RadGridPeople, ev);

Tuesday, June 5, 2012

Xbox SmartGlass


What Is Xbox SmartGlass?

As expected, Microsoft just announced something called SmartGlass at E3. Less expected? Just how awesome SmartGlass turned out to be. What could have been just an Apple AirPlay imitation, is something more ambitious. Something that could change television forever. But what is it, exactly?
It's the lifeline that'll make your dumb TV smart.

SmartGlass is an app...

SmartGlass is a new app that turns your phone or tablet into another screen for your TV, another controller for a game, a companion feature for a show, a remote control for the Internet and more. More importantly, it'll work with iOS, Android and Windows, so you won't need to buy new hardware to fit into its ecosystem.

...that connects your phone, tablet or computer with your Xbox 360...

SmartGlass does more than just push video and audio around. It turns the Xbox 360 into the beating heart of a multi-screen media experience in your living room. A tablet, phone or computer running SmartGlass essentially becomes a second and third screen for your TV.
A concrete example: As Game of Thrones was being shown on the TV via Xbox 360, a SmartGlass-enabled tablet displayed a map of Westeros and other relevant information about the show. Content can either be pushed from the tablet/phone/computer to the 360, or from the 360 directly to the TV. SmartGlass connects all of those devices to make content engrossing on multiple levels. Your individual devices don't have to ignore each other, they'll work together to entertain you more.

...and works with games, movies, TV shows and the Internet..

But SmartGlass can be used with more than just movies and TV shows. Microsoft also showed how a gamer could use a tablet as a separate playbook while playing Madden on the Xbox. Even further, Microsoft will finally bring Internet Explorer to the Xbox, with SmartGlass turning your phone into mouse. Sure, it's silly to surf the web on your television with an old and gray keyboard and mouse setup—unless the keyboard and mouse are your phone and tablet.

...to make your living room a lot smarter...

Microsoft very clearly wants to make the Xbox 360 the center of your living room transformation. It's the hub that powers everything. But if the Xbox 360 is the heart and the brain, SmartGlass gives users the limbs needed for a full functional, self-sufficient media beast. Combined with the Xbox's growing dominance as a top-flight streaming box, and you've got yourself a potentially very powerful monster.

...and it's all because of the Xbox.

If you think about it, Microsoft's vision of the living room of the future is a throwback to what the company has already known and mastered: the PC. It's smartening up the living room by using the Xbox as the PC, the TV as the monitor, the phone and tablet as the keyboard and mouse, Kinect as its futureproof wild card technology. SmartGlass, then, plays the role of Windows, seamlessly connecting everything.
But the real key to SmartGlass is its openness. Bring your own tools, Microsoft is saying. It doesn't matter. Because however you control it, all that really matters is the Xbox. And that's all Microsoft.