Team LiB
Previous Section Next Section

Appendix B: Exam 70-315—Developing and Implementing Web Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET

This appendix contains information that will help you prepare for Exam 70-315, Developing and Implementing Web Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET. This is a Microsoft Certified Professional (MCP) exam, and it also provides credit for the certifications Microsoft Certified Solution Developer (MCSD), Microsoft Certified Application Developer (MCAD) for Microsoft .NET, and Microsoft Certified Database Administrator (MCDBA) on Microsoft SQL Server 2000.

Creating User Services

This section describes directives, controls, validation, and events, as well as other information related to creating user services.

Common Directives

Table B-1 shows the common directives used for developing Web applications.

Table B-1: Common Web Application Directives

Directive

Description

@Page

Defines page-specific attributes (only in .aspx)

@Control

Defines control-specific attributes (only in .ascx)

@Import

Imports a namespace

@Implements

Declares a specific interface implemented

@Register

Creates aliases

@Assembly

Links an assembly

@OutputCache

Controls the output caching

@Reference

Links a page or user control

Setting the AutoEventWireup attribute to true in the @Page directive of the page automatically associates Web page events with server-side methods.

The following code needs to be placed in the .aspx file to link a class in a codebehind page:

<%@Page Inherits="ClassName"%>

The following directive allows an ASP.NET page to access COM objects:

<@Page ASPCompat="true" >

After you have converted all COM objects to .NET, you can remove the ASPCompat attribute of the <%@Page %> directive, which will increase performance substantially.

To include a disclaimer page on every page in your Web site, you should add the following code:

<%@Register TagPrefix="MyCo" TagName=Disclaimer" Src="Disclaim.ascx" %>

Common Control Types

Table B-2 shows the common types of controls used for developing Web applications.

Table B-2: Common Web Application Controls

Control

Description

HTML control

Regular HTML control

HTML server control

HTML control with runat="server" set

Web control

A true ASP.NET control

Table B-3 compares Web user controls with Web custom controls.

Table B-3: Differences Between Web User Controls and Web Custom Controls

Web User Control

Web Custom Control

Easier to create

Harder to create

Limited support for consumers who use Visual Studio .NET and cannot be added to the toolbox

Full Visual Studio .NET support and can be inserted in the toolbox

Must be inserted in each application that uses it

There can be only one copy in the GAC

Typically used with dynamic layout

Typically used with static layout

You can load a control dynamically at runtime with the following code:

Label MyLabel = new Label();
MyLabel.Text = "Hello World";
Container1.Controls.Add(MyLabel);

If you define the following for a Web page:

<%@Register TagPrefix="MyControls" Namespace="MyNamespace" Assembly="MyAssembly"%>

you can render a control on a page with the following code:

<MyControls:CSC1 id="Control1" runat="server"/>

To properly render a control defined with the following:

<%@Register TagPrefix="UControl" Namespace="MyUserControls"
Assembly="MyControls"%>

you need the following code:

<MyControl:GridX1 id="Control1" BackColor="Color.White"

    OnMyEvent="Gx-MyEvent" runat="server" />

To create an instance of a Web control that has been defined in this way:

<%@Register TagPrefix="ABC" Namespace="ReportNS" Assembly="rptctrl" %>

do the following:

<ABC:myReport PageNumber="42" src="rptctrl" runat="server" />

This sets a property of the control to a specific value at creation of the instance of the control.

If you create a user control in an assembly defined as MyCtrl.dll, you must do the following to use it:

Using System.
Using System.Web.UI;
Namespace MyCCNamespace{
     Public class MyControl {}
}

The following code is used to reference the control described above:

<%@Register TagPrefix="CC" Namespace="MyCCNamespace" Assembly"MyCtrl.dll"%>

The IsPostBack property of a control can be used to determine if the page is being loaded for the first time. If the property is true, the page was posted back from the browser. If it is false, this is the initial creation of the page, and its default values need to be loaded.

To bind a DataGrid to a DataSource only when it is first loaded, check the Page.IsPostBack property. If the value is false, bind the data.

To add an attribute to a cell of a DataGrid , use the following:

MyCell.Attributes.Add("Class", "HighlightedCell")

By default, the DropDownList control does not post back to the server when an item is selected. You can change this by setting the AutoPostBack property to true.

You should use the AutoPostBack property of a DataList to ensure that the DataList is automatically updated when an item is selected.

The following code binds code to a DataGrid:

MyDataSet ds = new MyDataSet();
MyDataAdapter.Fill(ds);
MyDataGrid.DataSource = ds;
MyDataGrid.DataBind();

The ItemDataBound event of a DataGrid is the best place to implement custom formatting, such as color for a DataGrid.

The DayRender event of the Calendar control can be used to populate the calendar with data.

If you create a custom control that has TextBox controls in it, and you want an ASP.NET application to be able to access properties of the TextBox control, you should create a public property for each TextBox property you wish to expose.

The Literal control is the best control to use to display formatted text, because it renders the data in its Text property directly to an HTML stream.

The following code allows you to execute a client-side method called GetRegistryString prior to executing a server method called GetRate:

<input type="button" runat="server" value="eurobtn"
    onclick="getregistrystring();" onserverclick="GetRate"/>

Common Validation Controls

Table B-3 shows the common types of validation controls used in Web applications.

Table B-3: Common Validation Controls

Control

Description

RequiredFieldValidator

The field is required.

CompareValidator

The value of the field is compared against a const value or another property's value. Supported operators are less-than, equal, greater-than, and so on.

RangeValidator

The value must be between a specified lower and upper range.

RegularExpressionValidator

The value of the field must match the given regular expression.

CustomValidator

The value must comply with user-defined rules.

The CustomValidator is the only control that allows you to write custom logic.

To quickly disable server-side validation when a value in a drop-down list is changed, you should set the AutoPostBack property of the DropDownList to false.

You should use the Validate method of a validation control on a TextBox control to validate the data placed in it.

If you want to validate user data and provide descriptions beside controls and detailed descriptions at the bottom of the page, you should do the following:

  1. Set the Text property of the validation controls to a brief error.

  2. Add a ValidationSummary control to the bottom of the form.

  3. Set the ErrorMessage property of the validation control to a detailed error message.

Common Events

Table B-4 shows the common types of events used in Web applications.

Table B-4: Common Web Application Events

Event

Description

APPLICATION

Application__Start

Called when the first user visits the Web application

Application__End

Called before the Web application is disposed

Application__BeginRequest

Called at the beginning of each request

Application_EndRequest

Called at the end of each request

SESSION

Session_Start

Called every time a new user visits a Web application's first page

Session__End

Called when the user session times out

PAGE

Page__Init

Called at the beginning of processing of a page to populate server controls with their value from ViewState

Page__Load

Called when Page_Init ends

Page_PreRender

Called before rendering a page

Page_UnLoad

Called before unloading a page

Page_Error

Called if there is an untrapped error

Page_AbortTransaction

Called if a transaction is aborted

Page_CommitTransaction

Called if a transaction is committed

Page_DataBinding

Called when one or more controls is bound to a DataSource

Page_Disposed

Called when the page is next to be disposed

SERVER

Postback events

Client-side events that cause a page to be posted back to the server and result in server-side events being raised

Cache events

Client-side events that are cached in the ViewState and are processed on postback events

Validation events

Occur at both the client and server

Event handlers should be written in the Web form.

If scripting is disabled on a user's computer, this may result in server-side events not working because they rely on Java scripts.

If an AutoPostBack property is set to true for a control, a form post will take place when the controls Changed event is fired. Otherwise, Changed events do not cause a form post.

The following code snippet will activate when the index changes for a list box:

<asp: ListBox id="MyList" AutoPostBack="true"
    OnSelectedIndexChange="MyList_IndexChanged runat="server">
<asp:ListItem Value="A">Apples</asp:ListItem>
<asp:ListItem Value="B">Bannas</asp:ListItem>
<asp:ListItem Value="C">Cherries</asp:ListItem>
</asp:ListBox>

The ImageButton.OnMouseOver event can be used to change the image of the control when the mouse hovers over the image.

The following code fires an event anytime a check box is checked:

<asp:CheckBox id="MyCheck" AutoPostBack="true"
    onCheckedChanged="MyCheck_Clicked" runat="server" />

Events must be declared as public for them to be fired in a custom control class.

The ItemCommand event is raised when any custom button in a DataGrid is clicked.

When clicking the Edit button in a DataGrid, you use the EditCommand event.

The SelectionChanged event of a Calendar control can be used to determine the date picked in the control.

More User Services Notes

By saving the global.asax file, you can make changes take effect immediately for all users with the least impact on them.

The Application_OnEnd event handler of the global.asax file can be used to handle events that need to occur when the last user of a Web application closes the session.

Code that should be run before or on application startup should be written in the global.asax file in the Application_OnStart method. This method can be used to load an application with data.

The fastest way to store state information is to store it in-process.

The following are valid ways to add a value to state information:

Session["MyVal"] = 99Session.Add["MyVal"] = 99

Setting the EnableViewState property of a control to false will improve performance, but it also disables storing state information.

ASP.NET applications should store session state information in SQL Server when state data should be secure and capable of being restored after a Web server restart.

Each processor in a Web garden maintains state information separately; therefore, you must use an out-of-process solution such as a state server or SQL to store state information.

To store session state in an out-of-process component, you should modify the Web.config file in this way:

<sessionState mode="StateServer" />

By placing the DataSet in the cache and placing the name of the selected employee in the session object, you can store data specific to the user between round-trips.

By setting the Duration attribute of the @OutputCache directive in the Web user control to a smaller number, you will reduce the amount of time the control caches data.

To cache the output of a user control so that subsequent requests are pulled from the cache, use the following code:

<%@OutputCache Duration="30"VaryByParam"*" %>

The following are three ways to cache a string of data:

Cache["MyKey"] = stringValue
Cache.Add("MyKey", stringValue)
Cache.Insert("MyKey", stringValue)

The most efficient way to query a database and cache that data is to create a control that caches the data for the Web form. Be sure to use the @OutputCache directive.

To prove the identity of your site to customer, you should use the Signcode.exe tool to sign all assemblies with an Authenticode digital signature.

The following command will sign an assembly:

sn --R MyAssembly.dll MyKeys.snk

The following will allow developers to continue to work on assemblies when they do not have the private key:

<assembly:AssemblyKeyFileAttribute("PublicKey.snk")>
<assembly:AssemblyDelaySignAttribute(true)>

By using Wsdl.exe and generating a Web Service proxy, you can allow developers to begin writing code for your service before you release it.

You can use sn.exe to bypass verification of an assembly's strong name. The Vr-switch allows you to temporarily disable the strong-name functionality during testing.

If users complain that an intranet .NET Web application fails to work after Internet Explorer security settings are tightened, you should make sure that you enable JavaScript in the Local Internet Zone setting.

By reading the preferred culture from the properties of a request object, you can allow the proper language Web site to be displayed.

In developing a multilanguage and culture site, you should create a separate satellite assembly for each culture as it is created. Then place the assembly in the bin directory of its own subdirectory.

To display a pop-up window confirming a custom choice, first create a client-side function named VerifyOrder that generates a pop-up window. Then add the following code in the Web page:

<input type="Submit" runat="server" Value="
Check Out" onclick="VerifyOrder()" onserverclick="submitbutton_click"/>

For an application to communicate with a Web Service, you must do take the following steps:

  1. Use Wsdl.exe to create a proxy for the Web Service.

  2. Use the Csc.exe compiler to create an assembly from the proxy.

  3. Place the resulting assembly in the \bin directory of the Web application.

You can define a namespace using the following methods:

  • Change the root namespace in the project's Property dialog box.

  • Use the namespace {} keyword.

Creating and Managing Components in .NET Assemblies

To create an XML document in a Web page, you add a using System.Xml statement. Then create the XML document with the following:

XmlDocument doc = new XmlDocument()
System.Xml.XmlDocument X = new System.Xml.XmlDocument

All assemblies that are used in your Web application must be installed in the bin directory.

You can use Windows Installer and Gacutil to install an assembly into the GAC.

You can link your Web application to shared assemblies in the GAC by adding <add> statements to the <assemblies> section of the Web.config file. You can add an assembly to a specific Web page by adding <@Assembly> to the top of the Web form.

If you create a custom control named MyControl and compile it into an assembly called MyCtrl.dll, you can set the default properties in the control with the following code:

[ToolboxData("<{0}: MyControl BackColor='Yellow'
WarningLevel="3" runat="server"></{0}:MyControl>"]
public class MyControl

Properties of a public class that are contained in a control are referred to as subproperties . ASP.NET uses hyphenated syntax to access subproperties: object-property.

Suppose that you create a control named wucControl and add it to a form. You want to dynamically set the DataSource at runtime, so you add code such as the following to the Form_Load event:

wucControl1.DataSource=MyDataSrc;

Then you get compile errors. To fix this, you need to add the following line to the declaration of the Web form:

protected wucControl wucControl1

A Web custom control is a good choice for a preference editor that will be used by multiple Web applications.

The following code will cache RegionValue information:

<%@OutputCache Duration="30" VaryByControl="RegionValue" %>

If you are trying to create a menu that will be the same for all of your applications, a Web user control is a good choice.


Team LiB
Previous Section Next Section