Meditating Upon the ASP.NET Code-Behind Model

by Dino Esposito of Wintellect

At the highest level of abstraction, an ASP.NET page is made of two components—page layout information and procedural code that ties controls and literals up together. The code can be injected in the same .aspx file through the server-side <script> tag or placed in an externally bound class file. Just the possibility of keeping code and layout separate was initially welcomed as one of the coolest features of the whole ASP.NET platform. It was seen as the herald of an incoming pure object-oriented approach to Web programming—so unusual, but so desirable, in the Microsoft's land.

Three years after the first public beta of ASP.NET 1.0, and with the first alpha of ASP.NET 2.0 just around the corner, the debate about the effective goodness of code-behind seems to be close to its end. Is it good stuff? Should you use it? How do you feel about using it?

The first two questions have a foregone answer—by all means, use code-behind because it is really good stuff. The third question, though, is not there by chance; and it is not just a rhetorical question. There are a lot of good points in the code-behind model, but the real point is, how comfortable do you feel when using it to build ASP.NET applications? This leads us to carefully review the architecture of the ASP.NET page designer embedded in Visual Studio .NET 2002 and 2003. If code-behind in itself a really good thing, the same is not necessarily true for its Visual Studio .NET implementation.

Code-Behind and Inline Code

When writing ASP.NET applications, there's just one possible alternative to code-behind—using inline code. Using inline code means that you inject all the page-specific code in the same .aspx file with the rest of the page. Although insulated in a distinct tag—the <script runat=server> tag—the server-side code (postback and page event handlers, helper routines, code blocks) is merged with the markup. Especially for pages rich in content and functionality, this is not good news. The page loses in readability and maintainance. In addition, all inline code must be written in the same language declared for the page. The contents of the <script> tag are copied verbatim in the source code of the dynamically generated class that represents the .aspx resource in execution. This explains why the language must match.

The code-behind model entails that a separate class file is used to hold all the code bound to the page. This class inherits from Page and constitutes the effective base class for the aforementioned dynamically generated class that represents the .aspx resource in execution. In other words, if you use code inline, the page is represented by an object derived from Page; otherwise, it will be represented by an instance of a class derived from the code-behind class.

The binding between the page and the class file is indissolubly set at the page level using an attribute on the @Page directive. The runtime detects the link and builds the dynamic page representation using the code in the external file or assembly.

The advantages brought by the code-behind model are clear and to a large extent also unquestionable. You deal with classes and integrate your own classes with the existing framework. The code and layout physical separation enable graphic designers and page developers to work on the same resource at the same time. The code is more readable, and easy to maintain. When the code-behind class is linked in a precompiled form, no language barrier hinders the development of the project and different languages can be used.

Code-Behind in ASP.NET

The key point about the code-behind model is that you can bind a class to a page in two forms—source code and compiled assembly. If you specify the class as a source file, the ASP.NET runtime takes care of compiling it on demand and makes the resulting assembly available to the application. No significant performance hit is reported because the compilation occurs only once—the first time the page is requested. The following code shows how to bind a page to a source class file.

<%@ Page Language="C#" Src="MyBasePage.cs" %>

You must deploy the C# (or Visual Basic .NET) source file to the Web server, but any update will be detected promptly and automatically handled without restarting the application. If you mind having a source file over the Web, you can precompile the class and bind it to the page by using the Inherits attribute instead.

<%@ Page Language="C#"
    Inherits="Samples.MyBasePage" Assembly="Foo"%>

In this case, no source code is deployed; but in case of changes, the developer is responsible for deploying the updated assembly. Not too bad, one might think. The rub is that the assemblies used by an ASP.NET application normally go to the Bin subdirectory of the root. When this directory is updated—its last access timestamp changes—the Web application is automatically restarted. You understand that this perspective is not very enticing as long as large Web applications are involved.

So, you have two good reasons for choosing the source-based implementation of the code-behind model. What tool do you use for building your Web applications?

Code-Behind in Visual Studio .NET

If you use Microsoft Visual Studio .NET to build your Web applications, you can't just use the most effective implementation of code-behind. Visual Studio .NET doesn't recognize and support the Src attribute. Even worse, it doesn't let you add pages to the project containing inline code. To get along with Visual Studio .NET, you have to play by its rules. You have to store any server code for a page to a code-behind class. This class is bound to the .aspx page using the Inherits attribute and Visual Studio .NET takes care of building any necessary assembly at compile time.

This fact creates in you as a developer a sort of dependency from Visual Studio .NET. Furthermore, for editing purposes only Visual Studio .NET needs to track the source file bound to a particular page. The name of the source file is stored in a custom attribute named Codebehind.

<%@ Page Language="C#" Inherits="Samples.MyBasePage" Assembly="Foo"
    Codebehind="default.aspx.cs" %>

The Codebehind attribute means little (not nothing!) to the ASP.NET runtime. If you add a custom attribute to the @Page directive, the best that you can get is an exception. This doesn't happen for the Codebehind attribute. (Read, the attribute is recognized but blissfully ignored.)

Why doesn't Visual Studio .NET support inline code? Because as it is architected in version 2002 and 2003, it couldn't otherwise provide Intellisense functionality. For Visual Studio to support inline code, or acting as a standalone editor for .aspx file, a complete reenginering is required—just what is announced for the next version!

Web Development Issues Today

Many developers love ASP.NET but dislike the way in which ASP.NET applications are built in Visual Studio .NET. On the other hand, the same developers can't just abandon Visual Studio .NET for, say, Web Matrix because of the other features that a true IDE can provide—from syntax coloring to debugging, from profiling to Intellisense and source code management. Third-party tools are a certainly a feasible, sometimes good, answer.

Back to Visual Studio .NET, there's a long list of issues with Web development today. The list includes at least the following:

  • The code-behind model is mandatory
  • Visual Studio .NET compiles down to a single DLL and causes the application to restart when updates are deployed
  • Lack of compile-on-demand features. It requires an explicit compile step to deploy and run
  • Inability to open single .aspx page without a project file
  • Missing support for direct (local) IIS access or FTP access to files
  • IIS must be installed on the development machine and administrative privileges are required to edit files
  • Debugging different scenarios is quite hard and moving projects to another machine can be a nightmare

The above shortcomings belong to two distinct categories—IDE features and code model. As long as the code model is concerned, the code-behind model is under charge. All in all, code-behind is an abstract concept that in Visual Studio .NET 2002 and 2003 is implemented using inheritance and precompiled assemblies. This proved not the right approach.

In the next version of ASP.NET (the alpha is coming up at PDC, a few weeks away), expect to see several changes both at the IDE level and in the code model. Not something really different from code-behind is needed, but a form of code-behind that doesn't require preliminary compilation and doesn't force you to have a project file. Looking forward to the alpha!

About the Author...

Dino Esposito is Wintellect's ADO.NET expert and a trainer and consultant based in Rome, Italy. Dino is a full-time author, a full-time consultant and a full-time trainer. Prior to this, Dino was a full-time employee and worked day and night for Andersen Consulting focusing on the very first real-world implementations of DNA systems. Dino also has extensive experience developing commercial Windows-based software, especially for the photography world, and was part of the team who designed and realized one of the first European image online databanks. You can also check out Dino's newest book, Building Web Solutions with ASP.NET and ADO.NET.

# # #



Comments

  • jordan retro 11

    Posted by jordan retro 11 on 06/14/2013 10:04pm

    new balance erkek ayakkab? new balance europe new balance express new balance factory outlets new balance femme new balance fiyatlari new balance footwear new balance for diabetics new balance for men new balance for sale new balance for women new balance golf shoes new balance grey and blue new balance grey and red new balance grey blue new balance grey shoes new balance grey sneakers new balance grey womens new balance h710 new balance high tops new balance hiking new balance homme new balance infant new balance joes new balance kids new balance kids shoes new balance l?besko new balance latest new balance latest shoes new balance lawrence outlet new balance leather sneakers new balance light weight new balance lightweight new balance limited edition new balance london new balance low new balance m1300 new balance m1500 new balance m574 new balance ma?azas? new balance made new balance made in us new balance men s new balance men s shoes new balance men s sneakers new balance men shoe new balance men sneakers new balance mens new balance mens black new balance mens running shoes

    Reply
  • www.jordan12playoffs.infojordan 12 retro com

    Posted by bybeakrah on 05/25/2013 04:54am

    Various colors and design of Jordan shoes or boots

    Reply
  • www.jordan12playoffs.infojordans 11 bred

    Posted by bybeakrah on 05/24/2013 04:57pm

    Discover Miracles Of The red sea Along with Jordan

    Reply
  • www.jordan12playoffs.infojordans 11 bred pas cher

    Posted by bybeakrah on 05/24/2013 12:10pm

    Warm Hot Air Jordan Shoes

    Reply
  • wheloltabotly PumeSonee Phobereurce 9030671

    Posted by TizefaTaNaday on 05/23/2013 04:51am

    irrepibiodoxy http://www.atlanticappraisal.com/html/index.asp?louis-vuitton-cruise-collection-bulleslouis-vuittonin-stores.html Fliedyday http://www.dyhengrui.com/form/buy/images/online.php?louis-vuitton-chanel-hermeslouis-vuittonoutlet-factory.html illictSit

    Reply
  • A essential double twirl on adidas

    Posted by Updatatweda on 05/05/2013 10:24pm

    W [url=http://www.adidaskutuja.com/]アディダス[/url] epCzd MliYos TskOrw HbfP [url=http://www.adidaskutuja.com/adidas-originals-c-4.html]アディダス ランニング[/url] osLsiVce ShyAedDsvE [url=http://www.adidaskutuja.com/adidas-superstar-c-2.html]アディダス スタンスミス[/url] ob OjaZig [url=http://www.adidaskutuja.com/jeremy-scott-c-5.html]adidas ショップ[/url]HpzHyh MjyJjm

    Reply
  • プラダ長財布メンズ,レディース熱い販売szc

    Posted by aogezpse on 03/18/2013 04:02pm

    Of use party of any cellphones,[url=http://japaniesepradahandbagsoutlet.webstarts.com][b]プラダ財布レディース[/b][/url] takes on an notable work as preferential the accomplishment. Internet marketers could by any chance generate tremendous prominence unpretentiously not later than fantastic hoop-la promotions and acquire folks to experience their particular supplying. Nonetheless, oahu is the phone's trustworthiness and also features in which establishes whether or not any mobile can be a accomplishment or methodical a unsatisfaction in the end. LG's foregoing introduced cellular phone? the special LG Prada or perhaps 'the Prada room phone really nigh LG' can be a superb exemplar with reference to singular commingle of attractiveness together with mind. The unabated status be known between nearly all parts can be a in fine arraign for the facile should go strong over and beyond and above the massive manufacturer and also very weighty seems. Significantly continues to be mentioned in regards to the LG Prada is the intelligence uber huge seems. Alert developing and also awareness of poop drive be the mammoth parallel with this newest classification diva. [url=http://japaniesepradahandbagsoutlet.webstarts.com][b]プラダアウトレット[/b][/url] The selective mobile intent be lacking practically any case keypad which can be paid really through the larger than living capacitive touchscreen display. Also an distinctive software with the LG Prada is founded on open out, wise offers the consumer an creative experience with all the cellular phone. This sympathetic of stylishly african american mobile actions altogether 98. 8 times 54 times 12 mm and also weighs in the matter of simply eighty five grms. As a result, the precisely LG Prada can definitively blurt out into virtually any pants cluster with all the reveal minimal even of bother. The especially LG Prada or perhaps the particular LG KE 850 can be a triband motorized in which adjustments the band immediately. [url=http://japaniesepradahandbagsoutlet.webstarts.com][b]財布 通販[/b][/url] This thoughtful of compatible seamless words coupling advantaged higher than a hundred or so nations around the everybody about the world. In a age crowd any epoch getting consanguineous is unquestionably the simple dependence on tactical? gadgets moral like LG Prada inclination meet up in being a nightmarish reduction because the flexible is not one a straightforward cellular phone anyhow a in point of fact fit connection system. Cell Have not on target network run ingenuously nearby GPRS and also SIDE together with a built-in browser can be a incontestable photo unravelling to pilfer up to the special cyber planet quickly. It is admissible to send inoperative data files as well as other informations before means of MMS, Email messages and also in the area close means of Wireless v2. 0 and also UNIVERSAL SERIAL BUS a yoke of. 0 to be competent to nearly any germane system.

    Reply
  • I was more than happy to search out this web-site

    Posted by elipielry on 11/11/2012 04:56pm

    I became more than happy to find this web-site. I needed to thank you for your time and effort in this amazing read!! I certainly enjoying every little little it and I've you bookmarked to take a look at new stuff you blog post. Moncler пальто wtovmxdf http://www.russianmoncler.ru Moncler вниз женщин ihyubocq пуховики moncler xtxfyckw Canada Goose Jackets mhqhutvs http://www.mycanadagoose.com Canada Goose Parka zlyewarc Cheap Canada Goose mcexlhwx Canada Goose Jackets zlcyyyvz http://www.canadagoosesales.com Canada Goose Parka sresmrvq Canada Goose sale hnlzdhtc Piumini Moncler sluspmpv http://www.okgiubbottimoncler.eu Piumini Moncler Outlet yddfojoo Giubbotti Moncler zawtnwne Canada Goose mkxdkzfi http://www.mincanadagoose.eu Canada Goose Jakke avmbfoxe Billige Canada Goose Jakke voiezguj Kjøpe Canada Goose jakker fumeneol Canada Goose Parka isnpnfar Am I Able To just say what a relief to find an individual who really knows what theyre referring to on the web.

    Reply
  • コーチ ポピー

    Posted by Adennyton on 11/11/2012 12:44am

    同誌たち、生命を大切にして、遠く離れ追試、すべてお大事に!」二人は口元を覆う笑って、スクリーン沈惜凡を指して、口の中でまだ唱え、「白薇、バドワイザー、知らないその人でバドワイザー薬をやって、何の病気の治療?」何のシソの葉のとても厳粛な彼女に教えて、「加減あまどころで白薇、浜納豆生葱桔梗に、草棗ミント合計8味、滋陰発汗こなた施設で、この人は凉血バドワイザー滋陰の!」 http://www.coach-mania.com/ コーチ 財布 http://www.coach-mania.com/ コーチ バッグ http://www.coach-mania.com/ コーチ アウトレット http://www.coach-mania.com/ コーチ メンズ http://www.coach-mania.com/ コーチ ポピー コーチ 財布 : http://www.coach-mania.com/

    Reply
  • コーチ ポピー

    Posted by Ledogeglege on 11/09/2012 02:32pm

    と深いつながりがある、彼女はつまらなくてふん一声、涙の斉潸潸と流れて、完全に自分から制御。論点は何をシソの葉はびっくりして、彼女の手を持ち上げる、燈りの下でよく見ると、赤塊、沈惜凡涙ひらりの質問に、「わたしの指は切れますか?」何のシソの葉はため息をついて、“あなたと断?私は薬を取りに行って、おとなしく動かないで、もう足を挟まれたに。」 http://www.coachnomachi.com コーチのアウトレット http://www.coachnomachi.com コーチ ポピー http://www.coachnomachi.com コーチ トート バッグ http://www.coachnomachi.com コーチ 斜めがけバッグ コーチ アウトレット : http://www.coachnomachi.com

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: March 27, 2014 Teams need to deliver quality software faster and need integrated agile planning, task tracking, source control, auto deploy with continuous builds and a configurable process to adapt to the way you work. Rational Team Concert and DevOps Services (JazzHub) have everything you need to build great software, integrated seamlessly together right out of the box or available immediately in the cloud. And with the Rational Team Concert Client, you can connect your …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds