Anda di halaman 1dari 48

WEB APPLICATION IN ASP .

NET
ASP.NET coding modules
ASP.NET 3.5 provides two paths for structuring the code of your ASP.NET pages. The first path utilizesthe code-inline model. This model should be familiar to classic ASP 2.0/3.0 developers because all thecode is contained within a single .aspx page. The second path uses ASP.NETs code-behind model,which allows for code separation of the pages business logic from its presentation logic. In this model,the presentation logic for the page is stored in an .aspx page, whereas the logic piece is stored in aseparate class file: .aspx.vb or .aspx.cs. It is considered best practice to use the code-behind modelas it provides a clean model in separation of pure UI elements from code that manipulates these elements.It is also seen as a better means in maintaining code. In this code-behind page from ASP.NET 1.0/1.1, you can see that a lot of the code that developers neverhave to deal with is hidden in the #Region section of the page. Because ASP.NET 3.5 is built on topof .NET 3.5, which in turn is utilizing the core .NET 2.0 Framework, it can take advantage of the .NETFramework capability of partial classes. Partial classes enable you to separate your classes into multipleclass files, which are then combined into a single class when the application is compiled. BecauseASP.NET 3.5 combines all this page code for you behind the scenes when the application is compiled,the code-behind files you work with in ASP.NET 3.5 are simpler in appearance and the model is easierto use. You are presented with only the pieces of the class that you need.

Inline Coding :
With the .NET Framework 1.0/1.1, developers went out of their way (and outside Visual Studio .NET) to build their ASP.NET pages inline and avoid the code-behind model that was so heavily promotedby Microsoft and others. Visual Studio 2008 (as well as Visual Web Developer 2008 Express Edition)allows you to build your pages easily using this coding style. To build an ASP.NET page inline instead ofusing the code-behind model, you simply select the page type from the Add New Item dialog and makesure that the Place Code in Separate File check box is unchecked. In fact, many page types have options for both inline and code-behind styles. The following tableshows your inline options when selecting files from this dialog.

File Options Using Inline Coding


Web Form AJAX Web Form Master Page AJAX Master Page Web User Control Web Service

File Created
.aspx file .aspx file .master file .master file .ascx file .asmx file

<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = "Hello " + Textbox1.Text; } </script> From this example, you can see that all the business logic is encapsulated in between <script>tags. Thenice feature of the inline model is that the business logic and the presentation logic are contained withinthe same file. Some developers find that having everything in a single viewable instance makes workingwith the ASP.NET page easier. Another great thing is that Visual Studio 2008 provides IntelliSense whenworking with the inline coding model and ASP.NET 3.5. Before Visual Studio 2005, this capability didnot exist. Visual Studio .NET 2002/2003 forced you to use the code-behind model and, even if you riggedit so your pages were using the inline model, you lost all IntelliSense capabilities.

Code-Behind Model
The other option for constructing your ASP.NET 3.5 pages is to build your files using the code-behindmodel. It is important to note that the more preferred method is the code-behind model rather than the inlinemodel. This method employs the proper segmentation between presentation and business logic in manycases. To create a new page in your ASP.NET solution that uses the code-behind model, select the page typeyou want from the New File dialog. The following table shows you the options for pages that use the code-behind model.

File Options Using Code-Behind


Web Form AJAX Web Form Master Page AJAX Master Page Web User Control Web Service

File Created
.aspx file .aspx.vb or .aspx.cs file .aspx file .aspx.vb or .aspx.cs file .master.vb or .master.cs file .master.vb or .master.cs file .ascx.vb or .ascx.cs file .asmx file .vb or .cs file

Default.aspx <%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title> Simple Page </title>

</head> <body> <form id="form1" runat="server"> What is your name?<br /> <asp:Textbox ID="Textbox1" Runat="server"></asp:Textbox><br /> <asp:Button ID="Button1" Runat="server" Text="Submit" OnClick="Button1_Click" /> <p><asp:Label ID="Label1" Runat="server"></asp:Label></p> </form> </body> </html> Default.aspx.cs using System; using System.Data; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Hello " + Textbox1.Text; } } The .aspx page using this ASP.NET 3.5 code-behind model has some attributes in the Page directivethat you should pay attention to when working in this mode. The first is the CodeFile attribute. This isan attribute in the Page directive and is meant to point to the code-behind page that is used with thispresentation page. The secondattribute needed is the Inherits attribute. This attribute was available in previous versions of ASP.NET,but was little used before ASP.NET 2.0. This attribute specifies the name of the class that is bound tothe page when the page is compiled. The directives are simple enough in ASP.NET 3.5. The code-behind page is rather simple in appearance because of the partial class capabilities that .NET3.5 provides. You can see that the class created in the code-behind file uses partial classes. This enables you tosimply place the methods that you need in your page class. In this case, you have a button-click eventand nothing else. Partial classes enable you to declare a class in more than one physical file. When the classgets compiled, one class is generated from all the partial classes. Any members of onepartial classincluding any private fields, methods, and propertiesare accessible to anyother partial classes of the same class. This makes sense because partial classes arecombined eventually to create one final class.The advantage of using partial classes is that you dont need to worry about declaring acontrol in both the presentation page and code-behind file. Anything that you declare inthe presentation page is available automatically in the code-behind file, and anything youdeclare in the code-behind file is available automatically in the presentation page.

Building code-behind pagesreally doesnt promote code reuse. A better way to reuse application logic across multiplepages is to build separate component libraries.

ASP.NET page directives


You can control the behavior ofyour ASP.NET pages by using these directives. Here is an example of the Page directive: <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"Inherits="_Default" %> Eleven directives are at your disposal in your ASP.NET pages or user controls. You use these directivesin your applications whether the page uses the code-behind model or the inline coding model.Basically, these directives are commands that the compiler uses when the page is compiled. Directivesare simple to incorporate into your pages. A directive is written in the following format: <%@ [Directive] [Attribute=Value] %> From this, you can see that a directive is opened with a <%@ and closed with a %>. It is best to put thesedirectives at the top of your pages or controls because this is traditionally where developers expect to seethem (although the page still compiles if the directives are located at a different place). Of course, youcan also add more than a single attribute to your directive statements, as shown in the following: <%@ [Directive] [Attribute=Value] [Attribute=Value] %> The following table describes the directives at your disposal in ASP.NET 3.5. Directive Description Links an assembly to the Page or user control for which it is associated.The @Assembly directive attaches assemblies, the building blocks of .NET applications, to an ASP.NETpage or user control as it compiles, thereby making all the assemblys classes and interfaces available tothe page. This directive supports two attributes: Name and Src Name: Enables you to specify the name of an assembly used to attach to the page files. The name of the assembly should include the file name only, not the files extension. Src: Enables you to specify the source of the assembly file to use in compilation. Page directive meant for use with user controls (.ascx).The @Control directive allows you to define the properties to be inherited bythe user control. These values are assigned to the user control as the page is parsed and compiled.This directive supports attributes such as: AutoEventWireup, ClassName, CodeFileBaseClass,CodeFile, CompilerOptions, CompileWith, Debug, Description, EnableTheming,

Assembly

Control

Implements

Import

Master

MasterType

OutputCache

EnableViewState, Explicit, Inherits, Language, LinePragmas, Src, Strict, WarningLevel. Implements a specified .NET Framework interface.This directive supports only a single attribute: Interface. The Interface attribute directly specifies the .NET Framework interface. When the ASP.NET page or user control implements an interface, it has direct access to all its events, methods, and properties. Imports specified namespaces into the Page or user control.By importing, all the classes and interfaces of the namespace are made available to the page or user control. This directive supports only a single attribute: Namespace. The Namespace attribute takes a String value that specifies the namespace to be imported. The @Importdirective cannot contain more than one attribute/value pair. Enables you to specify master pagespecific attributes and values to usewhen the page parses or compiles. This directive can be used only withmaster pages (.master).In using the @Master directive, you specify properties of the templated pagethat you will be using in conjunction with any number of content pages on your site. Any content pages(built using the @Page directive) can then inherit from the master page all the master content (defined inthe master page using the @Master directive).This directive supports attributes such as: AutoEventWireup, ClassName, CodeFileBaseClass, CodeFile, CompilationMode, CompilerOptions, CompileWith, Debug, Description, EnableTheming, EnableViewState, Explicit, Inherits, Language, LinePragmas, MasterPageFile, Src, Strict, WarningLevel. Associates a class name to a Page in order to get at strongly typedreferences or members contained within the specified master page.This directive supports two attributes:TypeName and VirtualPath TypeName: Sets the name of the derived class from which to get strongly typed references or members. VirtualPath: Sets the location of the page from which these strongly typed references and members will be retrieved. Controls the output caching policies of a Page or user control.The supported attributes by this directive are: CacheProfile Allows for a central way to manage an applications cache profile. Use theCacheProfile attribute to specify the name of the cache profile detailed in the web.config. Duration The duration of time in seconds that the ASP.NET page or user control is cached. Location Location enumeration value. The default is Any. This is valid for .aspx pages only and

Page

does not work with user controls (.ascx). Other possible values include Client, Downstream, None, Server, and ServerAndClient. NoStore Specifies whether to send a no-store header with the page. Shared Specifies whether a user controls output can be shared across multiple pages. This attribute takes a Boolean value and the default setting is false. SqlDependency Enables a particular page to use SQL Server cache invalidation. VaryByControl Semicolon-separated list of strings used to vary the output cache of a user control. VaryByCustom String specifying the custom output caching requirements. VaryByHeader Semicolon-separated list of HTTP headers used to vary the output cache. VaryByParam Semicolon-separated list of strings used to vary the output cache.

Enables you to specify page specific attributes and values to use whenthe page parses or compiles. This directive can be used only withASP.NET pages (.aspx). Enables an ASP.NET page to work with a postback from another pagein the application.The @PreviousPageType directive is a new directive that works with the new cross-page posting capabilitythat ASP.NET 3.5 provides. This simple directive contains only two possible PreviousPageType attributes: TypeName andVirtualPath: TypeName: Sets the name of the derived class from which the postback will occur. VirtualPath: Sets the location of the posting page from which the postback will occur. Links a Page or user control to the current Page or user control.The @Reference directive declares that another ASP.NET page or user control should be compiled alongwith the active page or control. This directive Reference supports just a single attribute: VirtualPath: Sets the location of the page or user control from which the active page will be referenced. Associates aliases with namespaces and class names for notation in custom server control syntax.The @Register directive supports five attributes: Assembly The assembly you are associating with the TagPrefix. Namespace The namespace to relate with TagPrefix. Src The location of the user control. TagName The alias to relate to the class name. TagPrefix The alias to relate to the namespace.

Register

@Page Directive :
This is the most frequently used directive of the bunch. The attributes available through the @Page directive are: AspCompat Permits the page to be executed on a single-threaded apartment threadwhen given a value of True. The default setting for this attribute is False. Async Specifies whether the ASP.NET page is processed synchronously orasynchronously. AsyncTimeout Specifies the amount of time in seconds to wait for the asynchronous taskto complete. The default setting is 45 seconds. This is a new attribute ofASP.NET 3.5. AutoEventWireup Specifies whether the page events are autowired when set to True. Thedefault setting for this attribute is True. Buffer Enables HTTP response buffering when set to True. The default setting forthis attribute is True. ClassName Specifies the name of the class that is bound to the page when the page iscompiled. ClientTarget Specifies the target user agent a control should render content for. Thisattribute needs to be tied to an alias defined in the <clientTarget>section of the web.config. CodeFile References the code-behind file with which the page is associated. CodeFileBaseClass Specifies the type name of the base class to use with the code-behind class,which is used by the CodeFile attribute. CodePage Indicates the code page value for the response. CompilationMode Specifies whether ASP.NET should compile the page or not. The availableoptions include Always (the default), Auto, or Never. A setting of Automeans that if possible, ASP.NET will not compile the page. CompilerOptions Compiler string that indicates compilation options for thepage. CompileWith Takes a String value that points to the code-behind file used. ContentType Defines the HTTP content type of the response as a standard MIME type. Culture Specifies the culture setting of the page. ASP.NET 3.5 includes the capability to give the Culture attribute a value of Auto toenable automatic detection of the culture required. Debug Compiles the page with debug symbols in place when set to True. Description Provides a text description of the page. The ASP.NET parser ignores this attribute and its assigned value. EnableEventValidation Specifies whether to enable validation of events in postbackand callback scenarios. The default setting of True means thatevent will be validated. EnableSessionState Session state for the page is enabled when set to True. Thedefault setting is True. EnableTheming Page is enabled to use theming when set to True. The defaultsetting for this attribute is True. EnableViewState View state is maintained across the page when set to True. Thedefault value is True.

EnableViewStateMac Page runs a machine-authentication check on the pages viewstate when the page is posted back from the user when set to True. The default value is False. ErrorPage Specifies a URL to post to for all unhandled page exceptions. Explicit Visual Basic Explicit option is enabled when set to True. The default setting is False. Language Defines the language being used for any inline rendering and script blocks. LCID Defines the locale identifier for the Web Forms page. LinePragmas Boolean value that specifies whether line pragmas are used with the resulting assembly. MasterPageFile Takes a String value that points to the location of the master page used with the page. This attribute is used with content pages. MaintainScrollPositionOnPostbackTakes a Boolean value, which indicates whether the pageshould be positioned exactly in the same scroll position or ifthe page should be regenerated in the uppermost position forwhen the page is posted back to itself. ResponseEncoding Specifies the response encoding of the page content. SmartNavigation Specifies whether to activate the ASP.NET Smart Navigationfeature for richer browsers. This returns the postback to the current position on the page. The default value is False. Src Points to the source file of the class used for the code behind of the page being rendered. Strict Compiles the page using the Visual Basic Strict mode when set to True. The default setting is False. StylesheetTheme Applies the specified theme to the page using the ASP.NET 3.5themes feature. The difference between the StylesheetTheme andTheme attributes is that StylesheetTheme will not override preexisting style settings in the controls, whereas Theme willremove these settings. Theme Applies the specified theme to the page using the ASP.NET 3.5 themes feature. Title Applies a pages title. This is an attribute mainly meant for contentpages that must apply a page title other than what is specified in the master page. Trace Page tracing is enabled when set to True. The default setting is False. TraceMode Specifies how the trace messages are displayed when tracing is enabled. The settings for this attribute include SortByTime or SortByCategory. The default setting is SortByTime. Transaction Specifies whether transactions are supported on the page. Thesettings for this attribute are Disabled, NotSupported, Supported, Required, and RequiresNew. The default setting is Disabled. UICulture The value of the UICulture attribute specifies what UI Culture touse for the ASP.NET page. ASP.NET 3.5 includes the capability to give the UICulture attribute a value of Auto to enable automaticdetection of the UICulture. ValidateRequest When this attribute is set to True, the form input values arechecked against a list of potentially dangerous values. This helpsprotect your Web application from harmful attacks such as JavaScript attacks. The default value is True. ViewStateEncryptionMode Specifies how the ViewState is encrypted on the page. Theoptions include Auto, Always, and Never. The default is Auto. WarningLevel Specifies the compiler warning level at which to stop compilationof the page. Possible values are 0 through 4.

Page events :
ASP.NET developers consistently work with various events in their server-side code. Many of the eventsthat they work with pertain to specific server controls. For instance, if you want to initiate some actionwhen the end user clicks a button on your Web page, you create a button-click event in your server-side code : Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Label1.Text = TextBox1.Text End Sub In addition to the server controls, developers also want to initiate actions at specific moments when theASP.NET page is being either created or destroyed. The ASP.NET page itself has always had a numberof events for these instances. The following list shows you all the page events you could use in ASP.NET1.0/1.1: AbortTransaction CommitTransaction DataBinding Disposed Error Init Load PreRender Unload Besides the page events just shown, ASP.NET 3.5 has the following events: InitComplete: Indicates the initialization of the page is completed. LoadComplete: Indicates the page has been completely loaded into memory. PreInit: Indicates the moment immediately before a page is initialized. PreLoad: Indicates the moment before a page has been loaded into memory. PreRenderComplete: Indicates the moment directly before a page has been rendered in thebrowser. If you create an ASP.NET 3.5 page and turn on tracing, you can see the order in which the main pageevents are initiated. They are fired in the following order: 1. PreInit 2. Init 3. InitComplete 4. PreLoad 5. Load 6. LoadComplete 7. PreRender 8. PreRenderComplete 9. Unload

With the addition of these choices, you can now work with the page and the controls on the page at manydifferent points in the pagecompilation process.

Page Life Cycle :


A series of processing steps takes place during this page life cycle. Following tasks are performed: Initialization Instantiation of controls Restoration & Maintainance of State Running Event Handlers Rendering of data to the browser

The life cycle may be broken down into Stages and Events. The stagesreflect the broad spectrum of tasks performed. The following stages take place: 1) Page Request - This is the first stage, before the page life cycle starts. Whenever a page is requested, ASP.NET detects whether the page is to be requested, parsed and compiled or whether the page can be cached from the system. 2) Start - In this stage, properties such as Request and Response are set. Its also determined at this stage whether the request is a new request or old, and thus it sets the IsPostBack property in the Start stage of the page life cycle. 3) Page Initialization - Each control of the page is assigned a unique identification ID. If there are themes, they are applied. Note that during the Page Initialization stage, neither postback data is loaded, nor any viewstate data is retrieved. 4) Load - If current request is a postback, then control values are retrieved from their viewstate. 5) Validation - The validate method of the validation controls is invoked. This sets the IsValid property of the validation control. 6) PostBack Event Handling - Event handlers are invoked, in case the request is a postback. 7) Rendering - Viewstate for the page is saved. Then render method for each control is called. A textwriter writes the output of the rendering stage to the output stream of the page's Response property. 8) Unload - This is the last stage in the page life cycle stages. It is invoked when the page is completely rendered. Page properties like Respone and Request are unloaded. Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.

PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To set master pages dynamically. Gets and Sets profile propety values. Init - Raised after all controls are initialized, and skin properties are set. InitComplete - This event may be used, when we need to be sure that all initialization tasks are complete. PreLoad - If processing on a control or a page is required before the Load event. Load - invokes the OnLoad event on the page. The same is done for each child control on the page. May set properties of controls, create database connections. Control Events - These are the control specific events, such as button clicks, listbox item selects etc. LoadComplete - To execute tasks that require that the complete page has been loaded. PreRender - Some methods are called before the PreRenderEvent takes place, like EnsureChildControls, data bound controls that have a dataSourceId set also call the DataBind method. Each control of the page has a PreRender event. Developers may use the prerender event to make final changes to the controls before it is rendered to the page. SaveStateComplete - ViewState is saved before this event occurs. However, if any changes to the viewstate of a control is made, then this is the event to be used. It cannot be used to make changes to other properties of a control. Render - This is a stage, not an event. The page object invokes this stage on each control of the page. This actually means that the ASP.NET server control's HTML markup is sent to the browser. Unload - This event occurs for each control. It takes care of cleanup activities like wiping the database connectivities. When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is calledHttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension. The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts theIHttpHandler interface which begins processing the application code by calling

the the for the

processRequest() method.The processRequest() method then calls FrameworkInitialize() method which begins building the control trees the requested page. Now the processRequest() method cycles through page's life cycle in the order listed below. Description Page_Init Page Initialization LoadViewState View State Loading LoadPostData Postback Data Processing Page_Load Page Loading RaisePostDataChangedEvent PostBack Change Notification RaisePostBackEvent PostBack Event Handling Page_PreRender Page Pre Rendering Phase SaveViewState View State Saving Page_Render Page Rendering Page_Unload Page Unloading Methods

ASP .NET Page Life Cycle

PostBack and CrossPage Posting


In Active Server Pages 3.0, developers had their pages post to other pages within the application.ASP.NET pages typically post back to themselves in order to process events (such as a button-clickevent). For this reason, you must differentiate between posts for the first time a page is loaded by the end userand postbacks. A postback is just that a posting back to the same page. The postback contains all theform information collected on the initial page for processing if required. Because of all the postbacks that can occur with an ASP.NET page, you want to know whether a requestis the first instance for a particular page or is a postback from the same page. You can make this check byusing the IsPostBack property of the Page class, as shown in the following example: if (Page.IsPostBack == true) { // Do processing } In addition to checking against a True or False value, you can also find out if the request is not a postbackin the following manner: if (!Page.IsPostBack) { // Do processing } The Page class includes a property called the IsPostBack property, which you can use todetect whether the page has already been posted back to the server.Because of View State, when you initialize a control property, you do not want to initializethe property every time a page loads. Because View State saves the state of control propertiesacross page posts, you typically initialize a control property only once, when the pagefirst loads. In fact, many controls dont work correctly if you re-initialize the properties of the controlwith each page load. In these cases, you must use the IsPostBack property to detectwhether or not the page has been posted. One common feature in ASP 3.0 that is difficult to achieve in ASP.NET 1.0/1.1 is the capability to docross-page posting. Cross-page posting enables you to submit a form (say, Page1.aspx) and have thisform and all the control values post themselves to another page (Page2.aspx). Traditionally, any page created in ASP.NET 1.0/1.1 simply posted to itself, and you handled the controlvalues within this page instance. You could differentiate between the pages first request and anypostbacks by using the Page.IsPostBack property, as shown here: If Page.IsPostBack Then deal with control values End If Even with this capability, many developers still wanted to be able to post to another page and deal withthe first pages control values on that page. This is something that is possible in ASP.NET 3.5, and it is quite a simple process.

You can work with the request through the use of the IsCrossPagePostBack property that isquite similar to the IsPostBack property from ASP.NET 1.0/1.1. The IsCrossPagePostBack propertyenables you to check whether the request is from previous page.

ASP.NET Application Compilation models


When an ASP.NET page is referenced in the browser for the first time, the request is passed to theASP.NET parser that creates the class file in the language of the page. It is passed to the ASP.NET parserbased on the files extension (.aspx) because ASP.NET realizes that this file extension type is meant forits handling and processing. After the class file has been created, the class file is compiled into a DLL andthen written to the disk of the Web server. At this point, the DLL is instantiated and processed, and anoutput is generated for the initial requester of the ASP.NET page. On the next request, great things happen. Instead of going through the entire process again for the secondand respective requests, the request simply causes an instantiation of the already-created DLL, whichsends out a response to the requester.Because of the mechanics of this process, if you made changes to your .aspx code-behind pages, youfound it necessary to recompile your application. This was quite a pain if you had a larger site and didnot want your end users to experience the extreme lag that occurs when an .aspx page is referenced forthe first time after compilation. Many developers, consequently, began to develop their own tools thatautomatically go out and hit every single page within their application to remove this first-time lag hitfrom the end users browsing experience. ASP.NET 3.5 provides a few ways to precompile your entire application with a single command thatyou can issue through a command line. One type of compilation is referred to as in-place precompilation. In order to precompile your entire ASP.NET application, you must use the aspnet_compiler.exe toolthat now comes with ASP.NET 3.5. You navigate to the tool using the Command window. Open theCommand window and navigate to C:\Windows\Microsoft.NET\Framework\v2.0.50727\. When youare there, you can work with the aspnet_compiler tool. You can also get to this tool directly by pullingup the Visual Studio 2008 Command Prompt. Choose StartAll ProgramsMicrosoft Visual Studio2008Visual Studio ToolsVisual Studio 2008 Command Prompt. After you get the command prompt, you use the aspnet_compiler.exe tool to perform an in-place precompilationusing the following command: aspnet_compiler -p "C:\Inetpub\wwwroot\WROX" -v none You then get a message stating that the precompilation is successful. The other great thing about thisprecompilation capability is that you can also use it to find errors on any of the ASP.NET pages in yourapplication. Because it hits each and every page, if one of the pages contains an error that wont betriggered until runtime, you get notification of the error immediately as you employ this precompilationmethod. The next precompilation option is commonly referred to as precompilation for deployment. This is an outstandingcapability of ASP.NET that enables you to compile your application down to some DLLs,

whichcan then be deployed to customers, partners, or elsewhere for your own use. Not only are minimal stepsrequired to do this, but also after your application is compiled, you simply have to move around the DLL and some placeholder files for the site to work. This means that your Web site code is completelyremoved and placed in the DLL when deployed. However, before you take these precompilation steps, create a folder in your root drive called, forexample, Wrox. This folder is the one to which you will direct the compiler output. When it is in place,you can return to the compiler tool and give the following command: aspnet_compiler -v [Application Name] -p [Physical Location] [Target] Therefore, if you have an application called INETA located at C:\Websites\INETA, you use the followingcommands: aspnet_compiler -v /INETA -p C:\Websites\INETA C:\Wrox Press the Enter key, and the compiler either tells you that it has a problem with one of the commandparameters or that it was successful. After compiling the application, you can go to C:\Wrox to see the output. Here, you see all the files andthe file structures that were in the original application. However, if you look at the content of one of thefiles, notice that the file is simply a placeholder. In fact, you find a Code.dll file in the bin folderwhere all the page code is located. Because it is in aDLLfile, it provides great code obfuscation as well. From here on, all you do is move these files to anotherserver using FTP or Windows Explorer, and you can run the entire Web application from these files.When you have an update to the application, you simply provide a new set of compiled files. Note that this compilation process does not compile every type of Web file. In fact, it compiles only theASP.NET-specific file types and leaves out of the compilation process the following types of files: HTML files XML files XSD files web.config files Text files You cannot do much to get around this, except in the case of the HTML files and the text files. For thesefile types, just change the file extensions of these file types to .aspx; they are then compiled into theCode.dll like all the other ASP.NET files.

ASP.NET Controls:
In the past, one of the difficulties of working with classic ASP was that you were completely incharge of the entire HTML output from the browser by virtue of the server-side code you wrote.Although this might seem ideal, it created a problem because each browser interpreted the HTMLgiven to it in a slightly different manner. The two main browsers out there at the time were Microsofts Internet Explorer and NetscapeNavigator. This meant that not only did developers have to be cognizant of the browser type towhich they were outputting HTML, but they also had to take into account which versions of thoseparticular browsers might be making a request to their application. Some developers resolvedthe issue by creating two separate applications. When an end user made an initial request to theapplication, the code made a browser check to see what browser type was making the request.Then, the ASP page would redirect the request down one path for an IE user, or down another pathfor a Netscape user. Because requests came from so many different versions of the same browser, the developer often designedfor the lowest possible version that might be used to visit the site. Essentially, everyone lost out by usingthe lowest common denominator as the target. This technique ensured that the page was rendered properlyin most browsers making a request, but it also forced the developer to dumb-down his application. If applications were always built for the lowest common denominator, the developer could never takeadvantage of some of the more advanced features offered by newer browser versions. ASP.NET server controls overcome these obstacles. When using the server controls providedby ASP.NET, you are not specifying the HTML to be output from your server-side code. Rather, youare specifying the functionality you want to see in the browser and letting the ASP.NET decide foryou on the output to be sent to the browser. When a request comes in, ASP.NET examines the request to see which browser type is making therequest, as well as the version of the browser, and then it produces HTML output specific to that browser. This process is accomplished by processing a User Agent header retrieved from the HTTP Request tosniff the browser. This means that you can now build for the best browsers out there without worryingabout whether features will work in the browsers making requests to your applications. Because of thepreviously described capabilities, you will often hear these controls referred to as smart controls.

Types of Server Controls:


ASP.NET provides two distinct types of server controls HTML server controls and Web server controls.Each type of control is quite different and, as you work with ASP.NET, you will see that much ofthe focus is on the Web server controls. This does not mean that HTML server controls have no value.They do provide you with many capabilities some that Web server controls do not give you.

HTML server controls map to specific HTML elements. You can placean HtmlTable server control on your ASP.NET page that works dynamically with a <table>element.On the other hand, Web server controls map to specific functionality that you want on your ASP.NETpages. This means an <asp:Panel>control might use a <table>or an another element altogether itreally depends on the capability of the browser making the request. The syntax will be: <asp:controlTypeid="ControlID"runat="server" /> The following table provides a summary of information on when to use HTML server controls and whento use Web server controls.

Control Type
HTML Server

When to Use This Control Type


When converting traditional ASP 3.0 Web pages to ASP.NET Web pages and speedof completion is a concern. It is a lot easier to change your HTML elements toHTML server controls than it is to change them to Web server controls.When you prefer a more HTML-type programming model. When you want toexplicitly control the code that is generated for the browser. When you require a richer set of functionality to perform complicated pagerequirements.When you are developing Web pages that will be viewed by a multitude of browser types and that require different code based upon these types.When you prefer a more Visual Basictype programming model that is based onthe use of controls and control properties.

Web Server

Of course, some developers like to separate certain controls from the rest and place them in their owncategories. For instance, you may see references to the following types of controls: List controls: These control types allow data to be bound to them for display purposes ofsome kind. Rich controls: Controls, such as the Calendar control, that display richer content andcapabilities than other controls. Validation controls: Controls that interact with other form controls to validate the data thatthey contain. Mobile controls: Controls that are specific for output to devices such as mobile phones, PDAs,and more. User controls: These are not really controls, but page templates that you can work with as youwould a control on your ASP.NET page. Custom controls: Controls that you build yourself and use in the same manner as the suppliedASP.NET server controls that come with the default install of ASP.NET 3.5. When you are deciding between HTML server controls and Web server controls, remember that no hardand fast rules exist about which type to use. You might find yourself working with one control type more than another, but certain features are available in one control type that might not be available in the other.If you are trying to accomplish a specific task and you do not see a solution with the control type you areusing, take a look at the other control type because it may very well

hold the answer. Also, realize thatyou can mix and match these control types. Nothing says that you cannot use both HTML server controlsand Web server controls on the same page or within the same application.

ASP.NET Server Controls:


The Web server control is ASP.NETs most-used component.Web server controls are definitelya notch higher in capability. They allow for a higher level of functionality that becomes moreapparent as you work with them.Web server controls work differently. They do not map to specific HTML elements, but instead enableyou to define functionality, capability, and appearance without the attributes that are available to youthrough a collection of HTML elements. When constructing a Web page that is made up of Web servercontrols, you are describing the functionality, the look-and-feel, and the behavior of your page elements.You then let ASP.NET decide how to output this construction. The output, of course, is basedon the capabilities of the container that is making the request. This means that each requestor mightsee a different HTML output because each is requesting the same page with a different browser typeor version. ASP.NET takes care of all the browser detection and the work associated with it on yourbehalf. Unlike HTML server controls, Web server controls are not only available for working with commonWebpage form elements (such as text boxes and buttons), but they can also bring some advanced capabilitiesand functionality to your Web pages.Remember that when you are constructing your Web server controls, you are actually constructing acontrol a set of instructions that is meant for the server (not the client). By default, all Web servercontrols provided by ASP.NET use an asp: at the beginning of the control declaration. The following is a typical Web server control: <asp:Label ID="Label1" runat="server" Text="Hello World"></asp:Label> Like HTML server controls, Web server controls require an ID attribute to reference the control in theserver-side code, as well as a runat="server" attribute declaration. As you do for other XMLbasedelements, you need to properly open and close Web server controls using XML syntax rules.

The Label Server Control :


The Label server control is used to display text in the browser. Because this is a server control, you candynamically alter the text from your server-side code. The control uses the Text attribute to assign the content of the control as shownhere: <asp:Label ID="Label1" runat="server" Text="Hello World" /> Any string that you assign to the Label controls Text property is displayed by the Labelwhen the control is rendered. You can assign simple text to the Text property or you canassign HTML content. As an alternative to assigning text to the Text property, you can place the text betweenthe Label controls opening and closing tags. Any text that you place before the openingand closing tags gets assigned to the Text property.By default, a Label control renders its contents in an HTML <span> tag. Whatever valueyou assign to the Text property is rendered to the browser enclosed in a <span> tag.

The Label control supports several properties you can use to format the text displayed bythe Label (this is not a complete list): BackColor - Enables you to change the background color of the label. BorderColor - Enables you to set the color of a border rendered around the label. BorderStyle - Enables you to display a border around the label. Possible values areNotSet, None, Dotted, Dashed, Solid, Double, Groove, Ridge, Inset, and Outset. BorderWidth - Enables you to set the size of a border rendered around the label. CssClass - Enables you to associate a Cascading Style Sheet class with the label. Font - Enables you to set the labels font properties. ForeColor - Enables you to set the color of the content rendered by the label. Style - Enables you to assign style attributes to the label. ToolTip - Enables you to set a labels title attribute. (In Microsoft InternetExplorer, the title attribute is displayed as a floating tooltip.)

The TextBox Server Control


One of the main features ofWeb pages is to offer forms that end users can use to submit their informationfor collection. The TextBox server control is one of the most used controls in this space. As its namesuggests, the control provides a text box on the form that enables the end user to input text. The TextBox control can be used to display three different types of input fields dependingon the value of its TextMode property. The TextMode property accepts the followingthree values: SingleLine -Displays a single-line input field. MultiLine - Displays a multi-line input field. Password - Displays a single-line input field in which the text is hidden. You can use the following properties to control the rendering characteristics of theTextBox control (this is not a complete list): AccessKeyEnables you to specify a key that navigates to the TextBox control. AutoCompleteTypeEnables you to associate an AutoComplete class with theTextBox control. AutoPostBackEnables you to post the form containing the TextBox back to theserver automatically when the contents of the TextBox is changed. ColumnsEnables you to specify the number of columns to display. EnabledEnables you to disable the text box. MaxLengthEnables you to specify the maximum length of data that a user canenter in a text box (does not work when TextMode is set to Multiline).

ReadOnlyEnables you to prevent users from changing the text in a text box. RowsEnables you to specify the number of rows to display. TabIndexEnables you to specify the tab order of the text box. WrapEnables you to specify whether text word-wraps when the TextMode is setto Multiline. The TextBox control also supports the following method: FocusEnables you to set the initial form focus to the text box. And, the TextBox control supports the following event: TextChangedRaised on the server when the contents of the text box are changed. When the AutoPostBack property has the value True, the form containing the TextBox isautomatically posted back to the server when the contents of the TextBox changes.

The Button Server Control


A common control for your Web forms is a button that can be constructed using the Button servercontrol. Buttons are the usual element used to submit forms. Most of the time you are simply dealing withitems contained in your forms through the Button controls OnClick event. Buttons are controls that post the form back to the server, enabling server-side processing tocommence. There are three types of button controls: Button LinkButton ImageButton The Button control supports the following properties: AccessKeyEnables you to specify a key that navigates to the Button control. CommandArgumentEnables you to specify a command argument that is passed tothe Command event. CommandNameEnables you to specify a command name that is passed to theCommand event. EnabledEnables you to disable the Button control. OnClientClickEnables you to specify a client-side script that executes when thebutton is clicked. PostBackUrlEnables you to post a form to a particular page. TabIndexEnables you to specify the tab order of the Button control. TextEnables you to label the Button control. UseSubmitBehaviorEnables you to use JavaScript to post a form.

The Button control also supports the following method: FocusEnables you to set the initial form focus to the Button control. The Button control also supports the following two events: ClickRaised when the Button control is clicked. CommandRaised when the Button control is clicked. The CommandName andCommandArgument are passed to this event.

The LinkButton Server Control


The LinkButton control is sort of a cross between a standard button and a HyperLinkcontrol. A LinkButton appears to the user as a hyperlink,i.e., the text is colored and underlined. The big difference between a LinkButton controland a standard Button control is that the LinkButton's functionality is implemented usingclient-side scripting. The LinkButton control, like the Button control, enables you to post a form to the server.Unlike a Button control, however, the LinkButton control renders a link instead of apush button. <asp:LinkButton ID="LinkButton1" Runat="server" OnClick="LinkButton1_Click"> Submit your name to our database </asp:LinkButton> Clicking the LinkButton invokes the JavaScript __doPostBack() method, which poststhe form to the server. When the form is posted, the values of all the other form fields inthe page are also posted to the server.The LinkButton control supports the following properties: AccessKeyEnables you to specify a key that navigates to the Button control. CommandArgumentEnables you to specify a command argument that is passed tothe Command event. CommandNameEnables you to specify a command name that is passed to theCommand event. EnabledEnables you to disable the LinkButton control. OnClientClickEnables you to specify a client-side script that executes when theLinkButton is clicked. PostBackUrlEnables you to post a form to a particular page. TabIndexEnables you to specify the tab order of the LinkButton control. TextEnables you to label the LinkButton control. The LinkButton control also supports the following method: FocusEnables you to set the initial form focus to the LinkButton control. The LinkButton control also supports the following two events: ClickRaised when the LinkButton control is clicked. CommandRaised when the LinkButton control is clicked. The CommandName andCommandArgument are passed to this event.

The ImageButton Server Control


The ImageButton control performs the same function as the standard button, except thatan image bitmap takes the place of the button on the browser UI. For the ImageButtoncontrol, there is no Text attribute, but there is an AlternateText attribute, whichspecifies what text to display on non-graphical browsers.In addition, note that the event handler uses an ImageClickEventArgs event argument,which is

slightly different than the event handlers for the Button and LinkButton controls. The ImageButton control, like the Button and LinkButton controls, enables you to post aform to the server. However, the ImageButton control always displays an image. <asp:ImageButton ID="ImageButton1" runat="server" OnClick="ImageButton1_Click" ImageUrl="MyButton.jpg" /> Default.aspx.cs protected void ImageButton1_Click(object sender, System.Web.UI.WebControls.ImageClickEventArgs e) { // Code here } The ImageButton control supports the following properties: AccessKeyEnables you to specify a key that navigates to the ImageButton control. AlternateTextEnables you to provide alternate text for the image DescriptionUrlEnables you to provide a link to a page that contains a detaileddescription of the image CommandArgumentEnables you to specify a command argument that is passed tothe Command event. CommandNameEnables you to specify a command name that is passed to theCommand event. EnabledEnables you to disable the ImageButton control. GenerateEmptyAlternateTextEnables you to set the AlternateText property toan empty string. ImageAlignEnables you to align the image relative to other HTML elements in thepage. Possible values are AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle,NotSet, Right, TextTop, and Top. ImageUrlEnables you to specify the URL to the image. OnClientClickEnables you to specify a client-side script that executes when theImageButton is clicked. PostBackUrlEnables you to post a form to a particular page. TabIndexEnables you to specify the tab order of the ImageButton control.

The ImageButton control also supports the following method: FocusEnables you to set the initial form focus to the ImageButton control. The ImageButton control also supports the following two events: ClickRaised when the ImageButton control is clicked. CommandRaised when the ImageButton control is clicked. The CommandName and CommandArgument are passed to this event.

The HyperLink Server Control

The HyperLink server control enables you to programmatically work with any hyperlinks on your Webpages. Hyperlinks are links that allow end users to transfer from one page to another. You can set thetext of a hyperlink using the controls Text attribute: <asp:HyperLink ID="HyperLink1" runat="server" Text="Go to this page here" NavigateUrl="~/Default2.aspx"></asp:HyperLink> This server control creates a hyperlink on your page with the text Go to this page here. When the linkis clicked, the user is redirected to the value that is placed in the NavigateUrl property. The interesting thing about the HyperLink server control is that it can be used for images as well as text. Instead of using the Text attribute, it uses the ImageUrl property: <asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="~/MyLinkImage.gif" NavigateUrl="~/Default2.aspx"></asp:HyperLink> The HyperLink control is a great way to dynamically place hyperlinks on a Web page based either uponuser input in a form or on database values that are retrieved when the page is loaded. The HyperLink control has four specific attributes: ImageURLThe path to an image (rather than text) to display. If this attribute is used, the controlappears to the user as identical to an ImageButton control, although the ImageButtoncontrol still posts the form and the HyperLink control only navigates. NavigateURLThe target URL to navigate to. TextThe text string that will be displayed on the browser as the link. If both the Text andImageURL properties are set, the ImageURL takes precedence. The text is displayed ifthe image is unavailable.If the browser supports tool tips and the ToolTip property has not been set, then theText value will display as a tool tip. If the ToolTip property has been set, then theToolTip text string will display as a tool tip. TargetDefines the target window or frame that will load the linked page. Special values of the Target attributeValue Description _blank, _new, _parent, _self, _top

The DropDownList Server Control


The DropDownList server control enables you to place an HTML select box on your Web page andprogram against it. It is ideal when you have a large collection of items from which you want the enduser to select a single item. It is usually used for a medium- to largesized collection. If the collection sizeis relatively small, consider using the RadioButtonList server control. The select box generated by the DropDownList control displays a single item and allows the end user tomake a selection from a larger list of items. Depending on the number of choices available in the selectbox, the end user may have to scroll through a list of items. Note that the appearance of the scroll bar inthe drop-down list is automatically created by the browser depending on the browser version and thenumber of items contained in the list.

Here is the code for DropDownList control: <asp:DropDownList ID="DropDownList1" runat="server"> <asp:ListItem>Car</asp:ListItem> <asp:ListItem>Airplane</asp:ListItem> <asp:ListItem>Train</asp:ListItem> </asp:DropDownList>

The ListBox Server Control


The ListBox server control has a function similar to the DropDownList control. It displays a collectionof items. The ListBox control behaves differently from the DropDownList control in that it displaysmore of the collection to the end user, and it enables the end user to make multiple selections from thecollection something that is not possible with the DropDownList control.A typical ListBox control appears in code as follows: <asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem>Hematite</asp:ListItem> <asp:ListItem>Halite</asp:ListItem> <asp:ListItem>Limonite</asp:ListItem> <asp:ListItem>Magnetite</asp:ListItem> </asp:ListBox> You can use the SelectionMode attribute to let your end users make multiple selections from what isdisplayed by the ListBox control The possible values of the SelectionMode property include Single and Multiple. Setting the value toMultiple allows the end user to make multiple selections in the list box. The user must hold down either the Ctrl or Shift keys while making selections. Holding down the Ctrl key enables the user to make asingle selection from the list while maintaining previous selections. Holding down the Shift key enables a range of multiple selections.

The CheckBox Server Control


Check boxes on a Web form enable your users to either make selections from a collection of items orspecify a value of an item to be yes/no, on/off, or true/false. Use either the CheckBox control or theCheckBoxList control to include check boxes in your Web forms. The CheckBox control allows you to place single check boxes on a form; the CheckBoxList control allowsyou to place collections of check boxes on the form. You can use multiple CheckBox controls on yourASP.NET pages, but then you are treating each check box as its own element with its own associatedevents. On the other hand, the CheckBoxList control allows you to take multiple check boxes and createspecific events for the entire group.The CheckBox control supports the following properties: AutoPostBackEnables you to post the form containing the CheckBox back to theserver automatically when the CheckBox is checked or unchecked. CheckedEnables you to get or set whether the CheckBox is checked. TextAlignEnables you to align the label for the check box. Possible values areLeft and Right.

The CheckBox control also supports the following method: FocusEnables you to set the initial form focus to the check box. The CheckBox control supports the following event: CheckedChangedRaised on the server when the check box is checked or unchecked. The CheckBox control, like the TextBox control, supports the AutoPostBackproperty. The page, how you can use the AutoPostBack propertyto post the form containing the check box back to the server automatically when thecheck box is checked or unchecked.

The CheckBoxList Server Control


The CheckBoxList server control is quite similar to the CheckBox control, except that the former enablesyou to work with a collection of items rather than a single item. The idea is that a CheckBoxList servercontrol instance is a collection of related items, each being a check box unto itself.

The RadioButton Server Control


The RadioButton server control is quite similar to the CheckBox server control. It places a radio button onyourWeb page. Unlike a check box, however, a single radio button on a form does not make much sense.Radio buttons are generally form elements that require at least two options. A typical set of RadioButtoncontrols on a page takes the following construction: <asp:RadioButton ID="RadioButton1" runat="server" Text="Yes" GroupName="Set1" /> <asp:RadioButton ID="RadioButton2" runat="server" Text="No" GroupName="Set1"/> When you look at the code for the RadioButton control, note the standard Text property that places thetext next to the radio button on the Web form. The more important property here is GroupName, whichcan be set in one of the RadioButton controls to match what it is set to in the other. This enables the radiobuttons on theWeb form to work together for the end user. How do they work together? Well, when oneof the radio buttons on the form is checked, the circle associated with the item selected appears filled in.Any other filled-in circle from the same group in the collection is removed, ensuring that only one of theradio buttons in the collection is selected. You always use the RadioButton control in a group. Only one radio button in a group ofRadioButton controls can be checked at a time.The RadioButton control supports the following properties: AutoPostBackEnables you to post the form containing the RadioButton back tothe server automatically when the radio button is checked or unchecked. CheckedEnables you to get or set whether the RadioButton control is checked. GroupNameEnables you to group RadioButton controls. TextEnables you to label the RadioButton control.

TextAlignEnables you to align the RadioButton label. Possible values are Leftand Right. The RadioButton control supports the following method: FocusEnables you to set the initial form focus to the RadionButton control. The RadioButton control supports the following event: CheckedChangedRaised on the server when the RadioButton is checked orunchecked.

The RadioButtonList Server Control


The RadioButtonList server control lets you display a collection of radio buttons on a Web page. TheRadioButtonList control is quite similar to the CheckBoxList and other list controls in that it allows youto iterate through to see what the user selected, to make counts, or to perform other actions.A typical RadioButtonList control is written to the page in the following manner: <asp:RadioButtonList ID="RadioButtonList1" runat="server"> <asp:ListItem Selected="True">English</asp:ListItem> <asp:ListItem>Russian</asp:ListItem> <asp:ListItem>Finnish</asp:ListItem> <asp:ListItem>Swedish</asp:ListItem> </asp:RadioButtonList> Like the other list controls, this one uses instances of the ListItem object for each of the items containedin the collection. From the example, you can see that if the Selected property is set to True, one of theListItem objects is selected by default when the page is generated for the first time.

Image Server Control


The Image server control enables you to work with the images that appear on your Web page from theserver-side code. It is a simple server control, but it can give you the power to determine how your imagesare displayed on the browser screen. A typical Image control is constructed in the following manner: <asp:Image ID="Image1" runat="server" ImageUrl="~/MyImage1.gif" /> The important property here is ImageUrl. It points to the file location of the image. In this case, thelocation is specified as the MyImage.gif file. The Image control supports the following properties: AlternateTextEnables you to provide alternate text for the image DescriptionUrlEnables you to provide a link to a page that contains a detailed description of the image. GenerateEmptyAlternateTextEnables you to set the AlternateText property toan empty string. ImageAlignEnables you to align the image relative to other HTML elements inthe page. Possible values are AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle,NotSet, Right, TextTop, and Top. ImageUrlEnables you to specify the URL to the image.

Table Server Control


Tables are one of the Web pages more common elements because the HTML <table> element is onepossible format utilized for controlling the layout of your Web page (CSS being the other). The typicalconstruction of the Table server control is as follows: <asp:Table ID="Table1" runat="server"> <asp:TableRow Runat="server" Font-Bold="True" ForeColor="Black" BackColor="Silver"> <asp:TableHeaderCell>First Name</asp:TableHeaderCell> <asp:TableHeaderCell>Last Name</asp:TableHeaderCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Bill</asp:TableCell> <asp:TableCell>Evjen</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Devin</asp:TableCell> <asp:TableCell>Rader</asp:TableCell> </asp:TableRow> </asp:Table> Tables are very important in web page design, as they are one of the primary means of controllingthe layout on the page. In pure HTML, there are several tags for creating and formatting tables,and many of those have analogs in ASP controls. If you don't need server-side capabilities, thenyou are just as well off using the static HTML tags. But when you need to control the table atruntime, then ASP controls are the way to go. ASP control Table TableRow TableCell Table HeaderCel l HTMLana log <table> <tr> <td> <th> Description Parent control for TableRow controls. The Rows property of theTable object is a collection of TableRow objects. Parent control for TableCell controls. The Cells property of theTableRow object contains a collection of TableCell objects. Contains content to be displayed. The Text property containsHTML text. The Controls collection can contain other controls. Derived from the TableCell class. Controls the display of headingcell(s)

The Calendar Server Control


The ASP Calendar control is a rich web control that provides several capabilities: Displays a calendar showing a single month Allows the user to select a day, week, or month Allows the user to select a range of days Allows the user to move to the next or previous month Allows all aspects of the appearance of the calendar to be customized either at designtime or under program control Programmatically controls the display of specific days

The Calendar server control is a rich control that enables you to place a full-featured calendar directlyon your Web pages. It allows for a high degree of customization to ensure that it looks and behaves in aunique manner. The Calendar control, in its simplest form, is coded in the following manner: <asp:Calendar ID="Calendar1" runat="server"> </asp:Calendar> By providing event handlers for the events, you canexercise considerable control over how the calendar behaves. These are: SelectionChanged event DayRender event VisibleMonthChanged event SelectRange method

AdRotator Server Control


Although Web users find ads rather annoying, advertising continues to be prevalent everywhere on theWeb. With the AdRotator control, you can configure your application to show a series of advertisementsto the end users. With this control, you can use advertisement data from sources other than the standardXML file that was used with the previous versions of this control.If you are using an XML source for the ad information, first create an XML advertisement file. The advertisementfile allows you to incorporate some new elements that give you even more control over theappearance and behavior of your ads. Element Description ImageUrl Takes a string value that indicates the location of the image to use. NavigateUrl Takes a string value that indicates the URL to post to when the image is clicked. AlternateText Takes a string value that is used for display either if images are turned off in theclients browser or if the image is not found. Keyword Takes a string value that sets the category of the image in order to allow for thefiltering of ads. Impressions Takes a numerical value that indicates the likelihood of the image being selected for display.

Panel Server Control


The Panel control enables you to work with a group of ASP.NET controls.The Panel control supports the following properties: DefaultButtonEnables you to specify the default button in a Panel. The defaultbutton is invoked when you press the Enter button. DirectionEnables you to get or set the direction in which controls that displaytext are rendered. Possible values are NotSet, LeftToRight, and RightToLeft. GroupingTextEnables you to render the Panel control as a fieldset with a particularlegend.

HorizontalAlignEnables you to specify the horizontal alignment of the contentsof the Panel. Possible values are Center, Justify, Left, NotSet, and Right. ScrollBarsEnables you to display scrollbars around the panels contents. Possiblevalues are Auto, Both, Horizontal, None, and Vertical. By default, a Panel control renders a <div> tag around its contents. If you set theGroupingText property, however, the Panel control renders a <fieldset> tag. The valuethat you assign to the GroupingText property appears in the <fieldset> tags <legend> tag.

The PlaceHolder Server Control


The PlaceHolder server control works just as its name implies it is a placeholder for you to interjectobjects dynamically into your page. Think of it as a marker with which you can add other controls. Thecapability to add controls to a page at a specific point also works with the Panel control.

BulletedList Server Control


One common HTML Web page element is a collection of items in a bulleted list. The BulletedList servercontrol is meant to display a bulleted list of items easily in an ordered (using the HTML <ol> element)or unordered (using the HTML <ul> element) fashion. In addition, the control can determine the styleused for displaying the list.The BulletedList control can be constructed of any number of <asp:ListItem> controls or can bedata-bound to a data source of some kind and populated based upon the contents retrieved. The BulletedList control also enables you to easily change the style of the list with just one or twoattributes. The BulletStyle attribute changes the style of the bullet that precedes each line of the list.It has possible values of Numbered, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman, Disc, Circle,Square, NotSet, and CustomImage. To employ images as bullets, use the CustomImage setting in the BulletedList control. You must also usethe BulletImageUrl attribute in the following manner: <asp:BulletedList ID="Bulletedlist1" runat="server" BulletStyle="CustomImage" BulletImageUrl="~/myImage.gif">

HiddenField Server Control


For many years now, developers have been using hidden fields in their Web pages to work with statemanagement. The <input type="hidden"> element is ideal forstoring items that have no security contextto them. These items are simply placeholders for data points that you want to store in the page itselfinstead of using the Session object or intermingling the data with the view state of the page. View stateis another great way to store information in a page, but many developers turn off this feature to avoidcorruption of the view state or possible degradation of page performance.Any time a hidden field is placed within a Web page, it is not interpreted in the browser in any fashion,although it is completely viewable by end users if they look at the source of the HTML page.

FileUpload Server Control

In ASP.NET 1.0/1.1, you could upload files using the HTML FileUpload server control. This control putan <input type="file"> element on your Web page to enable the end user to upload files to the server.To use the file, however, you had to make a couple of modifications to the page. For example, you wererequired to add enctype="multipart/form-data" to the pages <form> element. ASP.NET 2.0 introduced a new FileUpload server control that makes the process of uploading files toa server even simpler. When giving a page the capability to upload files, you simply include the new<asp:FileUpload> control and ASP.NET takes care of the rest, including adding the enctype attributeto the pages <form> element. No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from asingle ASP.NET page. The trick is to import the System.IO class into your ASP.NET page and then to use the HttpFileCollectionclass to capture all the files that are sent in with the Request object.

Wizard Server Control


Much like the MultiView control, the Wizard server control enables you to build a sequence of steps thatis displayed to the end user. Web pages are all about either displaying or gathering information and, inmany cases, you dont want to display all the information at once nor do you always want to gathereverything from the end user at once. Sometimes, you want to trickle the information in from or out tothe end user. When you are constructing a step-by-step process that includes logic on the steps taken, use the Wizardcontrol to manage the entire process. The first time you use the Wizard control, notice that it allows for afar greater degree of customization than does the MultiView control.In its simplest form, the Wizard control can be just an <asp:Wizard> element with any number of<asp:WizardStep> elements. <asp:WizardStep runat="server" Title="Step 1"> This is the first step.</asp:WizardStep> One of the most convenient capabilities of the Wizard control is that it enables you to divide large formsinto logical pieces. The end user can then work systematically through each section of the form. Thedeveloper, dealing with the inputted values of the form, has a few options because of the various eventsthat are available in the Wizard control.The Wizard control exposes events for each of the possible steps that an end user might take whenworking with the control. The <asp:Wizard> element itself contains a couple of important attributes. The first is DisplaySideBar, it is set to True by default meaning that a side navigation system in the displayedcontrol enables the end user to quickly navigate to other steps in the process. The ActiveStepIndexattribute of the Wizard control defines the first wizard step. The side navigation allows for easy access to the defined steps. The Wizard control adds appropriatebuttons to the steps in the process. The first step has simply a Next button, the middle step has Previousand Next buttons, and the final step has Previous and Finish buttons. The user can

navigate through the steps using either the side navigation or the buttons on each of the steps. You can customize the Wizardcontrol in so many ways that it tends to remind me of the other rich Web server controls from ASP.NET. The following table describes each of the available events. Event ActiveStepChanged Description Triggers when the end user moves from one step to the next. It does notmatter if the step is the middle or final step in the series. This eventsimply covers each step change generically. Triggers when the end user clicks the Cancel button in the navigation system. Triggers when the end user clicks the Finish button in the navigation system. the Next the Previous one of the navigation of

CancelButtonClick FinishButtonClick NextButtonClick

Triggers when the end user clicks button in the navigation system. Triggers when the end user clicks PreviousButtonClick button in the navigationsystem Triggers when the end user clicks SideBarButtonClick links contained within thesidebar the Wizard control.

ImageMap Server Control


The ImageMap control enables you to create a client-side image map. An image mapdisplays an image. When you click different areas of the image, things happen.In that case, clickingdifferent areas of the image map navigates to different pages in your website.You also can use an image map as an input mechanism. For example, you can click differentproduct images to add a particular product to a shopping cart. An ImageMap control is composed out of instances of the HotSpot class. A HotSpotdefines the clickable regions in an image map. The ASP.NET framework ships with threeHotSpot classes: CircleHotSpotEnables you to define a circular region in an image map. PolygonHotSpotEnables you to define an irregularly shaped region in an imagemap. RectangleHotSpotEnables you to define a rectangular region in an image map. The ImageMap control supports the following properties: AlternateTextEnables you to provide alternate text for the image DescriptionUrlEnables you to provide a link to a page which contains adetailed description of the image GenerateEmptyAlternateTextEnables you to set the AlternateText property toan empty string. HotSpotModeEnables you to specify the behavior of the image map when youclick a region. Possible values are Inactive, Navigate, NotSet, and PostBack.

HotSpotsEnables you to retrieve the collection of HotSpots contained in theImageMap control. ImageAlignEnables you to align the image map with other HTML elements inthe page. Possible values are AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle,NotSet, Right, TextTop, and Top. ImageUrlEnables you to specify the URL to the image. TabIndexEnables you to specify the tab order of the ImageMap control. TargetEnables you to open a page in a new window. The ImageMap control also supports the following method: FocusEnables you to set the initial form focus to the ImageMap control. The ImageMap control supports the following event: ClickRaised when you click a region of the ImageMap and the HotSpotMode propertyis set to the value PostBack.

HTML Controls
The HTML server controls provided by ASP.NET work in that they map to specific HTML elements. Youcontrol the output by working with the HTML attributes that the HTML element provides. The attributescan be changed dynamically on the server side before they are finally output to the client. There is a lotof power in this, and you have some HTML server control capabilities that you simply do not have whenyou work with Web server controls.HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time HTML Server Control HtmlAnchor HtmlButton HtmlForm HtmlGeneric HtmlImage HtmlInputButton HtmlInputCheckBox Description Controls an <a> HTML element Controls a <button> HTML element Controls a <form> HTML element Controls other HTML element not specified by a specific HTML server control, like <body>, <div>, <span>, etc. Controls an <image> HTML element Controls <input type="button">, <input type="submit">, and <input type="reset"> HTML elements Controls an <input type="checkbox"> HTML element

HtmlInputFile HtmlInputHidden HtmlInputImage

Controls an <input type="file"> HTML element Controls an <input type="hidden"> HTML element Controls an <input type="image"> HTML element

HtmlInputRadioButton Controls an <input type="radio"> HTML element HtmlInputText HtmlSelect HtmlTable HtmlTableCell HtmlTableRow HtmlTextArea Controls <input type="text"> and <input type="password"> HTML elements Controls Controls Controls Controls a <select> HTML element a <table> HTML element <td>and <th> HTML elements a <tr> HTML element

Controls a <textarea> HTML element

Validation Controls
Many web applications involve user input. The sad fact is, however, thatusers make mistakes: they skip required fields, they put in six digit phone numbers, and theyreturn all manner of incorrectly formatted data to your application. Your database routines canchoke on corrupted data, and orders can be lost if, for example, a credit card number is enteredincorrectly or an address is omitted, so it is imperative that user input be validated. Traditionally, it has taken a great deal of time and effort to validate user input. Each field must bechecked and routines must be created for ensuring data integrity. In the event that bad data isfound, error messages must be displayed so that the user knows how to correct the problem.In a given application, you may choose to validate that certain fields have a value, that the valuesfall within a given range, or that the data is formatted correctly. For example, when processing anorder, you may need to ensure that the user has input an address and phone number, that the phonenumber has the right number of digits (and no letters), and that the social security number enteredis in the appropriate form of nine digits separated by hyphens. Some applications require more complex validation, in which one field is validated to be within arange established by two other fields. For example, you might ask in one field what date thecustomer wishes to arrive at your hotel, and in a second field you might ask for the departure date.When the user books dinner, you'll want to ensure that the date is between the arrival anddeparture dates. There is no limit to the complexity of the validation routines you may need to write. Credit cardshave checksums built into their values, as do ISBN numbers. Zip and postal codes follow complexpatterns, as do international phone numbers. You may need to validate passwords, membershipnumbers, dollar amounts, dates, runway choices, and launch codes.In addition, it is very desirable for all of this validation to happen client-side so that you avoid thedelay of repeated round trips to the server while the user tinkers with his input. In the past, thiswas solved by writing client-side JavaScript to validate the input, and then server-side script tohandle input from browsers that don't support

client-side programming. In addition, as a securitycheck, you may want to do server-side validation even when you already have clientsidevalidation, since it is extremely easy for users to circumvent validation code deliberately. Traditionally, this involved writing your validation code twice. As you can see, in traditional Internet programming, validation requires extensive customprogramming. The ASP.NET framework greatly simplifies this process by providing rich controlsfor validating user input that provide precise control over the validation routine while requiring farless custom coding. They also allow you to specify exactly how and where the error messages willbe displayed; either in-line with the input controls, aggregated together in a summary report, orboth. These controls can be used to validate input for both HTML and ASP controls. You add validation controls to your ASP document just as you would add any other control. With uplevel browsers that support DHTML, such as Internet Explorer 4 or better, .NETvalidation is done client-side, avoiding the necessity of a round trip to the server. With downlevelbrowsers your code is unchanged, but the code sent to the client ensures validation at the server.Even when client-side validation is done, the values are validated server-side as well.The validation is done client side (using DHTML) if the browser will support it; otherwise, thevalidation is done on the server. Note that even when the validation is done on the client, it is alsodone on the server as a security precaution. Because client-side validation will prevent your server-side event handlers from ever running ifthe control is not valid, you may want to force server-side validation. In that case, set a pageattribute: <%@ Page language="c#" ClientTarget="downlevel" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Validation04.WebForm1" %> This directive will cause the validation to happen on the server even if your browser would havesupported DHTML and client-side validation. Most developers automatically assume their application requires some kind of validationsystem when a diverse population enters web-based information. Even if your application isfor fairly sophisticated users who are familiar with entering data, you still should considersome way to make sure that users do not accidentally omit an important piece of informationor enter data incorrectly. Client-Side Validation To get the input they want, developers use some kind of validation process. For themost part, the validation is done on the client side. Client-side validation is preferred sothat the server will not have to both process data and do validation. Imagine thousandsof users entering data at the same time. If all those users had to first have their dataverified by the server, the processing would be slowed as the server had the dual choresof verifying data entry and processing the data once it was verified. A more sensibleapproach is for users to have their data verified on their own computers before sendingit to the server.

While client-side validation is more practical because the validation process isdistributed to the clients, it does not offer the level of protection provided by the server.Clients can get around client-side validation. For example, you would not want creditcardvalidation done on the client-side even though you could design an application that coulddo so. So while some client-side validation with ASP.NET is possible, especially usingMicrosofts Internet Explorer, even validated data are re-validated on the server side. Client-Side versus Server-Side Validation Suppose that the end user clicks the Submit button on a form afterfilling out some information. What happens in ASP.NET is that this form is packaged in a request andsent to the server where the application resides. At this point in the request/response cycle, you can runvalidation checks on the information submitted. If you do this, it is called server-side validation because itoccurs on the server.On the other hand, it is also possible to supply a script (usually in the form of JavaScript) in the pagethat is posted to the end users browser to perform validations on the data entered in the form before theform is posted back to the originating server. If this is the case, client-side validation has occurred. Both types of validation have their pros and cons. Active Server Pages 2.0/3.0 developers (from theclassic ASP days) are quite aware of these pros and cons because they have probably performed allthe validation chores themselves. Many developers spent a considerable amount of their classic ASPprogramming days coding various validation techniques for performance and security. Client-side validation is quick and responsive for the end user. It is something end users expect of theforms that they work with. If something is wrong with the form, using client-side validation ensuresthat the end user knows this as soon as possible. Client-side validation also pushes the processing powerrequired of validation to the client meaning that you dont need to spin CPU cycles on the server toprocess the same information because the client can do the work for you. With this said, client-side validation is the more insecure form of validation. When a page is generated inan end users browser, this end user can look at the code of the page quite easily (simply by right-clickinghis mouse in the browser and selecting View Code). When he does this, in addition to seeing the HTMLcode for the page, he can also see all the JavaScript that is associated with the page. If you are validatingyour form clientside, it doesnt take much for the crafty hacker to repost a form (containing the valueshe wants in it) to your server as valid. There are also the cases in which clients have simply disabled theclient-scripting capabilities in their browsers thereby making your validations useless. Therefore, client-side validation should be considered a convenience and a courtesy to the end user andnever as a security mechanism.The more secure form of validation is server-side

validation. Server-side validation means that thevalidation checks are performed on the server instead of on the client. It is more secure because thesechecks cannot be easily bypassed. Instead, the form data values are checked using server code (C# or VB)on the server. If the form isnt valid, the page is posted back to the client as invalid. Although it is moresecure, server-side validation can be slow. It is sluggish simply because the page has to be posted to aremote location and checked. Your end user might not be the happiest surfer in the world if, after waiting20 seconds for a form to post, he is told his e-mail address isnt in the correct format.So what is the correct path? Well, actually, both! The best approach is always to perform client-sidevalidation first and then, after the form passes and is posted to the server, to perform the validationchecks again using server-side validation. This approach provides the best of both worlds. ASP.NET Validation Server Controls ASP.NET 3.5 has five Server validation controls and a validation summary control. 1. RequiredFieldValidator 2. RangeValidator control 3. RegularExpressionValidator control 4. CustomValidator control 5. CompareValidator control 6. Validation Summary RequiredFieldValidator control The simplest validation control, it ensures that the user does not skip over your inputcontrol. A RequiredFieldValidator can be tied to a text box to force input into the text box.With selection controls, such as a drop-down or radio buttons, the RequiredFieldValidatorensures that the user makes a selection other than the default. The RequiredFieldValidatordoes not examine the validity of the data, but only makes sure that some data is entered orchosen.For each field you want completed by a user,you can use a RequiredFieldValidator that includes the name of the control tovalidate and an error message using the following format: ControlToValidate= "ControlName" ErrorMessage="Error message informing user that the field needs to becompleted." Importantly, any form that must be completed can be named as the control to be validated.So in addition to a TextBox control, others such as check boxes, radio buttons, and listsrequiring selection can be validated as well. RangeValidator control Ensures that the value entered is within a specified lower and upper boundary. You cancheck the range within a pair of numbers (e.g., greater than 10 and less than 100), a pairof characters (e.g., greater than D and less than K) and a pair of dates (e.g., after 1/1/01and before 2/28/01). The values you check can be

constants that you create at design-time,or they can be derived from other controls on your page (greater than the value intextBox1 and less than the value in textBox2).The two key properties of thisvalidator are MaximumValue and MinimumValue. In the code, you will see thefollowing elements required to connect and set these values to a form: ControlToValidate="ControlName" MaximumValue="150000" MinimumValue="25000" The values entered into the validated control are automatically treated as numeric valuesrather than text. When the user enters a value, as long it falls within the range specified,no error occurs.

CompareValidator control Compares the user's entry against another value. It can compare against a constant thatyou specify at design time, or against a property value of another control. It can alsocompare against a database value. The comparison must use one of the comparisonoperators such as less than, equal to, greater than, etc.Thevalidator control uses the following operators: Equal NotEqual GreaterThan GreaterThanEqual LessThan LessThanEqual DataTypeCheck Each operator does a comparison between controls identified as ControlToCompare andControlToValidate. If all you want to do is to be sure they are the same or different, it doesntreally matter which control is assigned as the ControlToCompare or ControlToValidate;however, when using the other operators, you have to decide which will be the one tocompare and which the one to validate. RegularExpressionValidator control One of the most powerful validators, it compares the user's entry with a regularexpression that you provide. You can use this validator to check for valid social securitynumbers, phone numbers, passwords, and so forth. The term regular expression is a bit misleading because the expressions are anything butregular compared with natural language. For example, the regular expression: /[^ASP.NET]/ Means to match any characters except A, S, P, ., N, E, or T. It wouldmatch the lowercase version of those characters. To use those same characters as a match,just remove the caret (^) symbol.

CustomValidator control If none of these controls meets your needs, you can use the CustomValidator. This checksthe user's entry against whatever algorithm you provide in a custom method. The key property of the CustomValidator control isthe OnServerValidate event. Instead of having a built-in function to deal with thevalidation process, it passes a parameter to the C# event handler function and then codesthe outcome. For example, the ASP.NET code OnServerValidate="MyValidation" Calls the C# function MyValidation. Thats what the OnClick event does. However,you will find a key difference in the functions parameter. Instead of EventArgs, thesecond parameter type is ServerValidateEventArgs. It even requires an additionalnamespace statement: using System.Web.UI.WebControls; Once that is set up, you still need some way of handling the event generated by clickingthe button. Thats easy enough. Just add a regular event handler function the same asalways. However, when both a validation event and a button event are in an ASP.NETscript, the validation event is handled first. ValidationSummary Control The ValidationSummary control is not a control that performs validations on the content input into yourWeb forms. Instead, this control is the reporting control, which is used by the other validation controlson a page. You can use this validation control to consolidate error reporting for all the validation errorsthat occur on a page instead of leaving this up to each and every individual validation control. <asp:ValidationSummary ID="ValidationSummary1" Runat="server" ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary> You may find it rather user-friendly to have all the possible validation errors reported tothe end user in a single and easily identifiable manner. By default, the ValidationSummary control shows the list of validation errors as a bulleted list.The Text property is usedby the validation control and is not utilized at all by the ValidationSummary control.DisplayMode property of the ValidationSummary control canchange the display of the results to other types of formats. This control has the following possible values: BulletList List SingleParagraph

Building Databases
As more and more companies are coming up with n-tier client/server and Web-baseddatabase solutions, Microsoft with its Universal Data Access (UDA) model, offers highperformanceaccess to diverse data and information sources on multiple platforms. Also,UDA provides an easy-touse programming interface that works with practically any toolor language, leveraging the technical skills developers already have. The Microsoft UDA model is a collection of Data Access Components, which are the keytechnologies that enable Universal Data Access. The Data Access Components includeActiveX Data Objects (ADO), Remote Data Service (RDS), formerly known as AdvancedData Connector (ADC), Object Linking and Embedding Database (OLE DB), and OpenDatabase Connectivity (ODBC). Microsoft is targeting many more such Data Access components that offer easy-tomaintainsolutions to organizations. Such solutions are aimed at allowing organizationsuse their own choice of tools, applications, and data sources on the client, middle tier, orserver. One of the emerging components within the UDAs collection is ADO.NET. ADO.NET Basics Microsoft ADO.NET is the latest improvement after ADO. ADO.NET provides platforminteroperability and scalable data access. In the .NET Framework, data is transmitted inthe Extensible Markup Language (XML) format. Therefore, any application that can readthe XML format can process data. It is not necessary for the receiving component to bean ADO.NET component at all. The receiving component might be a Microsoft VisualStudiobased solution or any application running on any other platform. Although ADO.NET preserves some of the primary concepts from previous ADO models,it has been chiefly stretched to provide access to structured data from diverse sources.ADO.NET provides access to diverse data sources by using a consistent andstandardized programming model. ADO.NET is upgraded to offer several advantagesover previous versions of ADO and over other data access components.

ADO.NET builds the foundation of data-aware .NET applications. ADO.NET bringstogether all the classes that allow data handling. Such classes represent data containerobjects that feature typical database capabilities indexing, sorting, and views. WhileADO.NET offers a solution for .NET database applications, it presents an overallstructure that is not as database-centric as the ADO model. The ADO model uses the concept of recordsets, which are the ADO representation oftables and views from a database. Although these recordsets are very flexible to use andmajor drawback. In the case of distributed and Web applications, data needs to beexchanged among different components at different tiers, which might be running onvariety of platforms. Of course, the format of the data being exchanged should beunderstood by all components. This transmission of data requires the conversion of datatypes of values to some data types that are recognized by the receiving components.This conversion is called COM marshalling. Thus, the interoperability is limited whenusing ADO recordsets. So, the concept of ADO recordsets fails when we look at theInternet interoperability. Like ADO, ADO.NET also allows you to access data when disconnected from actual datasources. However, unlike ADO, ADO.NET uses XML as the data format. Because XMLis a universal data format being used, ADO.NET expands the boundaries ofinteroperability to the Internet. In addition, instead of recordsets, ADO.NET uses theDataSet and DataReader objects to access and manipulate data. Thus, ADO.NET is designed to perform better and bemore flexible than ADO. However, to support ADO objects, the correspondingequivalents exist in ADO.NET.

The workings of ADO.NET

Interoperability The ADO.NET model is designed to take maximum advantage of the flexibility providedby the large industry acceptance of XML. ADO.NET uses XML for transmitting datasetsamong components and across tiers. Any component that is capable of reading the XMLformat can process the data. It is not necessary for the receiving component to be anADO.NET component. The component that is sending or transmitting the dataset cansimply transmit the dataset to its destination without bothering with how the receivingcomponent is implemented. The component asking for the dataset,the destinationcomponent, can be implemented as a Visual Studio application or any other application.However, the important point to be considered is that the receiving component should becapable of accepting the XML file formatted as a dataset. Maintainability After an application is deployed, there might be a need for changes in the application.For example, the application might need substantial architectural changes to improve itsperformance. As the performance load on a deployed application server grows, systemresources can become inadequate, resulting in higher response times. As a solution tothese problems, the application might need to undergo architectural changes by addingtiers. Here, the problem is not the multitier application design, but rather the problem liesin increasing the number of tiers after an application is deployed. This transformationbecomes easier if the original application is implemented in ADO.NET using datasets. InADO.NET, the communication between tiers is relatively easy, because the tiers cantransmit data through XML-formatted datasets. Programmability The ADO.NET model uses typed programming to manipulate objects. In typedprogramming, the programming environment or programming language itself recognizesthe types of things that are important to users. To take full advantage of typedprogramming, you must know the things that are of interest to programmers and to endusers. Consider the following code using typed programming in ADO.NET:If TotalQty > DataSet1.ProductInfo("Baby Food").QtyAvailableThis code is equivalent to a line using non-typed programming and is easier to read byend users. An end user who has little or no programming experience can easily graspthe meaning of the condition being tested. Also, in non-typed programming, if thedeveloper makes a spelling mistake by chance (for example, ProductInfo is spelled asProdcutInfo), a run-time error will get generated. On the other hand, in typed datasets,errors in the syntax caused by misspellings are detected at compile time rather than atrun time. Performance In ADO, while transmitting data across tiers using COM marshalling in the form ofdisconnected RecordSets, the values must be converted to data types that arerecognized by COM. This results in poor performance. On the other hand, ADO.NET isdesigned to use disconnected data architecture, which in turn is easier to scale becauseit reduces the load on database (does not require any data type

conversions). Thus, inthe ADO.NET model, everything is handled at the client side, which in turn improvesperformance. Scalability The Web-based, data-centric applications require multiple users to access datasimultaneously. This increases the demand on data to be accessed, making scalabilityone of the most critical features. Applications that use resources, such as databaseconnections and database locks, cannot support more users to access datasimultaneously, because eventually the user demand for the limited resources willexceed their supply. Because ADO.NET uses disconnected data access, applications donot retain database locks or active database connections for long durations. Hence,ADO.NET accommodates scalability by encouraging programmers to conserve limitedresources, and allows more users to access data simultaneously. ADO.NET Object Model: The .NET Framework is designed to change dramatically the developer's current style ofdeveloping applications, including the data access features. For the .NET applications,the primary data access technology to be used would be ADO.NET the latest additionto the ADO model. The goal of ADO.NET is to provide a bridge between your objects in ASP.NET and your backend database. ADO.NET provides an objectoriented view into the database, encapsulating manyof the database properties and relationships within ADO.NET objects. Further, and in many waysmost important, the ADO.NET objects encapsulate and hide the details of database access; yourobjects can interact with ADO.NET objects without knowing or worrying about the details of howthe data is moved to and from the database. The ADO.NET Object Model is primarily divided into two levels: Connected Layer: Consists of the classes that comprise the ManagedProviders Disconnected Layer: Is rooted in the DataSet Managed Providers Managed Providers are a collection of classes in the .NET Framework that provide afoundation for the ADO.NET programming model. The .NET Framework allows you towrite language-neutral components, which can be called from any language, such asC++ or Visual Basic. In the .NET Framework, the OLE DB and ADO layers are mergedinto one layer. This results in high performance, and at the same time allowscomponents to be called from any language. The Managed Data Providers includeclasses that can be used for the following: Accessing data from SQL Server 7.0 and later Accessing the other OLE DB providers The Managed Provider for ADO.NET is the System.Data.OleDb namespace, whichallows you to access OLE DB data sources. This namespace includes classes that areused to connect to OLE DB data sources and execute database queries to access andmanipulate data. The Managed Provider for the ADO.NET classes to access and manipulate data storedon a SQL Server is the System.Data.SqlClient namespace.

DataSet class The DataSet comprises the Disconnected Layer of ADO.NET. The DataSet consists of alocal buffer of tables and relations. The DataSet object modelconsists of Tables, Columns, Relations, Constraints, and Rows. A DataSet contains acollection of DataTables (the Tables collection). A DataTable represents one table of inmemorydata. A DataTable consists of the following: A collection of columns (the Columns collection) that represents the table's schema. A collection of rows (the Rows collection) that represent the data held by the table. A DataTable remembers the original state along with the current state, tracking the kindsof changes that have occurred. The data access classes are included in theSystem.Data namespace.

The DataSet object model Class DataSet Description Represents acomplete collectionof tables,relationships, andconstraints. BoththeSystem.Data.OleDb and the System.Data.SqlClient namespacesshare this object of ADO.NET, makingit the corecomponent of the ADO.NET architecture.The keyclass is the DataSet, which is located in the System.Data namespace.The dataset represents a rich subset of the entire database, cached on your machine without acontinuous connection to the database. Periodically, you'll reconnect the dataset to its parentdatabase, and update the database with changes to the

DataAdapter

DataTable

dataset that you've made, and update thedataset with changes in the database made by other processes.The dataset captures not just a few rows from a single table, but represents a set of tables with allthe metadata necessary to represent the relationships and constraints among the tables recorded inthe original database. The dataset is comprised of DataTable objects as well as DataRelation objects. These are accessedas properties of the DataSet object. Represents adatabase query orstored procedurethat is used topopulate theDataSet object. Rather than tie the DataSet object too closely to your database architecture, ADO.NET uses aDataAdapter object to mediate between the DataSet object and the database. This decouples thedataset from the database, and allows a single dataset to represent more than one database or otherdata source. ASP.NET provides two different versions of the DataAdapter object; one foruse with SQL Server, and the other for use with other OLE DB providers. If you are connecting toan SQL Server database you will increase the performance of your application by usingSqlDataAdapter (from System.Data.SqlClient) along with SqlCommand andSqlConnection. Ifyou are using another database, you will use OleDbDataAdapter (from System.Data.OleDb) alongwith OleDbCommand and OleDbConnection. Represents a datasource that storesdata in row and column format.The DataSet object's Tables property returns a DataTableCollection collection, which in turncontains all the DataTable objects in the dataset. For example, the following line of code creates areference to the first DataTable in the Tables collection of a DataSet object named myDataSet. DataTable dataTable = myDataSet.Tables[0]; The DataTable has a number of public properties, including the Columns property, which returnsthe ColumnsCollection object, which in turn consists of DataColumn objects. Each DataColumnobject represents a column in a table. The DataRelation property returns a DataRelationCollection object, which contains DataRelationobjects. Each DataRelation object represents a relationship between two tables, throughDataColumn objects. Represents acolumn in a DataTable. Represents a rowin a DataTable. The Rows collection returns a set of rows for any given table. You use this collection to examinethe results of queries against the database, iterating through the rows to examine each record inturn. Programmers experienced with classic ADO may be confused by the absence of the RecordSet, with its moveNext and movePrevious commands. With ADO.NET youdo not iterate through the dataset; instead you access the table you need, and then you can iterate through the rows collection, typically with a foreach loop. The DBConnection object represents a connection to a data source. This connection may beshared among different

DataColumn

DataRow

DBCommand and

command objects.The DBCommand object allows you to send a command (typically an SQL statement or the nameof a stored DBConnection procedure) to the database. Often DBCommand objects are implicitly created whenyou create your dataset, but you can explicitly access these objects An alternative to the dataset is the DataReader object. The DataReader provides connectedforward-only access to a recordset returned by executing an SQL statement or a stored procedure.DataReaders are light-weight objects Data Reader ideally suited for filling a web page with data and thenbreaking the connection to the back-end database. Like DataAdapter, the DataReader class comes in two flavors:SqlDataReader for use with SQL Server and OleDbDataReader for use with other databases. You use DataBound controls to generate your applicationsuser interface for working with data. The DataBoundcontrols can be used to display and edit database data, XMLdata, or just about any other type of data you can imagine.There are three main types of DataBound controls: listcontrols, tabular DataBound controls, and hierarchical DataBound controls. List controls are used to display simple option lists.All five controls inherit from the same base ListControl class. This means that all thesecontrols share a core set of properties and methods. The ASP.NET 3.5 Framework includes thefollowing five List controls: BulletedList Displays a bulleted list of items. Each item can be displayed astext, a link button, or a hyperlink. CheckBoxListDisplays a list of check boxes. Multiple check boxes in the list canbe selected. DropDownListDisplays a drop-down list. Only one item in the dropdown list canbe selected. ListBoxDisplays a list box. You can configure this control so that only one itemin the list can be selected or multiple items can be selected. RadioButtonListDisplays a list of radio buttons. Only one radio button can beselected. The tabular DataBound controls are the main set of controls that you use when workingwith database data. These controls enable you to display and, in some cases, modify dataretrieved from a database or other type of data source.There are six tabular DataBound controls. These controls can be divided into two types:those that display multiple data items at a time and those that display a single data item at a time. First, you can use any of the following controls to display a set of data items: GridViewDisplays a set of data items in an HTML table. For example, you can usethe GridView control to display all the records

contained in the Movies databasetable. This control enables you to display, sort, page, select, and edit data. DataListDisplays a set of data items in an HTML table. Unlike the GridViewcontrol, more than one data item can be displayed in a single row. RepeaterDisplays a set of data items using a template. Unlike the GridView andDataList controls, a Repeater control does not automatically render an HTML table. ListViewDisplays a set of data items using a template. Unlike the Repeater control,the ListView control supports sorting, paging, and editing database data. You can use either of the following two controls to display a single data item at a time: DetailsViewDisplays a single data item in an HTML table. For example, you canuse the DetailsView control to display a single record from the Movies databasetable. This control enables you to display, page, edit, and add data. FormViewUses a template to display a single data item. Unlike the DetailsView, aFormView enables you to layout a form by using templates. A hierarchical DataBound control can be used to display nested data items. For example,you can use hierarchical DataBound controls to display the folder and page structure ofyour website, the contents of an XML file, or a set of master/detail database records.The ASP.NET 3.5 Framework includes two hierarchical DataBound controls: MenuDisplays data items in a static or dynamic menu. TreeViewDisplays data items in a tree.

The DataGrid Control The problem with pre-designed user controls is typically that they are either simple and thereforetoo limited to do what you want, or they are powerful and therefore so complex that they are verydifficult to learn. The DataGrid control attempts to overcome both of these constraints. Creating asimple DataGrid control couldn't be much easier, yet there is enough power and complexity tokeep you quite busy tweaking and modifying the control to do exactly what you want. DataSource Controls You bind a DataBound control to a DataSource control. A DataSource control is used torepresent a particular type of data.The ASP.NET 3.5 Framework includes the following six DataSource controls: SqlDataSourceRepresents data retrieved from a SQL relational database, includingMicrosoft SQL Server, Oracle, or DB2.Provides access to any data source that has an ADO.NET DataProvider available; by default, the control has access to the ODBC,OLE DB, SQL Server, Oracle, and SQL Server CE providers.

LinqDataSourceRepresents a LINQ to SQL query.Provides access to different types of data objects using LINQ queries.

AccessDataSourceRepresents data retrieved from a Microsoft Access database. ObjectDataSourceRepresents data retrieved from a business object. Provides specialized data access to business objects or other classes that return data. XmlDataSourceRepresents data retrieved from an XML document. Provides specialized data access to XML documents, either physically or in-memory.

SiteMapDataSourceRepresents data retrieved from a Site Map Provider. A SiteMap Provider represents the page and folder structure of a website. control Provides specialized access to site map data for a Web site that is stored by the site map provider. The ASP.NET Framework contains two basic types of DataSource controls. TheSqlDataSource, AccessDataSource, LinqDataSource, and ObjectDataSource controls allderive from the base DataSourceControl class. These controls can be used to representtabular data. The XmlDataSource and SiteMapDataSource controls, on the other hand,derive from the base HierarchicalDataSourceControl control. These two controls can beused to represent both tabular and hierarchical data. A DataBound control is associated with a particular data source control through itsDataSourceID property. All the data source controls are derived from the DataSourceControl class, which is derived fromControl and implements the IDataSource and IListSource interfaces. This means that although eachcontrol is designed for use with specific data sources, all data source controls share a basic set of corefunctionality. It also means that it is easy for you to create your own custom data source controls basedon the structure of your specific data sources.

STEPS TO RETRIVE DATA FROM DATABSE:


1.Created the string for the connection. The connection string is whatever string is neededto connect to the database, in the case of our example: string connectionString ="server=YourServer; uid=sa; pwd=YourPassword; database=ProgASPDotNetBugs"; 2. Created the string for the select statement, which generates a table containing bug IDsand their descriptions: string commandString ="Select BugID, Description from Bugs"; 3. Created the DataAdapter to extract the data from the SQL Server database and pass in theselection and connection strings:

SqlDataAdapter dataAdapter =new SqlDataAdapter( commandString, connectionString); 4. Created a new DataSet object: DataSet dataSet = new DataSet(); 5. Filled the dataset with the data obtained from the SQL select statement using theDataAdapter: dataAdapter.Fill(dataSet,"Bugs"); 6. Extracted the data table from the DataTableCollection object: DataTable dataTable = dataSet.Tables[0]; 7. Iterated the rows in the data table to fill the list box: foreach (DataRow dataRow in dataTable.Rows) { lbBugs.Items.Add(dataRow["BugID"] +": " + dataRow["Description"] ); }

Anda mungkin juga menyukai