About ASP.

net
The .NET Framework
ASP.NET inherits its programming model from the .NET Framework. This new application development platform brings together the best object-oriented feat res from lang ages s ch as !"" and #ava$ along with the ease and simplicit% of development associated with lang ages s ch as &icrosoft 'is al (asic. The .NET Framework feat res a r n-time e)ec tion environment and a rich class librar% b ilt on top of that. Fig re *-* shows the pieces of the .NET Framework and how the% b ild on each other.
Figure 1-1. A logical view of the .NET Framework

The Common Language untime The common lang age r ntime +!,-. forms the fo ndation of the .NET Framework b% providing a r n-time e)ec tion environment. Applications and components developed to r n in this environment are referred to as managed applications and components. The% are referred to as managed beca se the !,- manages the e)ec tion of code in these applications and components and provides a n mber of services that simplif% their development and deplo%ment. The !,- takes care of a n mber of low-level pl mbing details. /ne of the most important feat res in the !,- is its a tomatic memor% management and garbage collection f nctionalit%. This feat re allows %o to foc s on implementing %o r component0s behavior b% making it almost nnecessar% for %o to worr% abo t memor% management1 and memor% allocation1 related programming errors. This feat re also enables components to easil% interact with one another beca se the% all share a common memor% management scheme. The !,- allows %o to e)press the f nctionalit% of %o r component with a well-designed$ simple$ and int itive AP2 or object model via constr cts s ch as properties$ methods$ and events

that %o can declarativel% describe b% sing metadata attrib tes. Another important feat re of the !,- is that once %o have implemented %o r component$ the !,- a tomaticall% makes it available for se in one or more applications witho t an% e)tra registration re3 irements. The assembl% containing the component can be versioned and deplo%ed in a side-b%-side manner. 2n other words$ the !,- enables m ltiple versions of %o r component to coe)ist. This allows %o to develop and deplo% f t re versions of %o r component witho t inadvertentl% breaking an% e)isting applications that rel% on the e)act behavior of the c rrent version of %o r component. Finall%$ the !,- provides tr e lang age interoperabilit%. 4o r component can be developed$ cons med$ and inherited from in an% .NET programming lang age$ s ch as !5$ 'is al (asic .NET$ &icrosoft #Script .NET$ and &icrosoft 'is al #5. This enables %o to develop %o r component in the lang age %o prefer$ witho t arbitraril% imposing %o r lang age choice on %o r component0s cons mers. The .NET Framework Cla!! Librar" The .NET Framework class librar% b ilds on top of the !,- +as shown in Fig re *-*. and provides a rich hierarch% of classes covering a wide variet% of application and component development scenarios in a consistent and int itive manner. This class librar% tr l% makes component-based programming a realit% b% providing a common s bstrate and AP2 that can be shared b% all components and applications. This e)tensive class librar% can be divided into m ltiple parts$ as Fig re *-* shows. Each logical part is associated with a set of related namespaces sed to create a logical and hierarchical gro ping of classes in a class librar% based on their common p rpose$ f nctionalit%$ or targeted technolog%. The (ase !lass ,ibrar% +(!,. encompasses a n mber of commonl% sed namespaces$ s ch as S%stem$ S%stem.!ollections$ and S%stem.6iagnostics. 2t provides basic f nctionalit% that is sef l in all applications and components$ incl ding the basic primitive t%pes +2nt78$ String$ and (oolean. and commonl% sed data str ct res +s ch as Arra%$ Stack$ and 9ashtable.. The (!, also contains feat res s ch as network connectivit%$ protocol implementations$ file and stream 2:/ classes$ m ltithreading$ te)t processing$ reg lar e)pressions$ globali;ation s pport$ and reflection. 'ario s higher-level class libraries are b ilt on top of this fo ndation.

The A6/.NET la%er in Fig re *-* represents the data access f nctionalit% b ilt into the .NET Framework as part of the S%stem.6ata namespace and its s bnamespaces. A6/.NET provides the abilit% to operate on disconnected or offline caches of relational data. The data access la%er also enables access to a variet% of database engines. 2n partic lar$ it provides ver% highperformance connectivit% to &icrosoft S<, Server. The =&, la%er in Fig re *-* is a co nterpart of the A6/.NET la%er and incl des the classes in the S%stem.=ml namespace and its s bnamespaces. This =&, la%er enables efficient access to =&, data$ both str ct red and nstr ct red. 2n addition$ it provides an implementation of vario s ind str% standards$ s ch as E)tensible St%lesheet ,ang age Transformations +=S,T.$ =&, Path ,ang age +=Path.$ and =&, schemas. This la%er also gives %o the abilit% to seriali;e objects to and from =&, format. The >62" la%er in Fig re *-* represents the object-oriented drawing and painting f nctionalit% provided b% the S%stem.6rawing namespace and its s bnamespaces. The graphics capabilities of >62" incl de rendering primitive objects$ vector art$ and t%pograph% +formatted te)t.. F rthermore$ >62" enables the se and creation of image files in vario s formats$ incl ding #PE>$ >2F$ (&P$ and T2FF. The component model la%er consists of classes in the S%stem.!omponent&odel and S%stem.!omponent&odel.6esign namespaces. 2t provides the architect re that t rns classes into components that can be designed$ c stomi;ed$ seriali;ed$ and deseriali;ed in a design-time tool s ch as &icrosoft 'is al St dio .NET. 2n addition$ this la%er enables different application development technologies to share similar component creation and sage techni3 es as well as design-time feat res. The topmost la%ers in Fig re *-* represent the application development technologies. The .NET Framework enables the development of graphical ?in78 client applications and server applications. ?indows Forms$ which is implemented in the S%stem.?indows.Forms namespace$ enables the development of applications targeting the ?in78 platform. ASP.NET and ?eb Forms$ implemented in the S%stem.?eb namespace and its s bnamespaces$ enable the development of ?eb applications and =&, ?eb services.

Services Provides the f nctionalit% sed in the implementation$ description$ and discover% of =&.?eb.!aching Provides the implementation of an in-memor% caching s%stem that holds cached data based on c stom . that define the e)tensible architect re of ASP. ?eb services into controls. AServer !ontrolsBFirst StepsA and AServer !ontrolsB N ts and (olts$A cover the technical details of e)tending this page framework.NET$ which is implemented in the S%stem.NET controls. A=&.?eb. As a component developer in the ASP. Table *-* lists these namespaces and their associated f nctionalit%.9tml!ontrols$ S%stem. APage Programming &odel$A disc sses the page framework in greater detail. ASP. As a single nit$ these namespaces implement the feat re commonl% referred to as ?eb Forms.NET re3 est processing logic.?eb. S%stem.NET space$ %o 0ll be sing classes from these namespaces in %o r component implementation. ?eb services developed in the form of . S%stem. 2t also contains other definitions +s ch as 29ttp&od le and 29ttp9andler.A #uick Tour of ASP.?eb.@2. S%stem.asm) files.@2$ S%stem.NET Name!$ace! Name!$ace S%stem.NET ASP. ?eb Services$A disc sses how to incorporate =&.@2.?eb namespace and its vario s s bnamespaces$ collectivel% represents the feat res sed in developing both ?eb applications and =&.?eb!ontrols !ollectivel% form the page framework$ the control architect re$ and the standard ASP. ?eb services.?eb.?eb Functionalit" !ontains classes s ch as 9ttp!onte)t$ 9ttp-e3 est$ and 9ttp-esponse$ which are commonl% interface sed to implement the 9TTP r ntime$ its basic re3 est processing architect re$ and the sed intrinsic objects. Table 1-1.

?eb server.NET r ntime can be hosted in a c stom application o tside the 2nternet 2nformation Services +22S.NET is a complete ?eb application development platform.NET A$$lication ASP. .SessionState Provides an implementation of the Session state object. S%stem. Fig re *-8 ill strates a single incoming re3 est into an ASP..NET that enables the incorporation of email deliver% f nctionalit% sing Simple &ail Transfer Protocol +S&TP. Server across m ltiple re3 ests. %TTP untime& e'ue!t Proce!!ing in an ASP. 2t is complete in the sense that it contains all the pieces and la%ers necessar% to handle incoming re3 ests and to create an o tp t response in a ?eb application or =&. Session state is scoped to a single ser session$ and its data can be held either in memor% or in a database sing S<.Sec rit% Provides the implementation of vario s a thentication mechanisms commonl% sed b% ?eb applications$ s ch as forms-based S%stem. ?eb service.&ail A a thentication$ &icrosoft ?indows a thentication$ and &icrosoft Passport a thentication.?eb.e the performance and responsiveness of ?eb applications. The ASP. The caching s%stem is also sed b% the o tp t caching f nctionalit% of ser controls$ as described A@ser !ontrolsC From Page to !ontrol.?eb.A S%stem.NET sage scenarioC ASP. 9owever$ both the diagram and the description that follow are based on the most common ASP. tilit% namespace in ASP.NET ?eb application and the associated response that is generated b% the components that participate in the re3 est-processing life c%cle.dependenc% and e)piration r les.?eb.NET hosted in 22S. This namespace can be sed to optimi.

Some of the common file e)tensions handled b% ASP. The 9ttp!onte)t object also provides access to vario s services that are available for the d ration of the re3 est processing.NET 9TTP r ntime initiali. This conte)t object flows thro gh the linear processing chain shown in Fig re *-8$ in which each object can add other data or objects as conte)t information.asm)$ and .NET *eb a$$lication .NET 2SAP2 based on the e)tensions that ASP.$ an% posted data$ and 9TTP headers.asp)$ . stream.ash).es a n mber of objects to process the re3 est. The response object contains the o tp t content +s ch as the 9T&.NET cache$ and information abo t the ser identit%. being sent back to the re3 esting application from the ?eb server. The re3 est object represents the data being sent to the ?eb server b% the re3 esting application and contains information s ch as the re3 ested @-. 2t allows the components involved in processing the re3 est to generate content into the o tp t stream and to add information abo t the t%pe of the content$ s ch as its &2&E t%pe.NET is registered to handle. The 9ttp!onte)t instance provides access to the re3 est object$ which is an instance of the 9ttp-e3 est class$ and to the response object$ which is an instance of the 9ttp-esponse class.At its core$ the 9TTP r ntime handles an incoming ?eb re3 est from a client application s ch as a ?eb browser$ ro tes the re3 est thro gh the appropriate components in the application that process it$ and then generates a response that is ret rned to the client application iss ing the re3 est. The 9TTP r ntime first creates an instance of the 9ttp!onte)t object$ which contains information abo t the re3 est that is c rrentl% being processed$ and it then makes that conte)t object available to all other components involved in the processing logic. The ASP. These services incl de application and session state$ the ASP.NET incl de . e'ue!t $roce!!ing in!i)e an ASP. The ASP.NET 9TTP r ntime serves as a bridge between 22S and the managed ?eb application. An incoming 9TTP ?eb re3 est is first received b% the 22S ?eb server$ which hands this re3 est to the ASP. Figure 1-(.

asm)$ and . The 9TTP r ntime also selects a single 9TTP handler or 9TTP handler factor% that will be invoked to perform the act al processing of the incoming re3 est$ based on the re3 est @-. ASP.NET .NET provides a n mber of b ilt-in 9TTP handler implementations to handle file e)tensions s ch as . A handler can se an% of the information it is handedBs ch as the re3 est @-. These events incl de application start and end notifications$ re3 est start and end notifications$ and vario s hooks into the life c%cle of a re3 est$ s ch as a thentication and a thori. Each mod le in the pipeline handles vario s global application-level and re3 est-specific events to perform its logic. Each mod le can also raise its own set of events that an application developer can handle. These components implement the 29ttp&od le interface. /ne of the most commonl% sed 9TTP handlers is the page handler.ation. that forms the response content..@2.ation. The control tree has its own life c%cle.The 9TTP r ntime assembles a processing pipeline composed of components referred to as 9TTP mod les to perform re3 est preprocessing actions +s ch as cache look p and a thori.asp)$ .NET does not impose arbitrar% limitations on the implementation of an 9TTP handler..asp) page in a ?eb application is an 9TTP handler that handles incoming re3 ests for that partic lar page. A handler ses the 9ttp!onte)t object to gather information abo t the re3 est and to write o t the res lting response. The implementation of this 9TTP handler instantiates a hierarch% of server objects and ser interface components named server controls that derive directl% or indirectl% from the S%stem.?eb. An 9TTP handler is a component that implements the 29ttp9andler interface$ while an 9TTP handler factor% is a component that implements the 29ttp9andlerFactor% interface. E+ten)ing ASP. and postprocessing actions +s ch as pdating the cache. Essentiall%$ the control tree inside each page handler processes a re3 est and forms the response b% rendering itself into some form of mark p +t%picall% 9T&.$ re3 est headers$ and posted dataBand it can generate an% form of o tp t$ either te)t al or binar%.!ontrol class corresponding to the declarative content present in the .. ASP. Each .ash).asp) file$ and assembles them into a control tree.

These c stom components take the form of c stom controls or new 9TTP handlers and 9TTP mod les.s.NET. The% provide a r n-time programming model and a design-time e)perience that are sed b% the page developer and the page designer.NET page framework.NET Framework$ creates an e)citing new platform for both ?eb application developers and component developers.NET allows %o to develop and register c stom 9TTP handlers and 9TTP handler factories to process new file e)tensions$ s bstit te a b ilt-in 9TTP handler$ and c stomi. 4o can create new controls and e)tend or combine e)isting controls to implement and encaps late new behavior$ f nctionalit%$ and ser interface elements. !ontrols form the b ilding blocks that are sed to create the ser interface of all ASP.ASP. As a component developer$ %o can create components that fit into different levels of ASP.NET allows %o to develop and register c stom 9TTP mod les to participate in its pipeline architect re and perform preprocessing and postprocessing of all incoming re3 ests. ASP. Finall%$ ASP. ASP.NET ?eb applications.NET is an e)tensible ?eb application development platform. Server controls represent the most widel% sed components in an ASP.ing its b ilt-in capabilities with c stom controls and components. F rthermore$ ASP.e vario s aspects of the re3 est:response c%cle. The% contain the f nctionalit% to render themselves as part of the response generated b% the page when it is re3 ested. Server Control! .NET provides a powerf l ?eb application development framework that feat res well-designed architect re for e)tending and c stomi. The primar% foc s of the book is to e)plain the control architect re and to enable %o to develop c stom controls for se in the ASP.NET Ba feat re in and of itselfBres lts from the mod lar design and componenti.NET Framework provides a modern$ consistent$ and int itive class librar% as the fo ndation for b ilding components and component-based applications.NET to c stomi.NET$ along with the rest of the .NET ?eb application. As a component developer$ %o can develop c stom mod les that add e)tra processing for each re3 est$ s bstit te one of the b ilt-in mod les$ or generate content and content headers into the response stream.e the processing of specific @-. The .ed architect re of ASP. The e)tensibilit% of ASP.

NET pages to define the ser interface of a ?eb application.ed b% the server control feat res and capabilities that follow. Server controls contain the logic to provide the best possible e)perience b% e)amining the capabilities of the re3 esting browser or device. For e)ample$ the ?eb controls that ship as part of ASP.Server controls are components sed in ASP. . Server controls are the essential element of the ?eb Forms programming model.NET are abstractions of the 9T&. The ?eb Forms programming model greatl% simplifies application development for page developers and designers and is characteri. • Server controls create an int itive and simpler programming model for the page developer b% hiding the inconsistencies and comple)ities of the nderl%ing technolog%. and 9TTP technologies sed in the creation of browser-based applications. These controls are described as abstractions beca se the% do not directl% represent 9T&. At the other end of the spectr m$ controls s ch as !alendar and 6ata>rid provide new f nctionalit% that is not inherentl% available in 9T&. tag and hides the inconsistencies of the t%pe attrib te of the Einp tG tag. • The% hide the differences between vario s browsers and viewing devices$ as well as the vario s browser versions that a ?eb application might need to target. elementsD instead$ the% offer a more abstract object model for creating those elements. At a high level$ server controls provide abstractions of an nderl%ing ?eb application and presentation technolog%.$ s ch as date selection and data binding. For e)ample$ the ( tton ?eb control maps directl% to the Einp t t%peFAs bmitAG 9T&. The abilit% of server controls to render content as appropriate to the target browser enables the page developer to write a single application that can target m ltiple viewing platforms at r n time. The Te)t(o) ?eb control is slightl% more sophisticated and maps to one of the m ltiple te)t entr% tags provided b% 9T&. The% form the basis of a modern$ component-based$ int itive forms package that simplifies the development of ?eb ser interfaces$ similar to the wa% that the &icrosoft 'is al (asic forms package simplified ?indows programming.C Einp t t%peFAte)tAG$ Einp t t%peFApasswordAG$ and Ete)tareaG.

NET feat res an efficient data-binding model that provides the page developer with complete control over the data-binding process and over data access. • The% manage their state across postbacks and ro nd-trips. The% e)pose their f nctionalit% thro gh properties and methods. The object model e)posed b% server controls is strongl% t%pedB nlike that of 69T&. . 6ata-bo nd server controlsBthose server controls associated with a data so rceBgreatl% simplif% the creation of d%namic pages. • The% provide a compelling data-binding model. The% also provide an event-based programming model$ which allows page developers to implement application logic in response to ser interaction. ASP. Not onl% does being strongl% t%ped lead to better server control performance$ it also red ces programming errors. This feat re allows controls to provide a statef l programming model that creates the ill sion of contin it% while preserving the scalabilit% of a stateless application. Server controls provide a rich server-side programming model.e their rendering.NET page framework known as view state to manage their state across individ al ?eb re3 ests. • The% provide page developers with m ltiple mechanisms to c stomi.• The% f nction as tr e components$ providing the same benefits that %o might e)pect from working with components in other t%pes of applications. • The% contain logic to handle postback data associated with a ?eb re3 est and to enable the page developer to process ser inp t and handle ser actions in their server-side code. &ost ?eb applications are d%namic and feat re content based on a variet% of data so rces. The page developer is freed from nderstanding the details of postback and can instead foc s on the object model of the controlsBin other words$ the controls0 properties and events.e their formatting. Server controls se a feat re of the ASP. Server controls can provide st%le properties as a means to c stomi. A scalable ?eb application is statelessBin other words$ the application doesn0t maintain data and state on the server corresponding to each ser accessing the application.$ which is loosel% t%ped. The data-binding model feat res a simple and generic data so rce model that provides the page developer with a wide choice of objects that can be sed as data so rces.

?eb assembl%.config file. • The% are config rable on a machine level +via the machine. Server controls se both these mechanisms to provide a lookless ser interface$ which is an interface that does not provide a single preestablished look b t instead can blend seamlessl% into the rest of the application0s ser interface.ation of their content and la%o t.asc) files$ respectivel%$ while the .@2$ in the S%stem. The ASP.?eb. This enables page developers and designers to vis all% compose their pages and c stomi.@2.?eb!ontrols namespaces S%stem.e the appearance of the server controls in a ?4S2?4> fashion.@2. or on a ?eb application level +via the web.!ontrol class. .asp) and .?eb. Server controls can s pport config rable defa lts for their properties$ which enables page developers to control or change their behavior niforml% across pages witho t having to change or recompile the application itself. Fig re 8-* provides a high-level view of these namespaces.NET Server Control %ierarch" The ASP.?eb. ser e)perience in a vis al designtime environment s ch as &icrosoft 'is al St dio .@2.?eb. . ASP. • The% provide a rapid application development +-A6.9tml!ontrols$ S%stem. The Page and @ser!ontrol classes represent . Figure (-1.NET.config file.NET !erver control hierarch" All server controls derive directl% or indirectl% from the S%stem.iteral!ontrol class represents a contig o s range of static content present in these files..NET server control and classes are implemented in the S%stem.The% can also provide template properties for c stomi.

controls. *h" *rite Server Control!. These controls provide an object model that is strongl% t%ped$ simpler$ more int itive$ and more consistent than the 9T&. elements$ s ch as anchors$ images$ and tables.-based controls$ ASP. The s ite also contains databo nd controls$ s ch as 6ata>rid and -epeater$ sed to generate d%namic pages based on a data so rce. elements. form elements$ s ch as b ttons and te)t bo)es sed for collecting ser inp t$ as well as other common 9T&.?eb!ontrols namespace are referred to as the ?eb controls. These controls represent plain 9T&.@2. &ost of the controls in this namespace derive directl% or indirectl% from the ?eb!ontrol base class. ASP. This s ite incl des controls that render as the basic 9T&. Altho gh the standard ASP.?eb!ontrols namespace$ the ?eb!ontrol class provides a base class for most ?eb controls and for c stom controls that render themselves as 9T&.-centric object model.9tml!ontrols namespace$ the 9tml!ontrol class provides a base class for all 9T&. 2t incl des a set of validation controls that can be associated with the inp t controls to perform both client-side and server-side validation.@2.NET server controls do not address image maps$ chartgeneration capabilities$ or the creation of masked-edit data entr% forms.NET provides s pport for a thoring mobile ?eb applications targeted at small devices s ch as cell phones via a s ite of mobile controls in the S%stem.NET server controls address the most common application scenarios$ the% are b% no means e)ha stive. For e)ample$ the standard ASP.?eb. tags with a r natFAserverA attrib te and provide an 9T&. 2n the S%stem. 9owever$ ASP. 2n addition to the standard 9T&. There are several reasons and scenarios for which %o might develop server controlsC . controls.@2. 2n fact$ man% scenarios are not directl% addressed b% these controls.2n the S%stem. The class hierarch% presented in Fig re 8-8 shows the complete set of controls.@2.?eb.NET *eb Control! The controls in the S%stem.?eb.?eb.NET does provide an e)tensible control architect re that allows %o to develop c stom controls that can behave in the same wa% as the standard ones at both r n time and design time.&obile!ontrols namespace.

ASP.NET platform even more compelling$ j st as ?in78 Active= components pop lari.. • To enable 2nternet service providers +2SPs. Figure (-(.NET *eb control! Co)e -o)el ASP.NET platform. For e)ample$ in corporations$ developers on the team can p t together controls for se b% page designers who design and implement the application ser interface. 2t is e)pected that the thirdpart% component ind str% will make the ASP.ed 'is al (asic.NET ?eb sites to add s bstantial val e to their service b% offering a galler% of c stom server controls. This feat re is a significant improvement over Active Server Pages$ which re3 ired code to be interspersed with the static content of the . that host ASP. 6eveloping c stom controls that target this space is a compelling market opport nit% beca se ?eb Forms is the primar% programming model for ?eb application development in the . This richer f nctionalit% can enable an 2SP0s members to create more powerf l and interactive ?eb sites$ thereb% enabling the 2SP to disting ish itself from other competing service providers.• To encaps late application logic in the form of re sable and int itive abstractions that can then be sed in m ltiple ?eb applications.NET provides a new code model that enables both page developers and development tools to cleanl% and easil% separate code from presentation. • To create commercial component libraries similar to the Active= controls in &icrosoft 'is al (asic and the tag libraries in #ava Server Pages +#SP. The ASP. • To provide a clean mechanism for dividing work across a large team. 2n this sense$ server controls can provide a toolbo) of common ser interface components and behaviors.NET pages consist of two partsC the definition of the ser interface sing static te)t and server controls$ and the implementation of the ser interface behavior and the ?eb application logic in the form of server-side code.

NET Framework.asp) file via the Page directive.NET$ &icrosoft 'is al #5$ and &icrosoft #Script . 4o can se an% .NET code editor.NET$ all the code-behind class files are precompiled into a single assembl% at design time and therefore m st be implemented in the same lang age. The second form involves implementing a class deriving from Page$ saving the code in a separate file$ and associating it with the . The two models are f nctionall% e3 ivalent and prod ce the same o tp t at r n time.NET programming lang ageBs ch as !5$ 'is al (asic . This form is sometimes referred to as inline code. This new code model is commonl% sed in one of two forms.NET ?eb application.NET ties together all aspects of the page programming model.NETBto implement the behavior and logic of the page. ( t$ for o r p rposes$ what0s most important is that the c stom controls f nction identicall% in both models. This section takes a deeper look at how a page handles an incoming re3 est to generate an o tp t response. The first form involves simpl% embedding code in a r natFAserverA script block within the .isting 8-*.page. Each page can se onl% a single lang age. 2f %o are sing the inline code model$ a single application might have pages implemented in m ltiple lang ages$ which work together seamlessl%. The code model in ASP. The ASP. This form is generall% referred to as code-behind. Page E+ecution -o)el The page e)ec tion model in ASP.NET /verview$A provided the o tline for re3 est processing inside an ASP. 2n this book$ we will se the inline code model for most e)amples$ primaril% beca se it is easier to ill strate concepts with and it is easier to develop b% sing onl% the standard tools available with the .NET is also lang age agnostic$ as is the programming model associated with an% other application b ilt sing the . 9owever$ in the code-behind model sed b% 'is al St dio . AASP.NET Framework S6H.NET beca se it enables editing of the code sing the standard 'is al St dio . 4o specif% the code lang age of the page sing the .asp) file itself$ as %o saw in . .NET code model enables easier division of labor among a team of developers and designers$ and it increases the readabilit% and maintainabilit% of both code and content. The second approachBimplementing code in a separate fileBis the model favored b% 'is al St dio .ang age attrib te of the Page directive.

The incoming re3 est is handled b% 2nternet 2nformation Services +22S. %ow a $age han)le! re'ue!t! The page handler factor% first attempts to look for a previo sl% compiled page class in the ASP. ( t instead of containing controls$ a parse tree contains instances of objects known as control b ilders.NET cache and associates the cache entr% with a file dependenc%.NET cache associated with the . The page handler factor% also places the newl% created page class into the ASP. The page handler factor% is responsible for creating an instance of a Page object$ which is an 9TTP handler that will event all% process the re3 est to prod ce the response o tp t. The page handler factor% then invokes the appropriate compilerBfor e)ample$ the !5 compiler$ csc. This provides significantl% better performance than interpreted code +s ch as code contained in Active Server Pages.e)eB to d%namicall% compile a class deriving from Page. !ontrol b ilders contain information abo t controls that is gathered d ring the parsing process.asp) files.. An important aspect of the page programming model is that the pages e)ec te as f ll% compiled code.$ which hands the re3 est to the 9TTP r ntime in ASP.. The page e)ec tion model begins with the page 9TTP handler factor%$ which is registered with the 9TTP r ntime to handle re3 ests for all . The file dependenc% monitors changes made to the . The parse tree is then converted into code in the lang age associated with the page via the . ?hen this look p fails$ as it does d ring the first re3 est$ the handler factor% reads in the file and parses it to create a parse tree. Figure (-.Fig re 8-I ill strates two incoming re3 ests for the same page and shows how the page framework processes these two re3 ests.asp) file and ens res that an% change a tomaticall% invalidates the cache entr%$ which ca ses the modified file to be reparsed the ne)t time it is re3 ested.ang age attrib te of the Page directive. A parse tree is similar to a control tree. The page handler factor% instantiates the d%namicall% compiled page class and allows the newl% created instance to process the incoming re3 est.asp) file being re3 ested.NET for processing. The page .

This enables the development of stateless and scalable ?eb applications. 6 ring an% s bse3 ent re3 est$ the same page 9TTP handler factor% can se the previo sl% compiled and cached page class and contin e with its normal processing logic b% again instantiating a new page instance to handle the new incoming re3 est.e)ec tes the code generated from the parse tree$ which creates and processes the control tree contained in the original .ation$ loading$ rendering$ and disposing. This allows the handler factor% to skip all the work of opening$ reading$ and parsing the fileD generating codeD and invoking the compiler. Th s$ the page framework does not maintain an% state or page instances across re3 ests. At the end of its processing c%cle$ the page is completel% disposed of. The control tree has its own life c%cle involving initiali.ife !%cle$ Events$ and Postback. This single-parse-and-compile aspect of the page e)ec tion model greatl% improves the performance and responsiveness of the ?eb application.asp) file. A!ontrol . .A 2n its final processing phase$ the page renders itself to prod ce the response content.

Enable deb gging b% setting the 6eb g attrib te of the Page directive to tr e in the .provides low-level pl mbing for managed components$ %o can foc s on designing and implementing the real f nctionalit% of %o r components. 2n addition$ managed components have a simpler deplo%ment model and are easier to version. The server will ret rn an error message that contains vario s links at the bottom of the page. in %o r code inside a server-side script block in I. &anaged components e)ec te on top of the common lang age r ntime +!.asp) file into a control tree b% t rning on page deb gging. !lick the Show !omplete !ompilation So rce link.Viewing the Generated Code 4o can view the code for the class that the page parser generates to transform the . nbalanced parenthesis or a missing semicolon statement terminator.-. . -e3 est the page in %o r ?eb browser. (eca se the !. <%@ Page Debug="true" %> 7.. The following steps provide a 3 ick alternative to viewing the generated so rce codeC *.feat res s ch as lang age interoperabilit%$ a tomatic memor% management$ and code access sec rit%. -anage) Com$onent /verview 2f %o have developed !/& or Active= components$ %o will find managed components significantl% easier to develop.asp) fileC 2. This displa%s the a togenerated code for %o r page. 2ntrod ce a s%nta) error +s ch as an %o r page$ and save the file. and a tomaticall% benefit from !. 9owever$ this file is deepl% nested in a temporar% folder. J. 2n deb g mode$ the class file containing the generated code is preserved..

• • E)pose members that are compliant with the common lang age specification +!.-. (% conforming to the design g idelines$ %o will ens re that %o r component interoperates seamlessl% with classes in the . The following list contains a high-level s mmar% of the g idelines that %o sho ld follow when designing and implementing a component..-$ s ch as !5 or &icrosoft 'is al (asic .NET.-. The !.A thoring a managed component is no different from writing a class in a programming lang age that targets the !. 2n addition$ %o can describe %o r component0s members thro gh metadata attrib tes. • 6eplo% %o r managed component as part of a class librar% in an assembl% +managed librar%. ?hen developing managed components$ %o need to be aware of a few basic programming constr cts and follow a few simple g idelines.!omponent&odel. 4o do not have to e)pose all these constr cts$ b t the p blic and protected members of a component sho ld correspond to these constr cts.-. Pro$ertie! . to ens re that %o r component is sable from other programming lang ages that target the !.!omponent that implements this interface. E)pose an object model that consists of properties$ methods$ and events.NET Framework and provides a similar developer e)perience.S. @nlike !/& components written in !""$ %o do not have to do an% additional work to convert a class into a component. • &ake s re that %o r component conforms to .S is a s bset of programming feat res that are common to all lang ages targeting the !.NET Framework$ implement the 2!omponent interface or derive from a class s ch as S%stem. • A thor %o r component in a programming lang age that targets the !. These g idelines incl de naming conventions and implementation patterns. • To get the f ll benefit of the designer architect re in the .NET Framework design g idelines.

The propert% constr ct has been s pported in 'is al (asic for several editions b t is not offered b% object-oriented programming lang ages s ch as !"" and #ava... ?e0ll look at the propert% constr ct first. +Properties in #ava(eans are s pported indirectl% b% adherence to a naming convention for accessor methods. Then we0ll look at naming g idelines for properties and the advantages of e)posing properties. The Pro$ert" Con!truct Properties are like smart fields that are accessed sing fieldlike s%nta) b t implemented sing accessor methods. The following e)ample ill strates a simple propert% constr ct that defines a Name p blic propert% in the Person classC public class Person { // The private fiel // the #a$e propert". private string %na$e& public string #a$e { get { return %na$e& ' set { belo! is not part of the propert" ata that hol s the value of // construct but contains %na$e = value& ' ' ' .e components in a design-time environment. The .NET Framework brings the ease of -A6 programming to the object-oriented world b% s pporting properties as a first-class object-oriented programming constr ct.Properties encaps late the state of a component and are the essence of rapid application development +-A6. The% allow sers to c stomi.

2n o r e)ample$ a private field holds the data for the Name propert%. Altho gh the get and set accessors are e3 ivalent to methods$ the% cannot be invoked as methods in !5 and 'is al (asic .NET does se the Propert% ke%word as shown in the following e)ample$ which shows the ke%words in 'is al (asic .The boldface elementsBget$ set$ and val eBare ke%words in the !5 propert% s%nta). The s%nta) for setting a propert% is the same as that for setting a field.#a$e = "1ohn"& //T"pe of #a$e is string.NET is not a ke%word in propert% s%nta).et -eturn %na$e . ?hen %o are setting a propert%$ the assigned val e m st match the declared t%pe of the propert%C Person aPerson = ne! Person)*& aPerson.n .NET propert% s%nta) in boldfaceC Private (tring %na$e Public Propert" #a$e)* +s (tring . The propert% constr ct allows %o to abstract the storage and implementation of a propert% from the clients of %o r component.n (et Propert" (et )/"0al value +s (tring* 2n contrast with !5$ val e in 'is al (asic . The get accessorBalso called the getterBretrieves the val e of the propert%$ while the set accessorBalso called the setterBassigns a val e to the propert%. The val e identifier denotes the implicit parameter that is passed into the setter.et %na$e = value . The compiler transforms the code in the get and set blocks into methods that are called propert% accessors.n . ?hile the backing data for a propert% is often a private field$ the data co ld reside . !5 does not have a ke%word named propert%. 9owever$ 'is al (asic .NET b t are indirectl% accessed b% code that assigns or retrieves a propert%.

allows write-onl% properties$ the design g idelines for the ..elsewhereBfor e)ample$ on disk or in a databaseBor it co ld be generated d%namicall%$ as in a propert% that ret rns the s%stem time. 2f %o r component needs a write-onl% propert%$ %o sho ld implement a method instead of a propert% to provide the e3 ivalent f nctionalit%. 2n !5 and 'is al (asic .NET$ the access level of a propert% applies to both accessorsD it is not possible to have a different access level for each accessor. A propert% with onl% a get accessor is a read-onl% propert%$ while a propert% with onl% a set accessor is a writeonl% propert%. Altho gh the get and set accessors are not directl% accessible as methods$ the% are semanticall% e3 ivalent to methods. 0irtual Pro$ertie! 4o generall% provide virt al +overridable.NETBin the class in which the propert% is first declared. properties to allow derived classes to narrow the range of permissible val es$ alter associated metadata$ or perform additional logic when the val e of the propert% changes. F rthermore$ the% can perform an% program logic$ be overridden$ and throw e)ceptions. To make a propert% overridable$ %o m st mark it with the virt al ke%word in !5Band the /verridable ke%word in 'is al (asic . 9ere0s a !5 e)ampleC public class +n"2nteger { private int %nu$ber& public virtual int #u$ber { get { return %nu$ber& ' .NET Framework disco rage them. 2n the ne)t two sections$ we0ll show %o how to override a propert% and perform val e checking in a propert% accessor. A propert% can have an% access level allowed b% the r ntime$ incl ding p blic$ private$ protected$ or internal. Altho gh the !. A propert% can define both the get and set accessors or j st a single accessor.

8ception) "The nu$ber cannot be less than 7.set { %nu$ber = value& ' ' ' 9ere0s a 'is al (asic . To override a propert% in a derived class$ mark the propert% with the override ke%word in !5 and the /verrides ke%word in 'is al (asic .NET e)ampleC Public 3lass +n"2nteger Private %nu$ber +s 2nteger Public 4verri able Propert" #u$ber)* +s 2nteger ."*& .et -eturn %nu$ber .#u$ber& ' set { if )value < 7* { thro! ne! +rgu$ent4ut4f-ange. 9ere0s a !5 e)ampleC public class #on#egative2nteger 6 +n"2nteger { public overri e int #u$ber { get { return base.et %nu$ber = value .n 3lass 5+n"2nteger /verriding a propert% is similar to overriding a method.NET.n (et Propert" (et )/"0al value +s 2nteger* .n .n .

A virt al propert% cannot be sealed +made nonoverridable.#u$ber . Altho gh virt al properties make it easier to e)tend %o r component$ %o sho ld keep a few considerations in mind when %o define virt al properties. in a derived class.n .n 3lass 5Positive2nteger 2f both propert% accessors are defined in the base class$ %o m st override both accessors when overriding a propert%."* .n .#u$ber = value Propert" (et )/"0al value +s 2nteger* . 2f %o want to override the logic in onl% one of the accessors$ %o can let the other accessor delegate to the base class$ as the getter for the N mber propert% does in the previo s e)ample.et 2f value < 7 Then Thro! #e! +rgu$ent4ut4f-ange.n .' base.8ception) % "The nu$ber cannot be less than 7.NET e)ampleC Public 3lass #on#egative2nteger 2nherits +n"2nteger Public 4verri es Propert" #u$ber)* +s 2nteger .#u$ber = value& ' ' ' And here0s a 'is al (asic . 'irt al properties also have implications for .n (et 2f 9"/ase.et -eturn 9"/ase.

2f a propert% val e is not acceptable$ an accessor sho ld throw an e)ception. 4o sho ld se the most appropriate e)ception t%pe$ along with meaningf l error messages. A)vantage! of Pro$ertie! . A well-designed component sho ld perform arg ment validation in its propert% setters. 2n other words$ capitali. 2n the previo s e)ample$ we saw a propert% whose setter throws an Arg ment/ t/f-angeE)ception e)ception when the val e assigned to the propert% is not a positive integer. This helps identif% the location in ser code where the error occ rred. @se Pascal casing. /nce %o define a virt al propert%$ %o m st mark the propert% as virt al in later versions of %o r componentD otherwise$ %o co ld break e)isting derived classes.e.NET Framework$ follow these naming g idelinesC • • @se a no n or a no n phrase as a propert% nameBfor e)ample$ !o nt$ Font$ or Si. Naming 1ui)eline! for Pro$ertie! To ens re that %o r naming scheme for properties conforms to that of the .NET Framework class librar% provides a n mber of e)ception t%pes$ s ch as Arg mentE)ception$ Arg mentN llE)ception$ and Arg ment/ t/f-angeE)ception.versioning. 2f %o r setter accepts erroneo s val es$ there co ld be ndesirable side effects d ring program e)ec tion when the erroneo s val e of the propert% adversel% affects the behavior of %o r component. 2f a propert% does not throw e)ceptions$ it is m ch harder for the ser of %o r component to deb g and track the ca se of the ne)pected behavior. The .e the first letter of the propert% name and the first letter of each s bse3 ent word in the nameBfor e)ample$ &inim m. ?hen a setter throws an e)ception$ it flags an erroneo s propert% assignment as soon as it is made. in addition to getting or setting a propert%. Pro$ertie! an) 0ali)ation Propert% accessors can perform error checking +validation.evel and 'iewState.

• 6esigner s pport?hen a ser selects a component on the design s rface of a vis al designer$ the component0s properties are displa%ed in the propert% browser$ b t its fields are not.NET Framework. . Properties offer man% benefits over fieldsC • 6ata hidingThe storage and implementation of properties$ invisible to the ser.ations$ properties are no less performant than fieldsBas long as the accessors get or set an nderl%ing field witho t adding a significant amo nt of new logic. This also enables better error tracking. 4o cannot implement validation when sing a field. Therefore$ it sho ld come as no s rprise that we recommend that %o sho ld not e)pose fields from %o r components b t instead e)pose properties. 2n this section$ we covered general concepts related to the propert% constr ct in the . nlike that of fields$ is • 'alidationThe setter can perform logic to check whether the assigned val e satisfies an% constraints that are re3 ired b% %o r program logic. • /verridingProperties can be overriden$ th s allowing a derived class to alter the propert% implementation of the base class. • 2n general$ beca se of j st-in-time +#2T. ASimple Properties and 'iew State$A and A!omple) Properties and State &anagement$A we0ll disc ss details specific to properties in ASP.NET controls. • 6ata bindingThe data-binding architect re in ASP.2t is standard object-oriented practice to encaps late %o r component0s data.NET and ?indows Forms s pports binding to properties b t not to fields. optimi. ?e0ll also show %o how to implement different t%pes of properties$ s ch as primitive$ reference$ and collection properties. • 'ersioning(eca se the implementation of a propert% is hidden from the ser$ %o can modif% the implementation in f t re versions witho t breaking compatibilit%Bthat is$ witho t re3 iring an% changes to ser code.

The most notable points are the followingC • • 6etermining when %o sho ld implement a method instead of a propert% Naming conventions for method names and method parameter names 2m$lementing -etho)! 2n!tea) of Pro$ertie! 2n general$ methods represent actions and properties represent data. 2f the implementation of a propert% is considerabl% more e)pensive than that of a field$ implement a method instead. 2n general$ %o sho ld design %o r components so that properties can be set in an% order.NET Framework$A on &S6N. • • 2f some properties re3 ire a ser to set them in a predefined order$ implement those properties as methods.NET Framework$ follow these g idelinesC .NET Framework 6esign > idelinesB?riting !lass . 9owever$ in some sit ations$ it is not appropriate to implement properties. ?hen %o implement a method$ %o s ggest to sers that the% sho ld save and re se a ret rned val e if the% repeatedl% need it. (eca se propert% accessors are e3 ivalent to methods$ %o sho ld instead implement methods in those sit ations. Naming 1ui)eline! for -etho)! an) -etho) Parameter! To ens re that %o r naming scheme for methods conforms to that of the . ?hen %o e)pose a propert%$ %o s ggest to sers that making fre3 ent calls to it is acceptable.-etho)! Not m ch is significantl% different between methods in the managed world and methods in the nmanaged world. E)amples of these cases and additional ones appear in the white paper A.ibraries for the . 9ere are some e)amplesC • 2f a propert% accessor has observable side effects$ implement a method instead of a propert%. • 2f %o need a write-onl% propert%$ implement a method instead.

For e)ample$ if a parameter is of t%pe integer$ a name s ch as co nt is m ch more informative than a name s ch as int. 6escriptive parameter names provide val able information to the ser. This means sing lowercase for the first word in the parameter name and capitali. @se Pascal casing for method namesBfor e)ample$ !reate!hild!ontrols and Save'iewState. is called the event so rce or sender$ and the class that receives the event is called the event sink or receiver. The class that raises the event +sends the notification. • @se camel casing for parameter names. to specif% logic that is e)ec ted when the event occ rs. . 2t is imperative to follow the g idelines for method parameter names beca se parameters are displa%ed in the designer when vis al design tools provide conte)t-sensitive 2ntelliSense and class-browsing f nctionalit%.ing the first letter of each s bse3 ent word in the name Bfor e)ample$ level$ minim m.NET Framework naming g idelines for parameter names. of an event allows its sers +or s bscribers.evel$ and ma)9its.• @se method names that consist of verbs or verb phrases that indicate the task accomplishedBfor e)ample$ Add$ 6ispose$ and 'erif%. Event! An event is a message or notification sent b% a class to signal the occ rrence of an action or a change in its state. The% sho ld be descriptive eno gh so that$ in most scenarios$ the parameter name and t%pe are s fficient to determine the parameter0s meaning. Event-based architect re ses the p blish-s bscribe model in which the so rce +or p blisher. • 6o not prefi) parameter names with 9 ngarian notation. • @se a name based on the parameter meaning rather than its t%pe. These are the g idelinesC • @se descriptive parameter names. The occ rrence or change in state co ld be initiated b% a ser interface action$ s ch as when a ser clicks a b tton$ or ca sed b% some other program logic$ s ch as when a method finishes reading records from a database. • 4o sho ld also follow the .

6elegates combine the best of the earlier paradigms.et0s take at look at the delegate constr ct ne)t and then e)amine how delegates are sed in the event architect re of the .. 2f %o want to see the compiler-generated class$ %o can se the 2.NET Framework S6H. The following line of code contains the declaration of a delegate named &%6elegate that can refer +bind. A delegate also holds a linked list of other delegates$ which is ver% sef l for m lticasting events +sending an event to m ltiple s bscribers.NET Framework provides a new constr ctBcalled a delegateBto provide the f nctionalit% of a callback.6AS& disassembler tool that ships with the . To nderstand this$ let0s begin with a declaration of a delegate class. . 3elegate! A delegate in the .NET Framework. to onl% those methods that have a void ret rn t%pe and take one arg ment of t%pe integerC public elegate voi 9"Delegate)int nu$ber*& (efore we see how to bind a delegate to a method$ let0s look at the delegate declaration more closel%. A delegate has the gran larit% of a f nction pointer and the t%pe safet% of an interface. 2n effect$ a delegate is e3 ivalent to a t%pe-safe f nction pointer. 4o do not provide the implementation for a delegate classD the delegate declaration ca ses the compiler to generate a class that derives from S%stem.NET Framework is a class that can hold a reference to a static or instance method of a class. 2n programming terms$ event architect re needs some sort of callback mechanism. For e)ample$ sing o r earlier declaration$ the compiler generates a &%6elegate class that derives from S%stem.2n general$ the event so rce does not know its s bscribers ahead of time and does not know the logic that its s bscribers wo ld want to implement. 2n !""$ callbacks are implemented sing f nction pointersD in #ava$ the% are implemented sing interfaces. 9owever$ a delegate is not a methodBit is a class with its own methods and other members. A delegate declaration is similar to a method declaration$ with the addition of the delegate ke%word. The signat re of the method m st match the signat re of the delegate. The tool is briefl% described in the 2ntrod ction of this book. The . Event-based programming th s re3 ires an intermediar% mechanism that connects the so rce and the receiver.& lticast6elegate. . And that is not all.& lticast6elegate.

Delegate(a$ple { public elegate voi Print3allbac:)int nu$ber*& public class Printer { private Print3allbac: %print& public Print3allbac: Print3allbac: { get { return %print& ' set { . & lticast6elegate also contains a linked list of delegatesBcalled the invocation listBfrom which it can add or and remove delegates.S%stem. & lticast6elegate derives from the S%stem.NET Framework. ?hen an instance of & lticast6elegate is invoked$ it se3 entiall% invokes the delegates in its invocation list. .NET Framework class librar% do not derive directl% from 6elegateBthe% derive from & lticast6elegate$ which inherits from 6elegate the f nctionalit% to bind a delegate to a method. 4o sho ld not define a delegate b% deriving from & lticast6elegate %o rself. /nl% lang age compilers and the r ntime are intended to generate t%pes that derive from & lticast6elegate. 6elegate t%pes in the .& lticast6elegate is the base class for delegates in the . To define a delegate in !5 or 'is al (asic$ specif% the delegate ke%word and provide a class name and signat re$ as shown in o r definition of &%6elegate.isting 7-*C Li!ting 4-1 A )elegate u!e) a! a callback using ("ste$& na$espace 9(Press. The delegate-related code is boldface in .et0s look at the code first and then disc ss what the sample does.6elegate class. To see delegates in action$ let0s look at an e)ample. 2n the code$ we0ll define a delegate$ a class that e)poses a propert% of the delegate t%pe$ and a class that binds the delegate to a method.

.Print3allbac:)A7*& printer.Print3allbac: = ne! Print3allbac:) river..%print = value& ' ' ' public class Driver { private voi Print2nteger)int nu$ber* { 3onsole. 9ere0s what the sample doesC 2t defines a delegate named Print!allback that has a ret rn t%pe void and accepts a single parameter of t%pe integer. 2n its &ain method$ the 6river class binds the Print!allback delegate of its Printer instance to its Print2nteger method.Print3allbac:)A77*& 3onsole.rite<ine)"Press .-ea <ine)*& ' ' ' 2f %o compile and e)ec te the sample$ the o tp t sho ld look like thisC =ro$ Print2nteger6 The nu$ber is A7. The 6river class defines a Print2nteger method that has the same signat re as Print!allback. Press . =ro$ Print2nteger6 The nu$ber is A77. Now$ whenever the Print!allback delegate is invoked$ the method it binds toBPrint2ntegerBis e)ec ted.Print2nteger*& printer.nter to e8it."*& 3onsole. The Printer class has a delegate propert%$ Print!allback$ of t%pe Print!allback..."> nu$ber*& ' static voi Driver 9ain)string?@ args* { river = ne! Driver)*& Printer printer = ne! Printer)*& printer...rite<ine) "=ro$ Print2nteger6 The nu$ber is {7'.nter to e8it. .

has a delegate member.$ se the class name instead of the class instance name in the constr ctor. ?e0ll soon translate this high-level overview into concrete implementation details$ b t first let0s take a look at event delegates$ which are at the core of this event model. To raise an event$ the event so rce invokes its delegate$ which in t rn invokes the delegates in its invocation list. The reason for this difference is that the other parameter is implicit and points to the object that contains the callback method.Print2nteger. A class that wants to receive the event provides a method that performs some logic in response to the event +an event-handler method. The . 2f %o look at the constr ctor of the S%stem. The two-parameter constr ctor is intended for compilers and other tools. 4o sho ld alwa%s se the one-parameter constr ctor in %o r code$ as we showed in the sample.Print2nteger..NET Framework event model is elegant$ powerf l$ and eas% to implement. ( t we have s pplied onl% one parameter in o r delegate constr ctorC new Print!allback+driver. 2f the method %o are binding to is a static method +instead of an instance method. 6elegates have more feat res than we have covered$ b t the backgro nd we0ve provided sho ld be ade3 ate for sing them in event programming. The !5 and 'is al (asic . This convention is relied pon b% vis al design tools and provides a consistent . Event delegates in the . That completes o r 3 ick to r of delegates.?e wo ld like to make one minor point abo t the delegate constr ctor.& lticast6elegate class$ %o will see that it takes two parameters. 2n essence$ a class that wants to raise an event +send notifications. For e)ample$ if the Print2nteger method were a static method$ %o wo ld instantiate the delegate as new Print!allback+6river. Those delegates in t rn invoke the handlers the% are bo nd to$ th s completing the event se3 ence..NET Framework follow a certain convention for their signat re and their naming scheme. The receiverBor some other classBthen binds the event handler to a delegate and adds that delegate to the invocation list of the event so rce.NET compilers se the implicit parameter and the s pplied parameter to create the twoparameter constr ctor the r ntime needs.. Event 3elegate! Now that %o have seen how delegates work$ it is eas% to nderstand how the% are sed in event programming.

2mage( tton server control.@2.NET Framework and for %o r component to work in a vis al designer$ %o m st follow the signat re convention for an% event delegates that %o define. An e)ample of a class that holds event data is S%stem. &an% namespaces in the .?eb.2mage!lickEvent9andler. Event delegates are named event handlers beca se the% bind to methods that handle events.?eb!ontrols.2mage!lickEventArgs$ which holds ) and % coordinates for the !lick event of the S%stem.NET Framework contain event data classes and event delegates. Event data classes are given the name of the event$ appended b% the s ffi) EventArgs$ s ch as &onth!hangedEventArgs. Event delegates are given names that consist of the event name$ appended b% the s ffi) Event9andler$ s ch as &onth!hangedEvent9andler. 4o sho ld follow the . An event delegate takes two arg ments. The first arg mentBof t%pe /bjectBrepresents the sender of the event. Notice that the signat re convention is not limitingD %o can incl de an% data that %o want to provide for %o r event in the event data class. The base class EventArgs does not hold an% event data.NET Framework is analogo s to that of the Event9andler delegate.vent+rgs e*& The signat re of an event delegate in the .EventArgs.?eb.@2. !lasses that hold event data go hand in hand with event delegates.@2.NET Framework convention for naming event data classes and event delegates.@2. These are the specifics of the signat re conventionC • • The ret rn t%pe of an event delegate is void.( tton server control.pattern for client code.NET Framework$ S%stem. The second arg ment represents data for the event and is an instance of a class that derives from S%stem. 2ts corresponding event delegate$ Event9andler$ is sed for events that do not have associated data$ s ch as the !lick event of the S%stem. To interoperate with the . *iring Event! .Event9andlerC public elegate voi . 2ts associated event delegate is S%stem.?eb!ontrols.?eb.ventBan ler)obCect sen er> . To nderstand the convention$ let0s look at a commonl% accessed event delegate in the .?eb.

./utton%3lic:e *& 2n the preceding code fragment$ b tton is an instance of the ( tton control and is created in a class that has a ( ttonK!licked method that handles the b tton0s !lick event.For completeness$ we0ll briefl% describe the s%nta) for attaching an event handler to an event.. The sample files contain the sample in !5 and in 'is al (asic ./utton%3lic:e ress4f 9e. The process of associating an event handler with an event +adding a delegate to the invocation list.3lic:> + ress4f 9e.NET Framework design pattern for raising an event from %o r class.NET. 9owever$ the nderl%ing event mechanism in ASP.NET Framework. is called event nwiring. 2n the ne)t section$ we0ll show a complete sample that demonstrates these steps.NET$ event wiring and nwiring s%nta) looks like thisC + Ban ler button.3lic:> + The declarative s%nta) of ASP. 2n 'is al (asic . +2n this book$ we0ll foc s on showing %o how to raise events from %o r components and ass me that %o are familiar with handling events in ASP. is called event wiring$ while that of removing an event handler from an event +removing a delegate from the invocation list.ventBan ler)this. 2n !5$ the s%nta) for wiring and nwiring an event handler to an event looks like thisC button. ai!ing an Event 2n this section$ we0ll walk %o thro gh the .NET pages or in other .NET is no different from the rest of the .3lic: E= ne! .NET applications./utton%3lic:e *& button.3lic: D= ne! .ventBan ler)this./utton%3lic:e -e$oveBan ler button.NET pages hides m ch of the event architect re from the page developer.

2f %o r class does not have an% associated event data$ se the EventArgs class for event data.vent+rgs e*& L. 2f a s itable event delegate does not e)ist$ define an event delegate whose second arg ment has the t%pe of the event data class from step *.EventArgs and$ b% convention$ its name sho ld be the name of the event appended b% EventArgsBs ch as Ad!reatedEventArgs$ !ommandEventArgs$ or &onth!hangedEventArgs.vent+rgs 6 .To implement an event in %o r class$ %o need a class for event data$ an event delegate$ a delegate member in %o r class that holds the invocation list$ and a method that sends the event notification. (% convention$ the name of the event delegate is the name of the event appended b% Event9andlerBs ch as Ad!reatedEvent9andler$ !ommandEvent9andler$ or &onth!hangedEvent9andler. /r %o can se another pree)isting delegate if it matches %o r event. The t%pe of this member is the event delegate %o 9ere0s an e)ampleC H. The following code fragment declares an event data classC 2. This class m st derive from S%stem.. 2n %o r class$ define an event member sing the event ke%word. ?e0ll elaborate on these steps in the ne)t section. The following code defines an event delegateC F. The event member holds the list of delegates that s bscribe to the event. 2f %o r event does not have associated data and %o sed EventArgs in step *$ se S%stem. *. >ive the event member the name of %o r event.ventBan ler <o!3harge& sed in step 8.' 7. public class <o!3harge. ?hen this member is invoked$ it dispatches the event b% invoking the delegates.vent+rgs {. /r %o can se another pree)isting event data class if it matches %o r event. . public G. The act al implementation of an event is relativel% straightforwardBthe major effort is in nderstanding how the pieces fit together.Event9andler as %o r event delegate. public event <o!3harge.. 9ere0s a high-level overview of the steps that %o have to perform. elegate voi <o!3harge.ventBan ler)obCect sen er> <o!3harge. 2f a s itable event data class does not e)ist$ define a class to hold event data.

A2. method that invokes the event delegateBafter checking whether an% event listeners e)ist.vent+rgs e* { if )<o!3harge J= null* { <o!3harge)this> e*& The p rpose of the /nEEventNameG method is to allow classes that derive from %o r class to handle the event witho t attaching an event handler to themselves. 2n %o r class$ define a virt al +overridable. ' ' protecte virtual voi 4n<o!3harge)<o!3harge.$ while the ne)t two steps are implemented in %o r class. ?hen the !5 or 'is al (asic .ow!harge event we j st describedC public class /atter" { public event <o!3harge. The name of this method contains the event name prefi)ed b% /n. +4o can see these members b% sing the 2.NET Framework or third part% class librar%.vent+rgs e* { if )<o!3harge J= null* { <o!3harge)this> e*& ' ' ' As %o can see$ %o have to write ver% little code to implement an event. AA.. • • • A private field of the same t%pe as the event delegate$ s ch as the followingC private <o!3harge. 9ere0s an e)ampleC I. AK. 9ere0s the skeleton of a class that implements the .ventBan ler <o!3harge = null& A method that adds delegates to the event delegate$ s ch as the followingC .ventBan ler <o!3harge& protecte virtual voi 4n<o!3harge)<o!3harge. Note that the first two steps in the list describe classes that generall% e)ist o tside %o r class +defined b% %o $ or in the . A7.NET compiler sees a member marked with the event ke%word$ it a tomaticall% generates the three members shown in the following code.M.6AS& tool described in the 2ntrod ction of this book.

NET$ as we showed earlier.ventBan ler*Delegate.ventBan ler han ler* { is the sa$e as that of <o!3harge = )<o!3harge. The access level of the compiler-generated methods is the same as the access level of the event member. ?hen a class raises a large n mber of events$ it might not be efficient to allocate one delegate field per event$ especiall% when onl% a few of the events are commonl% handled. 3e!ignable Com$onent! .ventBan ler*Delegate. This is beca se each delegate field contrib tes memor% overhead to the class instance$ regardless of whether an% event handlers are wired to the associated event. A ser m st wire and nwire handlers sing the "F and -F s%nta) in !5 and the Add9andler and -emove9andler s%nta) in 'is al (asic .-e$ove)<o!3harge> han ler*& ' The two methods generated b% the compiler are event accessors that enable a ser to attach or remove event handlers to or from %o r event.!omponent&odel.ist$ which provides a more optimal storage mechanism for event delegates. 9owever$ even when the compilergenerated methods are p blic$ the% are not directl% accessible from client code in !5 and 'is al (asic .• • • • • • • • • • • • • // The access level of this $etho // the event $e$ber.ventBan ler han ler* { <o!3harge = )<o!3harge.NET Framework provides a tilit% class$ S%stem. public voi + is the sa$e as that of %<o!3harge)<o!3harge.Event9andler. public voi -e$ove%<o!3harge)<o!3harge.NET.3o$bine)<o!3harge> han ler*& ' A method that removes delegates from the event delegate$ s ch as the followingC // The access level of this $etho // the event $e$ber. For s ch sit ations$ the .

2!omponent interface. 2t can then be dragged and dropped onto a design s rface$ and$ when selected$ its properties will be a tomaticall% displa%ed in the propert% browser.!omponent&odel. The 2!omponent interface derives from the S%stem.NET Framework provides special s pport for components that are sed in a vis al designer. 2f %o tr% to add a class that does not implement 2!omponent$ the ser interface to c stomi. ?e0ll describe how to implement the 6ispose method when we look at e)amples of components that need to free nmanaged reso rces.NET.NET Framework$ a designable component is a class that directl% or indirectl% derives from S%stem.e the toolbo) will inform %o that %o r assembl% does not contain components that it can add to the toolbo). 2n the .!omponent or implements the S%stem.The . This kind of designer s pport is not available to a class that does not derive from !omponent or implement the 2!omponent interface. Control! .NET Framework.!omponent&odel. This clean p is re3 ired when a class contains references to nmanaged reso rces that m st be e)plicitl% freed$ s ch as database connections. 2n this section$ we0ll provide a high-level overview of designable components in the . Now let0s e)amine how designable components control e)ternal reso rces. The most significant feat res of a designable component are as followsC • • 6esign-time s pport !ontrol over e)ternal reso rces A designable component can be added to the toolbo) of a designer s ch as &icrosoft 'is al St dio . Altho gh managed objects are a tomaticall% garbage collected$ 26isposable allows a class to perform clean p in a more deterministic manner.26isposable interface$ which contains the 6ispose method that gives a component a chance to free e)ternal reso rces or references that it holds.

!ontrol is capable of drawing sing >62". This class implements the 2!omponent interface and renders mark p te)t that is sed b% a client0s browser or viewing device to render vis al elements. derives S%stem. The . .Forms.. • The base class for client-side This ?indows class Forms controls is from S%stem.?eb. S%stem.NET Framework defines two base control classesC • The base class for ASP.!ontrol.!ontrol.?indows.@2.2n the .NET Framework$ a control is a designable component that renders a ser interface or facilitates the rendering of vis al elements.NET server controls is S%stem.Forms.!omponent&odel.!omponent$ which implements the 2!omponent interface.?indows.