0% found this document useful (0 votes)
72 views38 pages

The Common Language Runtime

ASP.NET inherits its programming model from the.NET Framework..NET feat res a r n-time e)ec tion environment and a rich class librar% b ilt on top of that.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
72 views38 pages

The Common Language Runtime

ASP.NET inherits its programming model from the.NET Framework..NET feat res a r n-time e)ec tion environment and a rich class librar% b ilt on top of that.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 38

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.

A #uick Tour of ASP.NET


ASP.NET$ which is implemented in the S%stem.?eb namespace and its vario s s bnamespaces$ collectivel% represents the feat res sed in developing both ?eb applications and =&, ?eb services. As a component developer in the ASP.NET space$ %o 0ll be sing classes from these namespaces in %o r component implementation. Table *-* lists these namespaces and their associated f nctionalit%.
Table 1-1. ASP.NET Name!$ace!

Name!$ace S%stem.?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. 2t also contains other definitions +s ch as 29ttp&od le and

29ttp9andler. that define the e)tensible architect re of ASP.NET re3 est processing logic. S%stem.?eb.@2$ S%[email protected]!ontrols$ S%stem.?eb.@2.?eb!ontrols !ollectivel% form the page framework$ the control architect re$ and the standard ASP.NET controls. As a single nit$ these namespaces implement the feat re commonl% referred to as ?eb Forms. APage Programming &odel$A disc sses the page framework in greater detail. AServer !ontrolsBFirst StepsA and AServer !ontrolsB N ts and (olts$A cover the technical details of e)tending this page framework. S%stem.?eb.Services Provides the f nctionalit% sed in the implementation$ description$ and discover% of =&, ?eb services developed in the form of .asm) files. A=&, ?eb Services$A disc sses how to incorporate =&, ?eb services into controls. S%stem.?eb.!aching Provides the implementation of an in-memor% caching s%stem that holds cached data based on c stom

dependenc% and e)piration r les. This namespace can be sed to optimi;e the performance and responsiveness of ?eb applications. 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.A S%stem.?eb.SessionState Provides an implementation of the Session state object. Session state is scoped to a single ser session$ and its data can be held either in memor% or in a database sing S<, Server across m ltiple re3 ests. S%stem.?eb.Sec rit% Provides the implementation of vario s a thentication mechanisms commonl% sed b% ?eb applications$ s ch as forms-based S%stem.?eb.&ail A a thentication$ &icrosoft ?indows a thentication$ and &icrosoft Passport a thentication. tilit% namespace in ASP.NET that enables the incorporation of email deliver% f nctionalit% sing Simple &ail Transfer Protocol +S&TP..

%TTP untime& e'ue!t Proce!!ing in an ASP.NET A$$lication


ASP.NET is a complete ?eb application development platform. 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 =&, ?eb service. The ASP.NET r ntime can be hosted in a c stom application o tside the 2nternet 2nformation Services +22S. ?eb server. 9owever$ both the diagram and the description that follow are based on the most common ASP.NET sage scenarioC ASP.NET hosted in 22S. Fig re *-8 ill strates a single incoming re3 est into an ASP.NET ?eb application and the associated response that is generated b% the components that participate in the re3 est-processing life c%cle.

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. An incoming 9TTP ?eb re3 est is first received b% the 22S ?eb server$ which hands this re3 est to the ASP.NET 2SAP2 based on the e)tensions that ASP.NET is registered to handle. Some of the common file e)tensions handled b% ASP.NET incl de .asp)$ .asm)$ and .ash). The ASP.NET 9TTP r ntime serves as a bridge between 22S and the managed ?eb application. The ASP.NET 9TTP r ntime initiali;es a n mber of objects to process 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. 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. 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. 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 @-,$ an% posted data$ and 9TTP headers. The response object contains the o tp t content +s ch as the 9T&, stream. being sent back to the re3 esting application from the ?eb server. 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. The 9ttp!onte)t object also provides access to vario s services that are available for the d ration of the re3 est processing. These services incl de application and session state$ the ASP.NET cache$ and information abo t the ser identit%.
Figure 1-(. e'ue!t $roce!!ing in!i)e an ASP.NET *eb a$$lication

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;ation. and postprocessing actions +s ch as pdating the cache.. These components implement the 29ttp&od le interface. Each mod le in the pipeline handles vario s global application-level and re3 est-specific events to perform its logic. 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;ation. Each mod le can also raise its own set of events that an application developer can handle. 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 @-,. An 9TTP handler is a component that implements the 29ttp9andler interface$ while an 9TTP handler factor% is a component that implements the 29ttp9andlerFactor% interface. ASP.NET provides a n mber of b ilt-in 9TTP handler implementations to handle file e)tensions s ch as .asp)$ .asm)$ and .ash). 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. ASP.NET does not impose arbitrar% limitations on the implementation of an 9TTP handler. A handler can se an% of the information it is handedBs ch as the re3 est @-,$ re3 est headers$ and posted dataBand it can generate an% form of o tp t$ either te)t al or binar%. /ne of the most commonl% sed 9TTP handlers is the page handler. Each .asp) page in a ?eb application is an 9TTP handler that handles incoming re3 ests for that partic lar page. 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.@2.!ontrol class corresponding to the declarative content present in the .asp) file$ and assembles them into a control tree. The control tree has its own life c%cle. 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&,. that forms the response content.

E+ten)ing ASP.NET

ASP.NET is an e)tensible ?eb application development platform. The e)tensibilit% of ASP.NET Ba feat re in and of itselfBres lts from the mod lar design and componenti;ed architect re of ASP.NET. As a component developer$ %o can create components that fit into different levels of ASP.NET to c stomi;e vario s aspects of the re3 est:response c%cle. These c stom components take the form of c stom controls or new 9TTP handlers and 9TTP mod les. 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 page framework. !ontrols form the b ilding blocks that are sed to create the ser interface of all ASP.NET ?eb applications. 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. The% contain the f nctionalit% to render themselves as part of the response generated b% the page when it is re3 ested. Server controls represent the most widel% sed components in an ASP.NET ?eb application. 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. ASP.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;e the processing of specific @-,s. Finall%$ 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. 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. ASP.NET$ along with the rest of the .NET Framework$ creates an e)citing new platform for both ?eb application developers and component developers. The .NET Framework provides a modern$ consistent$ and int itive class librar% as the fo ndation for b ilding components and component-based applications. F rthermore$ ASP.NET provides a powerf l ?eb application development framework that feat res well-designed architect re for e)tending and c stomi;ing its b ilt-in capabilities with c stom controls and components.

Server Control!

Server controls are components sed in ASP.NET pages to define the ser interface of a ?eb application. Server controls are the essential element of the ?eb Forms programming model. 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. At a high level$ server controls provide abstractions of an nderl%ing ?eb application and presentation technolog%. For e)ample$ the ?eb controls that ship as part of ASP.NET are abstractions of the 9T&, 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&, elementsD instead$ the% offer a more abstract object model for creating those elements. The ?eb Forms programming model greatl% simplifies application development for page developers and designers and is characteri;ed b% the server control feat res and capabilities that follow.

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%. For e)ample$ the ( tton ?eb control maps directl% to the Einp t t%peFAs bmitAG 9T&, tag and hides the inconsistencies of the t%pe attrib te of the Einp tG tag. 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&,C Einp t t%peFAte)tAG$ Einp t t%peFApasswordAG$ and Ete)tareaG. 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&,$ s ch as date selection and data binding.

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. 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. Server controls contain the logic to provide the best possible e)perience b% e)amining the capabilities of the re3 esting browser or device.

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. Server controls provide a rich server-side programming model. The% e)pose their f nctionalit% thro gh properties and methods. The% also provide an event-based programming model$ which allows page developers to implement application logic in response to ser interaction. The object model e)posed b% server controls is strongl% t%pedB nlike that of 69T&,$ which is loosel% t%ped. Not onl% does being strongl% t%ped lead to better server control performance$ it also red ces programming errors.

The% manage their state across postbacks and ro nd-trips. 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. Server controls se a feat re of the ASP.NET page framework known as view state to manage their state across individ al ?eb re3 ests. 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.

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

The% provide a compelling data-binding model. &ost ?eb applications are d%namic and feat re content based on a variet% of data so rces. 6ata-bo nd server controlsBthose server controls associated with a data so rceBgreatl% simplif% the creation of d%namic pages. ASP.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 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.

The% provide page developers with m ltiple mechanisms to c stomi;e their rendering. Server controls can provide st%le properties as a means to c stomi;e their formatting.

The% can also provide template properties for c stomi;ation of their content and la%o t. 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.

The% are config rable on a machine level +via the machine.config file. or on a ?eb application level +via the web.config file.. 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.

The% provide a rapid application development +-A6. ser e)perience in a vis al designtime environment s ch as &icrosoft 'is al St dio .NET. This enables page developers and designers to vis all% compose their pages and c stomi;e the appearance of the server controls in a ?4S2?4> fashion.

. ASP.NET Server Control %ierarch" The ASP.NET server control and classes are implemented in the S%stem.?eb.@2$ in the

S%[email protected]!ontrols$

S%stem.?eb.@2.?eb!ontrols

namespaces

S%stem.?eb assembl%. Fig re 8-* provides a high-level view of these namespaces.


Figure (-1. The ASP.NET !erver control hierarch"

All server controls derive directl% or indirectl% from the S%stem.?eb.@2.!ontrol class. The Page and @ser!ontrol classes represent .asp) and .asc) files$ respectivel%$ while the ,iteral!ontrol class represents a contig o s range of static content present in these files.

2n the S%[email protected]!ontrols namespace$ the 9tml!ontrol class provides a base class for all 9T&, controls. These controls represent plain 9T&, tags with a r natFAserverA attrib te and provide an 9T&,-centric object model. 2n the S%stem.?eb.@2.?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&, elements. These controls provide an object model that is strongl% t%ped$ simpler$ more int itive$ and more consistent than the 9T&, controls. 2n addition to the standard 9T&,-based controls$ ASP.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.?eb.@2.&obile!ontrols namespace. ASP.NET *eb Control! The controls in the S%stem.?eb.@2.?eb!ontrols namespace are referred to as the ?eb controls. &ost of the controls in this namespace derive directl% or indirectl% from the ?eb!ontrol base class. This s ite incl des controls that render as the basic 9T&, form elements$ s ch as b ttons and te)t bo)es sed for collecting ser inp t$ as well as other common 9T&, elements$ s ch as anchors$ images$ and tables. 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. 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. The class hierarch% presented in Fig re 8-8 shows the complete set of controls. *h" *rite Server Control!, Altho gh the standard ASP.NET server controls address the most common application scenarios$ the% are b% no means e)ha stive. 2n fact$ man% scenarios are not directl% addressed b% these controls. For e)ample$ the standard ASP.NET server controls do not address image maps$ chartgeneration capabilities$ or the creation of masked-edit data entr% forms. 9owever$ ASP.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. There are several reasons and scenarios for which %o might develop server controlsC

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. 2n this sense$ server controls can provide a toolbo) of common ser interface components and behaviors.

To create commercial component libraries similar to the Active= controls in &icrosoft 'is al (asic and the tag libraries in #ava Server Pages +#SP.. 2t is e)pected that the thirdpart% component ind str% will make the ASP.NET platform even more compelling$ j st as ?in78 Active= components pop lari;ed 'is al (asic. 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 .NET platform.

To provide a clean mechanism for dividing work across a large team. 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.

To enable 2nternet service providers +2SPs. that host ASP.NET ?eb sites to add s bstantial val e to their service b% offering a galler% of c stom server controls. 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.

Figure (-(. The ASP.NET *eb control!

Co)e -o)el
ASP.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. ASP.NET provides a new code model that enables both page developers and development tools to cleanl% and easil% separate code from presentation. This feat re is a significant improvement over Active Server Pages$ which re3 ired code to be interspersed with the static content of the

page. The ASP.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. This new code model is commonl% sed in one of two forms. The first form involves simpl% embedding code in a r natFAserverA script block within the .asp) file itself$ as %o saw in ,isting 8-*. This form is sometimes referred to as inline code. The second form involves implementing a class deriving from Page$ saving the code in a separate file$ and associating it with the .asp) file via the Page directive. This form is generall% referred to as code-behind. 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 Framework S6H. The second approachBimplementing code in a separate fileBis the model favored b% 'is al St dio .NET beca se it enables editing of the code sing the standard 'is al St dio .NET code editor. The two models are f nctionall% e3 ivalent and prod ce the same o tp t at r n time. ( t$ for o r p rposes$ what0s most important is that the c stom controls f nction identicall% in both models. The code model in ASP.NET is also lang age agnostic$ as is the programming model associated with an% other application b ilt sing the .NET Framework. 4o can se an% .NET programming lang ageBs ch as !5$ 'is al (asic .NET$ &icrosoft 'is al #5$ and &icrosoft #Script .NETBto implement the behavior and logic of the page. 4o specif% the code lang age of the page sing the ,ang age attrib te of the Page directive. 2f %o are sing the inline code model$ a single application might have pages implemented in m ltiple lang ages$ which work together seamlessl%. Each page can se onl% a single lang age. 9owever$ in the code-behind model sed b% 'is al St dio .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.

Page E+ecution -o)el


The page e)ec tion model in ASP.NET ties together all aspects of the page programming model. AASP.NET /verview$A provided the o tline for re3 est processing inside an ASP.NET ?eb application. This section takes a deeper look at how a page handles an incoming re3 est to generate an o tp t response.

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. The incoming re3 est is handled b% 2nternet 2nformation Services +22S.$ which hands the re3 est to the 9TTP r ntime in ASP.NET for processing. 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 .asp) files. 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.
Figure (-.. %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.NET cache associated with the .asp) file being re3 ested. ?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. A parse tree is similar to a control tree. ( t instead of containing controls$ a parse tree contains instances of objects known as control b ilders. !ontrol b ilders contain information abo t controls that is gathered d ring the parsing process. The parse tree is then converted into code in the lang age associated with the page via the ,ang age attrib te of the Page directive. The page handler factor% then invokes the appropriate compilerBfor e)ample$ the !5 compiler$ csc.e)eB to d%namicall% compile a class deriving from Page. The page handler factor% also places the newl% created page class into the ASP.NET cache and associates the cache entr% with a file dependenc%. The file dependenc% monitors changes made to the .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. The page handler factor% instantiates the d%namicall% compiled page class and allows the newl% created instance to process the incoming re3 est. An important aspect of the page programming model is that the pages e)ec te as f ll% compiled code. This provides significantl% better performance than interpreted code +s ch as code contained in Active Server Pages.. The page

e)ec tes the code generated from the parse tree$ which creates and processes the control tree contained in the original .asp) file. The control tree has its own life c%cle involving initiali;ation$ loading$ rendering$ and disposing. A!ontrol ,ife !%cle$ Events$ and Postback.A 2n its final processing phase$ the page renders itself to prod ce the response content. At the end of its processing c%cle$ the page is completel% disposed of. Th s$ the page framework does not maintain an% state or page instances across re3 ests. 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. This allows the handler factor% to skip all the work of opening$ reading$ and parsing the fileD generating codeD and invoking the compiler. This single-parse-and-compile aspect of the page e)ec tion model greatl% improves the performance and responsiveness of the ?eb application.

Viewing the Generated Code


4o can view the code for the class that the page parser generates to transform the .asp) file into a control tree b% t rning on page deb gging. 2n deb g mode$ the class file containing the generated code is preserved. 9owever$ this file is deepl% nested in a temporar% folder. The following steps provide a 3 ick alternative to viewing the generated so rce codeC *. Enable deb gging b% setting the 6eb g attrib te of the Page directive to tr e in the .asp) fileC
2. <%@ Page Debug="true" %>

7. 2ntrod ce a s%nta) error +s ch as an %o r page$ and save the file.

nbalanced parenthesis or a missing

semicolon statement terminator. in %o r code inside a server-side script block in

I. -e3 est the page in %o r ?eb browser. The server will ret rn an error message that contains vario s links at the bottom of the page. J. !lick the Show !omplete !ompilation So rce link. This displa%s the a togenerated code for %o r page.

-anage) Com$onent /verview


2f %o have developed !/& or Active= components$ %o will find managed components

significantl% easier to develop. &anaged components e)ec te on top of the common lang age r ntime +!,-. and a tomaticall% benefit from !,- feat res s ch as lang age interoperabilit%$ a tomatic memor% management$ and code access sec rit%. 2n addition$ managed components have a simpler deplo%ment model and are easier to version. (eca se 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.

A thoring a managed component is no different from writing a class in a programming lang age that targets the !,-. @nlike !/& components written in !""$ %o do not have to do an% additional work to convert a class into a component. ?hen developing managed components$ %o need to be aware of a few basic programming constr cts and follow a few simple g idelines. The following list contains a high-level s mmar% of the g idelines that %o sho ld follow when designing and implementing a component.

A thor %o r component in a programming lang age that targets the !,-$ s ch as !5 or &icrosoft 'is al (asic .NET. E)pose an object model that consists of properties$ methods$ and events. 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. 2n addition$ %o can describe %o r component0s members thro gh metadata attrib tes.

E)pose members that are compliant with the common lang age specification +!,S. to ens re that %o r component is sable from other programming lang ages that target the !,-. The !,S is a s bset of programming feat res that are common to all lang ages targeting the !,-.

&ake s re that %o r component conforms to .NET Framework design g idelines. These g idelines incl de naming conventions and implementation patterns. (% conforming to the design g idelines$ %o will ens re that %o r component interoperates seamlessl% with classes in the .NET Framework and provides a similar developer e)perience.

To get the f ll benefit of the designer architect re in the .NET Framework$ implement the 2!omponent interface or derive from a class s ch as S%stem.!omponent&odel.!omponent that implements this interface.

6eplo% %o r managed component as part of a class librar% in an assembl% +managed librar%..

Pro$ertie!

Properties encaps late the state of a component and are the essence of rapid application development +-A6.. The% allow sers to c stomi;e components in a design-time environment. 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. +Properties in #ava(eans are s pported indirectl% b% adherence to a naming convention for accessor methods.. 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. ?e0ll look at the propert% constr ct first. 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& ' '

'

The boldface elementsBget$ set$ and val eBare ke%words in the !5 propert% s%nta). The compiler transforms the code in the get and set blocks into methods that are called propert% accessors. 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. !5 does not have a ke%word named propert%. 9owever$ '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 .NET propert% s%nta) in boldfaceC
Private (tring %na$e Public Propert" #a$e)* +s (tring ,et -eturn %na$e .n ,et %na$e = value .n .n (et Propert" (et )/"0al value +s (tring*

2n contrast with !5$ val e in 'is al (asic .NET is not a ke%word in propert% s%nta). 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 b t are indirectl% accessed b% code that assigns or retrieves a propert%. The s%nta) for setting a propert% is the same as that for setting a field. ?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.#a$e = "1ohn"& //T"pe of #a$e is string.

The propert% constr ct allows %o to abstract the storage and implementation of a propert% from the clients of %o r component. 2n o r e)ample$ a private field holds the data for the Name propert%. ?hile the backing data for a propert% is often a private field$ the data co ld reside

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. A propert% can define both the get and set accessors or j st a single 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 !,- allows write-onl% properties$ the design g idelines for the .NET Framework disco rage them. 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%. A propert% can have an% access level allowed b% the r ntime$ incl ding p blic$ private$ protected$ or internal. 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. Altho gh the get and set accessors are not directl% accessible as methods$ the% are semanticall% e3 ivalent to methods. F rthermore$ the% can perform an% program logic$ be overridden$ and throw e)ceptions. 2n the ne)t two sections$ we0ll show %o how to override a propert% and perform val e checking in a propert% accessor.
0irtual Pro$ertie!

4o generall% provide virt al +overridable. 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. 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 .NETBin the class in which the propert% is first declared. 9ere0s a !5 e)ampleC
public class +n"2nteger { private int %nu$ber& public virtual int #u$ber { get { return %nu$ber& '

set { %nu$ber = value& ' '

'

9ere0s a '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 .n ,et %nu$ber = value .n .n (et Propert" (et )/"0al value +s 2nteger*

.n

3lass 5+n"2nteger

/verriding a propert% is similar to overriding a method. 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. 9ere0s a !5 e)ampleC
public class #on#egative2nteger 6 +n"2nteger { public overri e int #u$ber { get { return base.#u$ber& ' set { if )value < 7* { thro! ne! +rgu$ent4ut4f-ange.8ception) "The nu$ber cannot be less than 7."*&

' base.#u$ber = value& ' '

'

And here0s a 'is al (asic .NET e)ampleC


Public 3lass #on#egative2nteger 2nherits +n"2nteger Public 4verri es Propert" #u$ber)* +s 2nteger ,et -eturn 9"/ase.#u$ber .n ,et 2f value < 7 Then Thro! #e! +rgu$ent4ut4f-ange.8ception) % "The nu$ber cannot be less than 7."* .n .n .n (et 2f 9"/ase.#u$ber = value Propert" (et )/"0al value +s 2nteger*

.n

3lass 5Positive2nteger

2f both propert% accessors are defined in the base class$ %o m st override both accessors when overriding a propert%. 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. 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. A virt al propert% cannot be sealed +made nonoverridable. in a derived class. 'irt al properties also have implications for

versioning. /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.
Pro$ertie! an) 0ali)ation

Propert% accessors can perform error checking +validation. in addition to getting or setting a propert%. 2f a propert% val e is not acceptable$ an accessor sho ld throw an e)ception. 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. A well-designed component sho ld perform arg ment validation in its propert% setters. ?hen a setter throws an e)ception$ it flags an erroneo s propert% assignment as soon as it is made. This helps identif% the location in ser code where the error occ rred. 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 .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. 4o sho ld se the most appropriate e)ception t%pe$ along with meaningf l error messages. Naming 1ui)eline! for Pro$ertie! To ens re that %o r naming scheme for properties conforms to that of the .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;e. @se Pascal casing. 2n other words$ capitali;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,evel and 'iewState.

A)vantage! of Pro$ertie!

2t is standard object-oriented practice to encaps late %o r component0s data. 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. Properties offer man% benefits over fieldsC

6ata hidingThe storage and implementation of properties$ invisible to the ser.

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. This also enables better error tracking. 4o cannot implement validation when sing a field.

/verridingProperties can be overriden$ th s allowing a derived class to alter the propert% implementation of the base class.

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

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.

6ata bindingThe data-binding architect re in ASP.NET and ?indows Forms s pports binding to properties b t not to fields.

2n general$ beca se of j st-in-time +#2T. optimi;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.

2n this section$ we covered general concepts related to the propert% constr ct in the .NET Framework. 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. ?e0ll also show %o how to implement different t%pes of properties$ s ch as primitive$ reference$ and collection properties.

-etho)!
Not m ch is significantl% different between methods in the managed world and methods in the nmanaged world. 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. 9owever$ in some sit ations$ it is not appropriate to implement properties. (eca se propert% accessors are e3 ivalent to methods$ %o sho ld instead implement methods in those sit ations. 9ere are some e)amplesC

2f a propert% accessor has observable side effects$ implement a method instead of a propert%. 2f the implementation of a propert% is considerabl% more e)pensive than that of a field$ implement a method instead. ?hen %o e)pose a propert%$ %o s ggest to sers that making fre3 ent calls to it is acceptable. ?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.

2f some properties re3 ire a ser to set them in a predefined order$ implement those properties as methods. 2n general$ %o sho ld design %o r components so that properties can be set in an% order.

2f %o need a write-onl% propert%$ implement a method instead.

E)amples of these cases and additional ones appear in the white paper A.NET Framework 6esign > idelinesB?riting !lass ,ibraries for the .NET Framework$A on &S6N. Naming 1ui)eline! for -etho)! an) -etho) Parameter! To ens re that %o r naming scheme for methods conforms to that of the .NET Framework$ follow these g idelinesC

@se method names that consist of verbs or verb phrases that indicate the task accomplishedBfor e)ample$ Add$ 6ispose$ and 'erif%. @se Pascal casing for method namesBfor e)ample$ !reate!hild!ontrols and Save'iewState.

4o sho ld also follow the .NET Framework naming g idelines for parameter names. 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%. These are the g idelinesC

@se descriptive parameter names. 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. 6escriptive parameter names provide val able information to the ser.

@se camel casing for parameter names. This means sing lowercase for the first word in the parameter name and capitali;ing the first letter of each s bse3 ent word in the name Bfor e)ample$ level$ minim m,evel$ and ma)9its.

@se a name based on the parameter meaning rather than its t%pe. 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.

6o not prefi) parameter names with 9 ngarian notation.

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 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. The class that raises the event +sends the notification. is called the event so rce or sender$ and the class that receives the event is called the event sink or receiver. Event-based architect re ses the p blish-s bscribe model in which the so rce +or p blisher. of an event allows its sers +or s bscribers. to specif% logic that is e)ec ted when the event occ rs.

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. Event-based programming th s re3 ires an intermediar% mechanism that connects the so rce and the receiver. 2n programming terms$ event architect re needs some sort of callback mechanism. 2n !""$ callbacks are implemented sing f nction pointersD in #ava$ the% are implemented sing interfaces. The .NET Framework provides a new constr ctBcalled a delegateBto provide the f nctionalit% of a callback. 6elegates combine the best of the earlier paradigms. 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. And that is not all. 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.. ,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 .NET Framework. 3elegate! A delegate in the .NET Framework is a class that can hold a reference to a static or instance method of a class. The signat re of the method m st match the signat re of the delegate. To nderstand this$ let0s begin with a declaration of a delegate class. The following line of code contains the declaration of a delegate named &%6elegate that can refer +bind. 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 declaration is similar to a method declaration$ with the addition of the delegate ke%word. 9owever$ a delegate is not a methodBit is a class with its own methods and other members. 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.& lticast6elegate. For e)ample$ sing o r earlier declaration$ the compiler generates a &%6elegate class that derives from S%stem.& lticast6elegate. 2f %o want to see the compiler-generated class$ %o can se the 2,6AS& disassembler tool that ships with the .NET Framework S6H. The tool is briefl% described in the 2ntrod ction of this book.

S%stem.& lticast6elegate is the base class for delegates in the .NET Framework. & lticast6elegate derives from the S%stem.6elegate class. 6elegate t%pes in the .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. & lticast6elegate also contains a linked list of delegatesBcalled the invocation listBfrom which it can add or and remove delegates. ?hen an instance of & lticast6elegate is invoked$ it se3 entiall% invokes the delegates in its invocation list. 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. 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. 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. ,et0s look at the code first and then disc ss what the sample does. The delegate-related code is boldface in ,isting 7-*C
Li!ting 4-1 A )elegate u!e) a! a callback using ("ste$& na$espace 9(Press.Delegate(a$ple { public elegate voi Print3allbac:)int nu$ber*&

public class Printer { private Print3allbac: %print& public Print3allbac: Print3allbac: { get { return %print& ' set {

%print = value& ' ' ' public class Driver { private voi Print2nteger)int nu$ber* { 3onsole.;rite<ine) "=ro$ Print2nteger6 The nu$ber is {7'."> nu$ber*& ' static voi Driver 9ain)string?@ args* { river = ne! Driver)*&

Printer printer = ne! Printer)*& printer.Print3allbac: = ne! Print3allbac:) river.Print2nteger*& printer.Print3allbac:)A7*& printer.Print3allbac:)A77*& 3onsole.;rite<ine)"Press .nter to e8it..."*& 3onsole.-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. =ro$ Print2nteger6 The nu$ber is A77. Press .nter to e8it...

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. The Printer class has a delegate propert%$ Print!allback$ of t%pe Print!allback. The 6river class defines a Print2nteger method that has the same signat re as Print!allback. 2n its &ain method$ the 6river class binds the Print!allback delegate of its Printer instance to its Print2nteger method. Now$ whenever the Print!allback delegate is invoked$ the method it binds toBPrint2ntegerBis e)ec ted.

?e wo ld like to make one minor point abo t the delegate constr ctor. 2f %o look at the constr ctor of the S%stem.& lticast6elegate class$ %o will see that it takes two parameters. ( t we have s pplied onl% one parameter in o r delegate constr ctorC new Print!allback+driver.Print2nteger.. The reason for this difference is that the other parameter is implicit and points to the object that contains the callback method. The !5 and 'is al (asic .NET compilers se the implicit parameter and the s pplied parameter to create the twoparameter constr ctor the r ntime needs. 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. 2f the method %o are binding to is a static method +instead of an instance method.$ se the class name instead of the class instance name in the constr ctor. For e)ample$ if the Print2nteger method were a static method$ %o wo ld instantiate the delegate as new Print!allback+6river.Print2nteger.. That completes o r 3 ick to r of delegates. 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. Event 3elegate! Now that %o have seen how delegates work$ it is eas% to nderstand how the% are sed in event programming. 2n essence$ a class that wants to raise an event +send notifications. has a delegate member. 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 receiverBor some other classBthen binds the event handler to a delegate and adds that delegate to the invocation list of the event so rce. To raise an event$ the event so rce invokes its delegate$ which in t rn invokes the delegates in its invocation list. Those delegates in t rn invoke the handlers the% are bo nd to$ th s completing the event se3 ence. The .NET Framework event model is elegant$ powerf l$ and eas% to implement. ?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. Event delegates in the .NET Framework follow a certain convention for their signat re and their naming scheme. This convention is relied pon b% vis al design tools and provides a consistent

pattern for client code. To nderstand the convention$ let0s look at a commonl% accessed event delegate in the .NET Framework$ S%stem.Event9andlerC
public elegate voi .ventBan ler)obCect sen er> .vent+rgs e*&

The signat re of an event delegate in the .NET Framework is analogo s to that of the Event9andler delegate. These are the specifics of the signat re conventionC

The ret rn t%pe of an event delegate is void. An event delegate takes two arg ments. The first arg mentBof t%pe /bjectBrepresents the sender of the event. The second arg ment represents data for the event and is an instance of a class that derives from S%stem.EventArgs.

To interoperate with the .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. 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. !lasses that hold event data go hand in hand with event delegates. The base class EventArgs does not hold an% event data. 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.?eb.@2.?eb!ontrols.( tton server control. An e)ample of a class that holds event data is S%[email protected]!lickEventArgs$ which holds ) and % coordinates for the !lick event of the S%stem.?eb.@2.?eb!ontrols.2mage( tton server control. 2ts associated event delegate is S%[email protected]!lickEvent9andler. &an% namespaces in the .NET Framework contain event data classes and event delegates. 4o sho ld follow the .NET Framework convention for naming 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. Event delegates are named event handlers beca se the% bind to methods that handle events.
*iring Event!

For completeness$ we0ll briefl% describe the s%nta) for attaching an event handler to an event. +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.NET pages or in other .NET applications.. The process of associating an event handler with an event +adding a delegate to the invocation list. is called event wiring$ while that of removing an event handler from an event +removing a delegate from the invocation list. is called event nwiring. 2n !5$ the s%nta) for wiring and nwiring an event handler to an event looks like thisC
button.3lic: D= ne! .ventBan ler)this./utton%3lic:e *& button.3lic: E= ne! .ventBan ler)this./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. 2n 'is al (asic .NET$ event wiring and nwiring s%nta) looks like thisC
+ Ban ler button.3lic:> + ress4f 9e./utton%3lic:e ress4f 9e./utton%3lic:e

-e$oveBan ler button.3lic:> +

The declarative s%nta) of ASP.NET pages hides m ch of the event architect re from the page developer. 9owever$ the nderl%ing event mechanism in ASP.NET is no different from the rest of the .NET Framework.

ai!ing an Event 2n this section$ we0ll walk %o thro gh the .NET Framework design pattern for raising an event from %o r class. 2n the ne)t section$ we0ll show a complete sample that demonstrates these steps. The sample files contain the sample in !5 and in 'is al (asic .NET.

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. The act al implementation of an event is relativel% straightforwardBthe major effort is in nderstanding how the pieces fit together. 9ere0s a high-level overview of the steps that %o have to perform. ?e0ll elaborate on these steps in the ne)t section. *. 2f %o r class does not have an% associated event data$ se the EventArgs class for event data. /r %o can se another pree)isting event data class if it matches %o r event. 2f a s itable event data class does not e)ist$ define a class to hold event data. This class m st derive from S%stem.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. The following code fragment declares an event data classC
2. public class <o!3harge.vent+rgs 6 .vent+rgs {...'

7. 2f %o r event does not have associated data and %o

sed EventArgs in step *$ se

S%stem.Event9andler as %o r event delegate. /r %o can se another pree)isting delegate if it matches %o r event. 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 *. (% convention$ the name of the event delegate is the name of the event appended b% Event9andlerBs ch as Ad!reatedEvent9andler$ !ommandEvent9andler$ or &onth!hangedEvent9andler. The following code defines an event delegateC
F. public G. elegate voi <o!3harge.ventBan ler)obCect sen er>

<o!3harge.vent+rgs e*&

L. 2n %o r class$ define an event member sing the event ke%word. >ive the event member the name of %o r event. The t%pe of this member is the event delegate %o 9ere0s an e)ampleC
H. public event <o!3harge.ventBan ler <o!3harge&

sed in step 8.

The event member holds the list of delegates that s bscribe to the event. ?hen this member is invoked$ it dispatches the event b% invoking the delegates.

M. 2n %o r class$ define a virt al +overridable. method that invokes the event delegateBafter checking whether an% event listeners e)ist. The name of this method contains the event name prefi)ed b% /n. 9ere0s an e)ampleC
I. A7. AA. A2. AK. ' ' protecte virtual voi 4n<o!3harge)<o!3harge.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. 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 .NET Framework or third part% class librar%.$ while the ne)t two steps are implemented in %o r class. 9ere0s the skeleton of a class that implements the ,ow!harge event we j st describedC
public class /atter" {

public event <o!3harge.ventBan ler <o!3harge& protecte virtual voi 4n<o!3harge)<o!3harge.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. ?hen the !5 or 'is al (asic .NET compiler sees a member marked with the event ke%word$ it a tomaticall% generates the three members shown in the following code. +4o can see these members b% sing the 2,6AS& tool described in the 2ntrod ction of this book..

A private field of the same t%pe as the event delegate$ s ch as the followingC
private <o!3harge.ventBan ler <o!3harge = null&

A method that adds delegates to the event delegate$ s ch as the followingC

// The access level of this $etho // the event $e$ber. public voi +

is the sa$e as that of

%<o!3harge)<o!3harge.ventBan ler han ler* {

<o!3harge = )<o!3harge.ventBan ler*Delegate.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. public voi -e$ove%<o!3harge)<o!3harge.ventBan ler han ler* { is the sa$e as that of

<o!3harge = )<o!3harge.ventBan ler*Delegate.-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. The access level of the compiler-generated methods is the same as the access level of the event member. 9owever$ even when the compilergenerated methods are p blic$ the% are not directl% accessible from client code in !5 and 'is al (asic .NET. 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 .NET$ as we showed earlier. ?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. 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. For s ch sit ations$ the .NET Framework provides a tilit% class$ S%stem.!omponent&odel.Event9andler,ist$ which provides a more optimal storage mechanism for event delegates.

3e!ignable Com$onent!

The .NET Framework provides special s pport for components that are sed in a vis al designer. 2n this section$ we0ll provide a high-level overview of designable components in the .NET Framework. 2n the .NET Framework$ a designable component is a class that directl% or indirectl% derives from S%stem.!omponent&odel.!omponent or implements the S%stem.!omponent&odel.2!omponent interface. 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 .NET. 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. This kind of designer s pport is not available to a class that does not derive from !omponent or implement the 2!omponent interface. 2f %o tr% to add a class that does not implement 2!omponent$ the ser interface to c stomi;e the toolbo) will inform %o that %o r assembl% does not contain components that it can add to the toolbo). Now let0s e)amine how designable components control e)ternal reso rces. The 2!omponent interface derives from the S%stem.26isposable interface$ which contains the 6ispose method that gives a component a chance to free e)ternal reso rces or references that it holds. Altho gh managed objects are a tomaticall% garbage collected$ 26isposable allows a class to perform clean p in a more deterministic manner. 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. ?e0ll describe how to implement the 6ispose method when we look at e)amples of components that need to free nmanaged reso rces. Control!

2n the .NET Framework$ a control is a designable component that renders a ser interface or facilitates the rendering of vis al elements. The .NET Framework defines two base control classesC

The base class for ASP.NET server controls is S%stem.?eb.@2.!ontrol. 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.

The

base

class

for

client-side This

?indows class

Forms

controls

is from

S%stem.?indows.Forms.!ontrol.

derives

S%stem.!omponent&odel.!omponent$ which implements the 2!omponent interface. S%stem.?indows.Forms.!ontrol is capable of drawing sing >62"..

You might also like