Sunteți pe pagina 1din 62

Check out these great features

at www.cramsession.com
> Discussion Boards
http://boards.cramsession.com
Your Trusted
Study Resource > Info Center
for http://infocenter.cramsession.com
Technical
Certifications > SkillDrill
http://www.skilldrill.com
Written by experts.
The most popular > Newsletters
study guides http://newsletters.cramsession.com/default.asp
on the web.
In Versatile > CramChallenge Questions
http://newsletters.cramsession.com/signup/default.asp#cramchallenge
PDF file format
> Discounts & Freebies
http://newsletters.cramsession.com/signup/ProdInfo.asp

Developing and Implementing


Web Applications with
Microsoft Visual
Basic .NET & Microsoft
Visual Studio .NET
Version 3.0.0

Notice: While every precaution has been taken in the preparation of this material, neither the author nor
Cramsession.com assumes any liability in the event of loss or damage directly or indirectly caused by any
inaccuracies or incompleteness of the material contained in this document. The information in this document
is provided and distributed "as-is", without any expressed or implied warranty. Your use of the information in
this document is solely at your own risk, and Cramsession.com cannot be held liable for any damages
incurred through the use of this material. The use of product names in this work is for information purposes
only, and does not constitute an endorsement by, or affiliation with Cramsession.com. Product names used
in this work may be registered trademarks of their manufacturers. This document is protected under US and
international copyright laws and is intended for individual, personal use only.
For more details, visit our legal page.
CRAMSESSION SINGLE USER LICENSE
This is a legal agreement between you, an individual user, and BrainBuzz.com, Inc. (BrainBuzz.com). BrainBuzz.com
provides you with the content, information, and other material associated with this CramSession study guide,
hereinafter referred to as the Content, solely under the following terms and conditions, hereinafter referred to as the
License. By accessing the Content, you agree to be bound by the terms of this License. If you do not agree to be bound
by the terms of this License, do not access, view, or use the Content. Each time you access, view, or use the Content,
you reaffirm your agreement to and understanding of this License.

1. Grant of License.
BrainBuzz.com hereby grants to you a nonexclusive, nontransferable, non-assignable, limited right and license to access, view, and use the
Content on one (1) computer or workstation at a time for your individual, personal, non-commercial use. You may further print one (1) copy
of the Content for your individual, personal, non-commercial use, but may not otherwise copy or reproduce the Content.
You may not share or allow others to view the Content. You may not network the Content or display or use it on more than one computer or
workstation at the same time. You may not upload, post, transmit, or distribute printed or electronic versions of the Content in any manner
to any other party. You may not sell, rent, lease, lend, sublicense, or otherwise transfer or distribute the Content to any other party. You
may not modify or create a derivative work based on the Content. You may not modify or delete any proprietary notices contained in the
Content, including, but not limited to, any product identification, product restriction, trademark, copyright, or other proprietary notices.

2. Term of License.
In the event that you are in breach of any provision of this License, this License shall thereby be automatically terminated with no further
action required by BrainBuzz.com. In the event of such termination, you agree to immediately destroy all printed and electronic versions of
the Content in your possession, custody, or control.

3. Ownership.
The Content is the proprietary product of BrainBuzz.com and is protected by copyright, trade secret, and other intellectual property laws.
You are acquiring only the right to access, view, and use the Content as expressly provided above. BrainBuzz.com now holds and shall
retain all right, title, and interest in and to the Content, including, but not limited to, all copyrights, patent rights, trade secret rights,
trademark rights, and other similar property rights with respect to the Content. Upon termination of this License, you shall retain no rights of
any nature with respect to the Content.

4. Limited Warranty and Limited Liability.


YOU EXPRESSLY ACKNOWLEDGE AND AGREE THAT USE OF THE CONTENT IS AT YOUR OWN RISK AND THAT
BRAINBUZZ.COM PROVIDES, AND YOU ACCEPT, THE CONTENT AS IS WITHOUT ANY WARRANTIES, CONDITIONS, OR
REPRESENTATIONS WHATSOEVER; AND BRAINBUZZ.COM DISCLAIMS ANY AND ALL WARRANTIES, CONDITIONS, AND
REPRESENTATIONS (STATUTORY, EXPRESS, OR IMPLIED, ORAL OR WRITTEN), WITH RESPECT TO THE CONTENT,
INCLUDING, BUT NOT LIMITED TO, ANY AND ALL IMPLIED WARRANTIES OR CONDITIONS OF TITLE, NONINFRINGEMENT,
MERCHANTABILITY, ACCURACY OR FITNESS OR SUITABILITY FOR ANY PARTICULAR PURPOSE (WHETHER OR NOT
BRAINBUZZ.COM KNOWS, HAS REASON TO KNOW, HAS BEEN ADVISED, OR IS OTHERWISE IN FACT AWARE OF ANY SUCH
PURPOSE), WHETHER ALLEGED TO ARISE BY LAW, BY REASON OF CUSTOM OR USAGE IN THE TRADE, OR BY COURSE OF
DEALING. BRAINBUZZ.COM DOES NOT WARRANT THAT THE CONTENT WILL MEET YOUR REQUIREMENTS. SOME STATES OR
COUNTRIES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO CERTAIN OF THE ABOVE EXCLUSIONS MAY NOT
APPLY.
BRAINBUZZ.COM SHALL NOT BE LIABLE TO YOU UNDER ANY CIRCUMSTANCES FOR ANY DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA, OR DATA
USE, INCURRED BY YOU ARISING OUT OF OR RELATED TO THE USE OF OR INABILITY TO USE THE CONTENT, WHETHER IN
AN ACTION IN CONTRACT OR TORT, EVEN IF BRAINBUZZ.COM HAS BEEN ADVISED OR IS AWARE OF THE POSSIBILITY OF
SUCH DAMAGES. BRAINBUZZ.COMS LIABILITY FOR DAMAGES SHALL IN NO EVENT EXCEED THE FEES PAID BY YOU FOR THIS
LICENSE.
The Content may be subject to export restrictions. You agree that you will not export the Content or any part thereof to any country, person,
entity, or end user subject to U.S. export restrictions. You expressly agree not to export any part of the Content to any country to which the
U.S. has embargoed or restricted the export of goods or services, or to any national who intends to export the Content back to any
embargoed country. You warrant and represent that no U.S. federal agency has suspended, revoked, or denied your export privileges.
BrainBuzz.com may use fictitious names of companies, products, and individuals in the Content. These fictitious names are not intended to
represent any real companies, products, or individuals.
BrainBuzz.com may use real product names in the Content for informational purposes only. By using these product names, BrainBuzz.com
does not imply any endorsement of or affiliation with these products or their manufacturers. Some product names may be registered
trademarks of their owners.

The Content contains links that may take you to other third-party web sites, pages, or services not under BrainBuzz.coms control.
BrainBuzz.com provides these links on its web site only as a convenience to you. BrainBuzz.com is not responsible for content of these
third party offerings. You should not infer that BrainBuzz.com endorses the content accessible through these links in any way.

5. Applicable Law.
This agreement shall be governed in its construction, interpretation, and performance by the laws of the State of Florida, without reference
to law pertaining to choice of laws or conflict of laws. In the event of any claim or dispute arising out of or relating to this agreement or the
breach, termination, validity, or enforcement of this agreement, venue shall be exclusively in Pinellas County, Florida.
PLEASE READ CAREFULLY. THE FOLLOWING LIMITS SOME OF YOUR RIGHTS, INCLUDING THE RIGHT TO BRING A LAWSUIT IN
COURT. By accepting this agreement, you and BrainBuzz.com agree that all claims or disputes between us will be submitted to binding
arbitration if demanded by either party. The arbitration will be handled by the American Arbitration Association and governed by its rules.
This agreement requiring arbitration (if demanded) is still fully binding even if a class action is filed in which you would be a class
representative or member. You and BrainBuzz.com agree that the arbitration of any claim or dispute between the parties will be conducted
apart from all other claims or disputes of other parties and that there will be no class or consolidated arbitration of any claim or dispute
covered by this agreement. You and BrainBuzz.com also agree that this agreement does not affect the applicability of any statute of
limitations.

6. Waiver.
No failure or delay on the part of BrainBuzz.com in exercising any right or remedy with respect to a breach of this agreement by you shall
operate as a waiver thereof or of any prior or subsequent breach of this agreement by you, nor shall the exercise of any such right or
remedy preclude any other or future exercise thereof or exercise of any other right or remedy in connection with this agreement. Any waiver
must be in writing and signed by BrainBuzz.com.
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Developing and Implementing


Web Applications with
Microsoft Visual Basic .NET and
Microsoft Visual Studio .NET
Version 3.0.0

Abstract:
This study guide will help you prepare for Microsoft exam 70-305,
Developing and Implementing Web Applications with Microsoft Visual
Basic .NET and Microsoft Visual Studio .Net. Exam topics include:
Creating User Services; Creating and Managing Components and .NET
Assemblies; Consuming and Manipulating Data; Testing and
Debugging; Deploying a Web Application; Maintaining and Supporting
a Web Application; and Configuring and Securing a Web Application.

Find even more help here:

2003 All Rights Reserved BrainBuzz.com


05/07/2003
1
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Contents:
Creating User Services.................................................................................... 5
Create ASP.NET pages................................................................................. 5
Add and set directives on ASP.NET pages.................................................... 6
Separate user interface resources from business logic................................... 7
Add Web server controls, HTML server controls, user controls, and HTML code to
ASP.NET pages........................................................................................... 7
Set properties on controls........................................................................10
Load controls dynamically........................................................................11
Apply templates. ....................................................................................11
Set styles on ASP.NET pages by using cascading style sheets. ......................12
Implement navigation for the user interface. .................................................13
Manage the view state. ...........................................................................13
Manage data during postback events.........................................................14
Use session state to manage data across pages. .........................................14
Validate user input.....................................................................................15
Implement error handling in the user interface...............................................17
Configure custom error pages. .................................................................17
Implement Global.asax, application, page-level, and page event error handling.
...........................................................................................................18
Display and update data. ............................................................................19
Bind data to the user interface. ................................................................19
Transform and filter data .........................................................................20
Use controls to display data. ....................................................................20
Instantiate and invoke a Web service or component........................................20
Instantiate and invoke a Web service. .......................................................20
Instantiate and invoke a COM or COM+ component. ....................................22
Instantiate and invoke a .NET component. .................................................23
Call native functions by using platform invoke. ...........................................25
Implement globalization. ............................................................................25
Implement localizability for the user interface.............................................26
Convert existing encodings. .....................................................................27
Implement right-to-left and left-to-right mirroring.......................................27
Prepare culture-specific formatting............................................................27
Handle events. ..........................................................................................28
Create event handlers. ............................................................................29
Raise events. .........................................................................................30
Use and edit intrinsic objects. Intrinsic objects include response, request, session,
server, and application. ..............................................................................30
Creating and Managing Components and .NET Assemblies ..................................31
Create and modify a .NET assembly. ............................................................31
Create and implement satellite assemblies. ................................................31
Create resource-only assemblies...............................................................32

2003 All Rights Reserved BrainBuzz.com


05/07/2003
2
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Create custom controls and user controls. .....................................................32


Consuming and Manipulating Data...................................................................34
Access and manipulate data from a Microsoft SQL Server database by creating
and using ad hoc queries and stored procedures. ...........................................34
Access and manipulate data from a data store. Data stores include relational
databases, XML documents, and flat files. Methods include XML techniques and
ADO .NET. ................................................................................................35
Handle data errors. ....................................................................................40
Testing and Debugging ..................................................................................40
Create a unit test plan. ...............................................................................40
Implement tracing. ....................................................................................41
Add trace listeners and trace switches to an application. ..............................41
Display trace output................................................................................43
Debug, rework, and resolve defects in code. ..................................................45
Configure the debugging environment. ......................................................45
Create and apply debugging code to components, pages, and applications......46
Provide multicultural test data to components and applications. ....................46
Execute tests. ........................................................................................46
Resolve errors and rework code................................................................46
Deploying a Web Application...........................................................................47
Plan the deployment of a Web application. ....................................................47
Create a setup program that installs a Web application and allows for the
application to be uninstalled. .......................................................................47
Deploy a Web application. ...........................................................................48
Add assemblies to the Global Assembly Cache. ..............................................48
Maintaining and Supporting a Web Application ..................................................50
Optimize the performance of a Web application. .............................................50
Diagnose and resolve errors and issues.........................................................50
Configuring and Securing a Web Application......................................................51
Configure a Web application. .......................................................................51
Modify the Web.config file........................................................................51
Modify the Machine.config file...................................................................51
Add and modify application settings. .........................................................51
Configure security for a Web application........................................................52
Select and configure authentication type. Authentication types include
Windows Authentication, None, forms-based, Microsoft Passport, Internet
Information Services (IIS) authentication, and custom authentication. ...........52
Configure authorization. Authorization methods include file-based methods and
URL-based methods. ..................................................................................53
Configure role-based authorization............................................................53
Implement impersonation. .......................................................................54
Configure and implement caching. Caching types include output, fragment, and
data.........................................................................................................54
Use a cache object, cache directives..........................................................54

2003 All Rights Reserved BrainBuzz.com


05/07/2003
3
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Configure and implement session state in various topologies such as a Web garden
and a Web farm.........................................................................................55
Use session state within a process. ...........................................................55
Use session state with session state service. ..............................................55
Use session state with Microsoft SQL Server. ..............................................55
Install and configure server services. ............................................................56
Install and configure a Web server. ...........................................................56
Install and configure ASP.NET ..................................................................57
Install and configure Microsoft FrontPage Server Extensions. .....................57
New features of Visual Basic.NET.....................................................................57

2003 All Rights Reserved BrainBuzz.com


05/07/2003
4
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Creating User Services


Create ASP.NET pages.
To start creating a new ASP.NET Web Application written in Visual Basic .NET, you
must select the New Project button or menu command. When the New Project
Wizard appears, select Visual Basic Projects and then ASP.NET Web Applications.

Its then possible to specify the location of the project that can be on the local
computer (http://localhost/) or on another machine with IIS installed.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
5
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Add and set directives on ASP.NET pages.


Directives are used to specify settings of an ASP.NET page (.aspx) or control (.ascx).

Directives must be declared within <%@ and %> (open and close directive tags).

There are several directives:

@ Page (only in .aspx files) Defines page-specific attributes like


Language, CodeBehind, etc.

@ Control (only in .ascx files) Defines control-specific attributes.

@ Import Imports a namespace.

@ Implements Declares that a specific interface is


implemented.

@ Register Creates aliases.

@ Assembly Links an assembly.

@ OutputCache Controls the output caching.

@ Reference Links a page or a user control.

When the directive name is missing, Page is assumed for an .aspx file and Control is
assumed for an .ascx file.

Here is an example of a Page directive:

<%@ Page language="vb" Codebehind="WebForm1.aspx.vb"


AutoEventWireup="false" Inherits="Cramsession70_305.WebForm1" %>

2003 All Rights Reserved BrainBuzz.com


05/07/2003
6
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Separate user interface resources from business logic.


Code-behind is used to separate directives and page layout from the Visual Basic
code.

The HTML tags and ASP.NET directives are saved in .aspx files, and the code is saved
in .aspx.vb files.

The link between the two set of files is maintained in the Page directive (like in the
previous paragraph).

When the user loads an .aspx page, the code-behind is loaded and is compiled with
the page. This allows having two different groups of developers that work on the
project: one group designing the pages and the other group writing the code.
By default, Visual Studio.NET generates a code-behind version of every ASP.NET
page.

Add Web server controls, HTML server controls, user controls,


and HTML code to ASP.NET pages.
To add HTML code to an ASP.NET page, simply select the HTML at the bottom of the
.aspx page.

To add controls to a page, simply select the Toolbox and drag the desired control to
the design view of a page.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
7
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Here is an example of a Toolbox:

2003 All Rights Reserved BrainBuzz.com


05/07/2003
8
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

HTML server controls are typical HTML elements that have the runat attribute set to
server. This setting enables the persistence of the selections made by the user and
other interesting behaviors (that are different for each control). HTML server controls
maintain the naming used in normal HTML tags and are typically used to migrate
existing ASP or HTML pages. To convert an HTML control in an HTML server control,
simply add the attribute in the HTML view or right-click the control in design view
and select Run as Server control.

Web server controls (also called ASP.NET server controls) are similar to HTML server
controls (they also require the runat=server attribute), but they have different
names and different properties (that are coherent between different controls). Web
server controls are more than HTML controls: there are complex controls like a
calendar, the AdRotator, DataGrid, and so on.

Another difference is that Web server controls support a greater number of events.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
9
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Set properties on controls.


To set properties on controls (but also on web pages and other elements), use the
Properties Window:

Its possible to set default properties of a control by editing the control in the HTML
view. Its also possible to change or to read properties of a control in VISUAL BASIC
.NET code simply by using the dot notation (control.property).

2003 All Rights Reserved BrainBuzz.com


05/07/2003
10
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Load controls dynamically.


To dynamically create controls and to add them on a page, a container control must
be present (for example, a table can be used as a container for dynamically
generated rows). Placeholder or Panel Web server controls can be used as containers
when there are no container controls.

Here is an example of a new dynamic label added to a container called Container1:

Dim myLabel As New Label()

myLabel.Text = "Cramsession"

Container1.Controls.Add(myLabel)

Apply templates.
Templates are used to change how some of the Web server controls are rendered in
HTML. Templates consist of HTML and/or embedded server controls that are
rendered in place of the default HTML for the control.

DataList and Repeater controls require a template to display output (their default
templates are empty).

A control can have multiple templates, one for every part of the control.
Here is a list of controls that supports templates and their templates:

Repeater HeaderTemplate, FooterTemplate, ItemTemplate,


AlternatingItemTemplate, SeparatorTemplate

DataList HeaderTemplate, FooterTemplate, ItemTemplate,


AlternatingItemTemplate, SeparatorTemplate,
SelectedItemTemplate, EditItemTemplate

DataGrid HeaderTemplate, FooterTemplate, ItemTemplate


(column), EditItemTemplate (column), Pager

2003 All Rights Reserved BrainBuzz.com


05/07/2003
11
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Here is an example on how to apply, in the HTML, some templates to a DataList:

<asp:datalist ID="DataList1" runat="server">


<HeaderTemplate>

</HeaderTemplate>
<ItemTemplate>

</ItemTemplate>
</asp:datalist>

Set styles on ASP.NET pages by using cascading style sheets.


There are many options to use CSS on an ASP.NET page. The first options are like
any other HTML page with CSS:

Using <STYLE></STYLE> tags in the HEAD section of the HTML page

Importing an external CSS using <LINK REL="stylesheet"


TYPE="text/css" HREF="filename.css"> in the HEAD section of the HTML
page

Its also possible to set properties like ForeColor, BackColor, Font (Bold, Italic and so
on) on controls and have these properties rendered as a STYLE attribute if the user
browser supports it, or render in other ways (like, for example, a FONT statement) if
it doesnt support style sheets.

Composite controls can have multiple styles (for example the Calendar control can
have DayStyle, SelectedDayStyle, WeekEndDayStyle, etc., each used on different
part of the control).

Its also possible to set the CSSClass property of a control if classes were defined in
the CSS file.

The CSSStyle property is available on some controls allowing you to set style
attributes. But, if explicit properties are also declared (like ForeColor), they take
precedence.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
12
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Implement navigation for the user interface.


When a Web Form is sent to the browser its also destroyed on the server, so its not
directly possible to retain the value of the used variables.

Here are some ways to solve this problem (MSDN: Introduction to Web Forms State
Management):

Query strings This information is passed between requests and responses


as part of the Web address. Since they are visible to the user, they should not
contain secure information such as passwords.

Cookies Are used to store small amounts of information on a client. Clients


might refuse cookies, so dont rely on them.

View State - Items are stored as hidden fields on the page.

Session variables - Items that are local to the current session (single user)
can be stored in Session variables.

Application variables Are used to store items that must be available to all
users of the application.

Manage the view state.


The ViewState property (available for every control on a page and for the page itself)
is used to store the value of each control that will be restored on every posting of the
page between the client and the server.

Its also possible to store and retrieve custom information, in the form of strings.

Use ViewState("xxx")= string value to write to a particular item in the


ViewState collection. Remember that complex objects must be serialized in the form
of strings.

The value red from the ViewState collection is an object that must be converted to
the desired type.

The ViewState collection is stored in a hidden form field on the HTML page, and
requires one <form runat=server> to run.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
13
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Manage data during postback events.


When a page is loaded for the first time, it must be filled with all the default values.

When a form redirects the user on the same page, the page must retain the user
selected values.

To distinguish between these cases, the IsPostBack property of the page can be
used. If its true, the page was posted back from the browser, and so it must not be
cleared with the default values.

Use session state to manage data across pages.


Session variables can be used to maintain state information across different requests
from the client browser on a per user basis.

When a browser requests a page and a session state is enabled, the server
recognizes that the clients requesting its first page. It then raises the
Session_OnStart event and creates a session context.

Everything that is stored in session variables can be read only by pages requested
from the same browser.

If the browser doesnt requires a page before the timeout period, or the session is
explicitly closed, the Session_OnEnd event is raised and the session is closed.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
14
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Validate user input.


MSDN Web Forms Validation

Validation controls are used to validate user input in Web Forms. They allow
validating on both the server and client side (on IE 4.0 or later).

There are several validation controls:

RequiredFieldValidator The Field is required.

CompareValidator The value of the Field is compared


against a constant value, or
against a property value of
another control.
Supported operators are: less
than, equal, greater than, and so
on.

RangeValidator The value must be between


specified lower and upper
boundaries.

RegularExpressionValidator The value of the Field must match


the given regular expression.

CustomValidator The value must comply with the


users defined rules.

Simply add a validation control from the Toolbox to the Web Form (typically next to
the control that must be validated).

Every validation control has some common properties like:

ControlToValidate The control that is validated

Text Text that is displayed near the control (typically a star *)

ErrorMessage Text that can be displayed in a ValidationSummary control

2003 All Rights Reserved BrainBuzz.com


05/07/2003
15
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

There are other properties like ValidationExpression, ValueToCompare, Operator, etc.


that are specific to each validation control type.

Multiple validation rules can be applied to a single control. Validation controls are
always combined using a logical AND.

Its possible to display the error information near the control or in a specific place on
a page. The ValidationSummary control can be used to display information about
every error in the page in one place. Typically the control is put on the top or on the
bottom of the page, or where there is enough space for some lines.

Its possible to programmatically see if a condition is matched by checking the


IsValid property of a validation control, for example, in the Page Load event.

Its also possible to force a validation by calling the Validate method on a validation
control.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
16
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Implement error handling in the user interface.


In traditional languages, errors are generally reported by every single code
statement as error codes, and must be handled with if statements. This approach
tends to make the code unreadable.

VISUAL BASIC .NET, like many other object-oriented languages allows, handles
errors using exceptions.

Put the code inside a TryCatchFinallyEnd Try block:

Try

code that can generate an exception

Catch excObject as exceptionClass

(optional) code that handles the exception

Finally

(optional) code that is always executed (clean-up code)

End Try

There can be more than one catch block, from the most detailed exception to the
most general one.

Catch and finally blocks are optional, but at least one of them is needed.

Exceptions are objects derived from System.Exception. Its possible to define custom
exceptions (that derive from System.ApplicationException) or to use system
exceptions (that derive from System.SystemException).

If errors are not trapped, they are handled by the ASP.NET runtime.

Configure custom error pages.


The Web.config file can be used to configure the pages used to display custom
errors.

The <customErrors> tag can contain a defaultredirect attribute that specifies the
page that is called when there is a generic error. The mode attribute can be set to
On, forcing the redirection to the error page, or to Off, forcing a detailed

2003 All Rights Reserved BrainBuzz.com


05/07/2003
17
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

description of the error by the ASP.NET runtime. The RemoteOnly setting works
like On for remote clients and like Off for the users on the local server.

A <customErrors> tag can contain more <error> tags that must specify the
statuscode of the error (in numeric format; i.e., 404 for File Not Found) and the
redirect page.

Here is an example:

<customErrors defaultredirect="/error/generalError.aspx" mode="on">

<error statuscode="404" redirect="/error/filenotfound.aspx" />

</customErrors>

While it is possible to configure the same information in IIS, this requires editing and
deploying the IIS metabase, whereas using the web.config method only requires the
distribution of a text file.

This error handling technique works only for ASP.NET files (.aspx, .ascx, .asmx,
etc), while IIS error handling works for every file type (.htm, .gif, .jpg, etc.)

Implement Global.asax, application, page-level, and page event


error handling.
The Application_Error event handler is called when no appropriate error handler is
set at page level. Application_Error can be found in the Global.asax file, and is
called before checking the Web.config.

The <%@Page ErrorPage=errorPage.aspx%> directive is used to redirect to


an error page on a page by page basis. This is invoked before the Application_Error
and Web.config

The Page_Error event handler is called when there is an error on a page, and is
called before all the other methods.

Use the Page_Error event handler if you want to trap the error in the page that has
generated it. Use the ErrorPage directive if you want to specify an error page for a
specific page. Use the Application_Error if you want to handle errors at application
level, and use the Web.config file if you want to handle errors in a declarative way,
without writing the error handler.

Use Server.GetLastError to obtain error information.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
18
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Use Server.ClearError to prevent the error from flowing from Page_Error to the
ErrorPage directive, to the Application_Error, and then to the Web.config.

Display and update data.


In ASP.NET Web Forms, you can read data with ADO.NET from a data source and
produce HTML by writing code (like in any other environment). You can also bind
data directly to Web Forms Server controls, not only from traditional data sources
(like DataSets), but also to almost any structure that contains data like arrays,
collections, properties or other controls.

Bind data to the user interface.


You can bind single-value controls in the HTML view using a data-binding expression
<%# source %>.

For example, you bind the datafield field of the first record of the dataView to a
TextBox with the following code:

<asp:TextBox id=TextBox1 runat=server Text=<%#


dataView(0)(datafield) %>>

</asp:TextBox>

You can also use the visual designer and select the DataBindings property. From the
DataBindings dialog box, bind every property of the control to a data source.

When there are list controls on the page (Repeater, DataList, DataGrid,
CheckBoxList, and RadioButtonList), the data binding for those controls must be
specified as a whole using special data-binding properties:

The DataSource property defines the data source of the control.

The DataMember property is used to define the table of the dataset that is
mapped.

The DataKeyField property is used on DataList or DataGrid and is typically


associated to the primary key of the table.

The DataTextField is used with ListBox, DropDownList, CheckBoxList,


RadioButtonList, or HtmlSelect controls to determine which column to bind.

The DataValueField optional property is related to the previous property and


restricts which column the value of the selected item is taken from.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
19
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Transform and filter data


There are situations where data retrieved from a data source does not match with
the data type of the destination control.

Two events, Format and Parse, allow transforming the data before sending the data
to the control and vice versa.

These events also allow creating custom formats for displaying data.

The Format event is fired when the property is bound, when the Position changes, or
when the data is changed (sorted or filtered).

The Parse event is fired after the Validated event, when the Position changes, or
when the EndCurrentEdit method is called.

To filter data in a DataSet, use the Select statement or a DataView (that is a View on
the DataSet).

Use controls to display data.


To actually do the data binding, call the DataBind method of the page or of the
control (this is valid in all the previous cases).

The DataBind method is typically called only when the page is first loaded, and not
on every post back, in order to avoid overwriting the value of the control selected or
edited by the user.

Instantiate and invoke a Web service or component.


Instantiate and invoke a Web service.
To use an XML Web Service, a proxy class must be created by using the Add Web
Reference command in the Project menu of the Visual Studio.NET or by using the
WSDL.EXE command from the command line.

Using the Add Web Reference displays a form where it is possible to find Web
Services on the UDDI Registry, or by using the WSDL description of the service
directly.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
20
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

The generated proxy can be instantiated like any other class.

Dim sampleCalculator As New mssoapsampleserver.Calc()

Dim result As Double

result = sampleCalculator.Add(10,20)

The namespace, the name of the class and the name of the methods are taken from
the WSDL description of the XML Web Service.

There are a set of properties and methods that are always generated. These allow
you to control the Web Service client. For example, the Url property allows you to
change the URL of the Web Service.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
21
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Instantiate and invoke a COM or COM+ component.


From the .NET managed code, call COM and COM+ components using the Runtime
Callable Wrapper (RCW).

The RCW is created when a .NET Client loads a COM component. There is one RCW
for each COM component, ensuring that they represent a single object identity.

When the RCW is created, it reads the COM type library of the component and
exposes every interface and every method of the component.

The RCW is responsible for keeping the COM object alive as long as the RCW is not
garbage collected.

When a method is called on the RCW, it converts the parameters between .NET and
COM types and vice-versa.

Then the RCW converts the HRESULT errors (if there are any) from the COM
component in .NET exceptions, and converts results into .NET types.

To generate the RCW, use the TLBIMP.EXE command-line utility or the Visual
Studio.NET Add Reference command in the Project menu.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
22
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Instantiate and invoke a .NET component.


A .NET component is a class that implements the
System.ComponentModel.IComponent interface (directly or by deriving it from
another class that implements that interface).

The IComponent interface extends the System.IDisposable interface, which has a


method called Dispose that is called to release external resources explicitly.

When a component is created (via the new operator), the component is created in
the garbage collected heap.

When there are no more references to the component, the garbage collector marks
the component and, when the memory is needed, the finalizer is called.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
23
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

If the component holds references to some expensive resources, these resources are
taken until the component is finalized. The Dispose method can be explicitly called to
release those resources and free them.

A .NET component can be included by using the Add Reference menu of the Visual
Studio.NET or by customizing the Toolbox. Every .NET component has the RAD
support built in the Framework, without requiring other code from the developer.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
24
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Call native functions by using platform invoke.


To call functions in unmanaged code, the Declare Function or Declare Lib
statements are used.

Imports System.Runtime.InteropServices
Public Class Win32
Declare Function MessageBox Lib "user32.dll"(hWnd As Integer, _
txt As String, caption As String, Typ As Integer) As Integer
End Class

Public Class HelloWorld


Public Shared Sub Main()
Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0)
End Sub
End Class

To use the function, simply think the Declare Function as a Static method of the
containing class.

To use Declare Function, Import the namespace System.Runtime.InteropServices.

Implement globalization.
The .NET Framework supports multiple cultures and languages. The CultureInfo
class contains culture specific information like:

Language

Country/region

Calendar

Etc.

Each culture has a unique name formed by two lowercase letters, called culture code
(the language; e.g., en, it, fr, de, etc.), and optionally two uppercase letters that
specify the country or the region (e.g., IT, CH, etc.)

2003 All Rights Reserved BrainBuzz.com


05/07/2003
25
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Implement localizability for the user interface.


GOTDOTNET Localizing ASP.NET Applications
The simplest method to localize a Web user interface is the copy and translate
method.

Simply prepare several versions of the same page, each with localized content and
with the <%@Page Culture="..." %> directive.

The Culture directive allows you to change the default culture used by the page, so
its possible to format a date using <%=DateTime.Now.ToString("f", null)%> in the
localized format.

The second way is to use controls that support localization of the content. Its always
better to specify the UICulture Page directive, with the same value of the Culture
directive, because the UICulture is often used by controls to determine the
localization.

The third way is to put localization data in resource only assemblies (see later), so
when there is the need of a new language, simply add a new DLL to the web
application.

The last way is to put localization data in a database, and use this data when
required.

To set the Culture and UICulture of a page by code (for example, by matching the
users selection on the browser) the following code is required:

Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(Request.UserLanguages(0))
Thread.CurrentThread.CurrentUICulture = New
CultureInfo(Request.UserLanguages(0))

2003 All Rights Reserved BrainBuzz.com


05/07/2003
26
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Convert existing encodings.


ASP.NET pages are handled in Unicode. To specify the Encoding that the browser will
receive, use the <%@Page ResponseEncoding="..."%> directive.

If the Encoding must be set on all the files of the web application, it must be
declared in the web.config file, using the fileEncoding attribute of the
globalization element:

<globalization

fileEncoding="utf-8"
/>

Implement right-to-left and left-to-right mirroring.


To enable Right-To-Left (RTL) mirroring in web applications, simply use the DIV
HTML statement with the attribute dir=rtl surrounding the text that must be
mirrored.

This is useful for RTL languages such as Hebrew, Chinese, etc

Prepare culture-specific formatting.


MSDN Formatting for Different Cultures

Generally the ToString method is used to convert any type into a string.

There are overloaded versions of the ToString method that allow specifying the
format to use when converting the type into the string. The first method allows you
to specify a format string (like C for currency), and uses the current culture. The
other methods allow specifying an IFormatProvider derived class (like CultureInfo,
DateTimeFormatInfo and NumberFormatInfo) that can specify another cultures
information.

Public ToString(String) As String

Public ToString(IFormatProvider) As String

Public ToString(String, IFormatProvider) As String

2003 All Rights Reserved BrainBuzz.com


05/07/2003
27
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

For example, its possible to format a number using a different culture other than the
current one.

Dim MyInt As Int = 100


Dim ItalianCulture As CultureInfo = New CultureInfo("it-IT")
Dim MyString As String = MyInt.ToString("C", ItalianCulture)
Response.Write(MyString)

Handle events.
Events can occur at the application, session, page or server control level.

Application events are:

Application_Start Called when the first user visits the first page of the Web
Application

Application_End Called before the Web Application will be disposed

Application_BeginRequest Called at the beginning of each request

Application_EndRequest Called at the end of each request

Session events are:

Session_Start Called every time a new user visits its first page

Session_End Called when the timeout of a users session occurs

Page level events are:

Page_Init Called at the beginning of the processing of a page to populate


server controls with their value from the ViewState

Page_Load Called when the Page_Init is ended

Page_PreRender Called before rendering the page

Page_UnLoad Called before unloading the page

Page_Error Called if there is an untrapped error

Page_AbortTransaction Called if a transaction is aborted

2003 All Rights Reserved BrainBuzz.com


05/07/2003
28
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Page_CommitTransaction Called if a transaction is committed

Page_DataBinding Called when one or more controls are bound to a data


source

Page_Disposed Called when the page is next to be disposed

Server control events can occur on both client-side and server-side and are divided
into three categories:

Post-Back events These client-side events cause the Web page to be sent
back to the server, and then server-side events are raised.

Cached events These client-side events are cached in the ViewState and will
be processed when a Post-Back event is raised. Cached events are
immediately processed like Post-Back events if the AutoPostBack property is
set to true.

Validation events These events can occur at the client and also at the
server.

Create event handlers.


To create default event handlers, simply double click the control and the event
handler is created automatically.

To create non-default event handlers, go to the Code Editor for the aspx.vb page, go
to the top of the window, select the control from the left-hand drop-down list, then
select the event from the right-hand drop-down list.

Event handlers already created are displayed in bold.

To bind an event handler to the event by code, use AddHandler method:

2003 All Rights Reserved BrainBuzz.com


05/07/2003
29
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

AddHandler Button1.Click, AddressOf myEventHandler

A handler can be unbounded with the RemoveHandler method.

Raise events.
To raise an event server-side, simply call the event handler by invoking
control.event(sender, eventargs).

To raise a server-side event from an HTML page in the browser, a JScript code that
calls the RaisePostBackEvent method is required.

Use and edit intrinsic objects. Intrinsic objects include


response, request, session, server, and application.
The Request object (derived from the HttpRequest object) is used to read
information about the request that the browser has made. Here are the most
important properties of the object:

Browser Contains information about the browser that has required the
page, such as the major and minor version, the model, if it supports cookies,
etc.

ClientCertificates Contains all the client certificates that the browser has
sent to authenticate the client.

Cookies Contains the cookies that the browser has sent to the server.

Files Contains the files that were (eventually) uploaded by the client.

InputStream Allows the reading of raw data from the stream that the
browser has sent to the server.

QueryString Contains all the parameters that were sent on the query string
or via a GET request

Form Contains all the values that were submitted via a POST request

2003 All Rights Reserved BrainBuzz.com


05/07/2003
30
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

The Response object (derived from HttpResponse object) is used to send data to the
browser. Here is a list of its most important properties and methods:

Cache Allows controlling the caching of the page.

Cookies Allows writing cookies to the browser.

Write Allows writing directly to the output stream.

Binarywrite Allows writing binary data.

The Server object (derived from HttpServerUtility object) contains a set of utilities
that are useful when developing Web Applications, such as HtmlEncode and
HtmlDecode, UrlEncode, etc.

The Session object (derived from HttpSessionState object) contains data that are
related to a particular user, and that are accessible when that user accesses a page.
The Application object (derived from HttpApplication object) contains data that are
common for every user of the application, and that remain valid after the Web
Application is disposed.

Creating and Managing Components and .NET


Assemblies
Create and modify a .NET assembly.
Create and implement satellite assemblies.
MSDN Creating satellite assemblies

Satellite assemblies contain only resource files and no code. Satellite assemblies can
be replaced or updated without modifying the main assembly.

Satellite assemblies can be generated with Visual Studio.NET or via the Assembly
Linker (al.exe).

2003 All Rights Reserved BrainBuzz.com


05/07/2003
31
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Create resource-only assemblies.


Go to Project Menu and select Add New Item, and then choose Assembly Resource
File.

If you want to create a localized resource file, add the culture identifier (e.g., it-IT or
de-CH) to the resource name.

To use a resource, simply create a ResourceManager:

Dim resMan As New ResourceManager(Namespace.Resource,


Assembly.GetExecutingAssembly())

and then get all the information from the resource:

Response.Write(resMan.GetString("strMessage"))

If there are localized versions of the same assembly, the right one is selected.

If there isnt a correct resource file, the default one is loaded.

Create custom controls and user controls.


Web user controls are similar to Web form pages in that they can be prepared
visually using the Visual Studio designer. However, they dont offer good support for
consumers that use the Visual Studio designer.

Web custom controls are controls that are created only with code, but they offer
great support for consumers.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
32
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Here are the main differences between the two types of controls:

Web user controls Web custom controls

Easier to create (with Visual Harder to create (with code only)


Studio Designer)
Limited support for consumers Full VS.NET support, and can
who use VS.NET (that shows only also be inserted in the ToolBox
a placeholder), and cannot be
added to the VS.NET ToolBox

Must be inserted in each There can be only one copy in


application that uses it the GAC (Global Assembly
Cache)

Typically used with static layout Typically used with dynamic


layout

Creating a Web user control

Web user controls are web pages with the .ascx extension. Web user controls
cannot contain <HTML>, <BODY>, <FORM> elements, which must be
contained in the page that hosts the control.

Its possible to create them by using the HTML editor or by using the Visual
Designer, selecting the Add New Item and then selecting Web User Control.

Creating a Web custom control

Custom controls are controls that are implemented with code.

A custom control can derive from System.Web.UI.Control if it hasnt a UI, or it


can derive from System.Web.UI.WebControls.WebControl if it has a UI and
needs some properties like ForeColor, BackColor, Width, Height, BorderStyle,
Font, etc.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
33
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Consuming and Manipulating Data


Access and manipulate data from a Microsoft SQL Server
database by creating and using ad hoc queries and stored
procedures.
To access and manipulate data from a Microsoft SQL Server database, the Transact
SQL language is used.

The most important commands are:

SELECT Used to retrieve data stored into the database

INSERT Used to insert new rows into the database

UPDATE Used to change data into the database

Stored procedures are T-SQL commands stored in the database for later use.

Using stored procedures to access a SQL Server database provides these


advantages:

SQL statements are pre-compiled and execute faster

Syntax is checked at compile time, not every time

Stored Procedures remain in the cache of the database

Network traffic is low because the code is in the database

Stored Procedures can be shared between applications, allowing code reuse

Stored Procedures provide better security

2003 All Rights Reserved BrainBuzz.com


05/07/2003
34
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Access and manipulate data from a data store. Data stores


include relational databases, XML documents, and flat files.
Methods include XML techniques and ADO .NET.
ADO.NET is the preferred technique to access data in the .NET Framework.

ADO.NET supports various types of data storage:

Relational databases (SQL Server, Oracle, etc.)

Hierarchical data (XML files)

Structured data (CSV, Excel, Active Directory, etc.)

Unstructured data

ADO.NET supports two different environments:

Connected

Disconnected.

A connected environment requires a continuous connection with the data source. A


disconnected environment allows retrieving data, releasing the connection,
manipulating the data, reopening the connection and storing the data back into the
data source.

ADO.NET is composed of a series of classes, interfaces, structures and enumerations


grouped in a series of namespaces:

System.Xml

System.Data

System.Data.Common

System.Data.SqlTypes

System.Data.SqlClient

System.Data.OleDb

2003 All Rights Reserved BrainBuzz.com


05/07/2003
35
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

The last two namespaces are used to access data. The first is used to access SQL
Server 7.0 and SQL Server 2000, and the second is used for all the other OLE DB
data sources. Other data access providers (with their namespace) are coming
(ODBC, Oracle, DB2, MySql, etc.)

To access data in a connected environment, three classes are involved:

xxxConnection Used to establish a connection to a specific data source

xxxCommand Used to execute a command from a data source

xxxDataReader Used to read a forward-only, read-only stream of data

where xxx can be Sql for the SqlClient data source and OleDb for the OleDb data
source.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
36
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

A wizard helps to set up a connection to the database:

To access data in a disconnected environment, two other classes are involved:

xxxDataAdapter Uses the xxxConnection, xxxCommand and xxxDataReader


classes to populate a DataSet and to update the data source with the changes
made to the DataSet

DataSet A class that encapsulates a set of tables and their relationship.


Every operation made to the DataSet can be replicated to the data source
using the xxxDataAdapter.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
37
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

There is a wizard that helps to configure a DataAdapter:

2003 All Rights Reserved BrainBuzz.com


05/07/2003
38
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

After the data adapter is created, it can be used to obtain a DataSet with a wizard:

XML is an important part of data access, because its possible to retrieve an ADO.NET
DataSet and see it as an XML document or vice versa. Its also possible to fill a
DataSet with XML data.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
39
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Handle data errors.


ADO.NET classes throw exceptions if something goes wrong.

Every .NET data provider has an exception class:

SQLException (has an Errors collection that contains SqlError objects)

OleDbException (has an Errors collection that contains OleDbError objects)

Its important to enclose ADO.NET code in Try..Catch..Finally..End Try statements


in order to properly handle errors, and to execute the clean-up code when needed.

The xxxError object has some properties like:

Class The severity level of the error

LineNumber The line number within the SQL stored procedure or batch file

Message The text that describes the error

Number The error code

Testing and Debugging


Create a unit test plan.
With unit testing you test every unit separate from the rest of the application to
determine if it behaves as expected.

The most common approach to unit testing requires the implementation of drivers
and stubs. Drivers are used to simulate a call from another unit, whereas stubs are
used to simulate a called unit.

Implementing drivers and stubs is expensive, and sometimes unit testing is not
implemented or has a low priority in the project. This is a great mistake, because its
proven that a large percentage of bugs are identified during these kinds of tests.
Moreover, trying to discover errors across the entire application is more complicated
than finding them in every single unit.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
40
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Implement tracing.
There are two classes used to trace debugging or other information when the
program runs:

Debug Used to print debugging information when the project is built in


Debug mode.

Trace Used to print information when the program is in Release mode.


Traces can be enabled or disabled with trace switches.

Both classes share a set of methods:

Write, WriteLine They always send the information to the trace listener.

WriteIf, WriteLineIf They send the information to the trace listener if the
condition is true.

Assert Tests a condition and stops the program execution if its false

Fail Causes a termination of the program.

Add trace listeners and trace switches to an application.


Trace listeners are used to collect, store and route tracing messages.

Tracing messages can be logged, printed or stored on a file.

Listeners can be used with both Debug and Trace classes. Three types of listeners
are already implemented in the .NET Framework:

DefaultTraceListener Its the default behavior of both Trace and Debug


classes. It sends messages to OutputDebugString and calls the Debugger.Log
method (in Visual Studio.NET this sends the messages to the Output window).

In addition to this behavior, Fail and failed Assert generate a message box.

EventLogTraceListener It sends the messages to an event log.

TextWriterTraceListener It sends the messages to an instance of the


TextWriter class or to a Stream derived class.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
41
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

To add a listener to Debug or Trace classes simply create it and add it to the
Listeners collection of one of them.

Here is an example:

Dim myTraceLog As New


System.IO.FileStream("C:\\myTraceLog.txt",
System.IO.FileMode.OpenOrCreate)

Dim myListener As New TextWriterTraceListener(myTraceLog)


Trace.Listeners.Add(myListener)

Its also possible to create a Listener and use it without adding it to the Debug or
Trace classes.

Simply use the Write or WriteLine methods of the listener, but remember to call the
Flush method at the end. This is not required if the listener is added to the Listeners
collection.

Trace switches are used to enable or disable tracing. There are two types of
predefined switches:

BooleanSwitch Enables or disables tracing.

TraceSwitch Enables or disables tracing based on the level of the message


(Off, Error, Warning, Info, Verbose in increasing order). When a level is
selected, all the lower levels are selected.

Here is an example:

Dim myTraceSwitch As New TraceSwitch("MySwitch", "Description")


myTraceSwitch.Level = TraceLevel.Info
Trace.WriteLineIf(myTraceSwitch.TraceError, "Its displayed
because its lower then Info")

2003 All Rights Reserved BrainBuzz.com


05/07/2003
42
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Trace switches can also be configured with the XML configuration file using:

<system.diagnostics>

<switches>

<add name="MySwitch" value="0" />

</switches>

</system.diagnostics>

Where 0 corresponds to Off and 4 to Verbose.

Display trace output.


Trace output can also be sent to the browser using the directive <%@ Page
Trace="true"%>. Trace output can also be sorted adding the directive
TraceMode= to the previous directive.

Enabling Trace not only allows displaying information from the Trace class, but tells
the ASP.NET runtime to generate complete trace information of all the events, server
variables, cookies, etc. on the page.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
43
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

With Tracing enabled on the browser, its also possible to use the Trace.Warn
statement, which prints the trace text in red.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
44
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Debug, rework, and resolve defects in code.


Configure the debugging environment.
To set up the debugging environment use the Tool menu, Options and then go to
Debugging folder.

Most of the options are under General:

In the Edit and Continue tab you can set enable the feature for each .NET language.

Just-In-Time enables the Just-In-Time debugging.

Native enables RPC debugging and Load DLL export.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
45
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Create and apply debugging code to components, pages, and


applications.
Debug methods are the same as the Trace class.

To enable debugging on a Web application, the debug=true attribute of the


<compilation> tag in the Web.config file must be set. This enables the generation
of debugging information for the compiled pages, but slows down the execution and
then compilation of the pages.

Provide multicultural test data to components and applications.


Its very difficult to manually enter test inputs in different languages (Arabic,
Hebrew, Thai, East Asian languages, German, Greek, etc.). In some cases these
limitations that are not trivial to understand.

Its better to use a Unicode text generation utility that can generate text according to
different languages rules.

Its also very important to test how the Web application is rendered in different
cultures. English strings are generally shorter than those of any other language.

Execute tests.
Its important to have some test machines that allow testing for different
configurations. For example, if the Web application is localized, its important to test
it with a different representative user locale, like German to test Western Europe
characters, and Japanese to test East Asian characters.

Its possible to instruct the Browser to request pages in different languages.


Moreover, its very important to use multiple browsers and multiple versions of the
same browser to test how the pages are rendered on each of them.

Resolve errors and rework code.


Its very easy to modify pages and components because pages are recompiled if
changed, and DLLs are not locked in memory and can be replaced simply by
overwriting them (by using the shadow copy technique, the DLL is copied and the
copy is loaded in memory).

So modifying code is possible, even when the application is deployed and is running.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
46
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Deploying a Web Application


Plan the deployment of a Web application.
Deploy a Web application by creating a Windows Installer (.msi) file, or by copying
all the files to the appropriate directory on the target machine.

The .msi file is more practical if deploying the application using a removable media
(like CD-ROM), while copying all the files is easier on a network (for example using
FTP to deploy the application).

Create a setup program that installs a Web application and


allows for the application to be uninstalled.
Use the Web Setup Project to create a new Windows Installer file.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
47
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

You can then add files to the Web Application Folder, and to its bin subfolder. Its
also possible to add other special directories to the project.

You can check for the existence of the IIS, to edit the target machine registry, to add
components to the GAC (Global Assembly Cache), etc.

After building the solution, these files are generated:

where InstMsiA.exe, InstMsiW.exe, Setup.exe and Setup.Ini are the Windows


Installer 2.0 installation files and Setup2.msi is the Windows Installer file.

Deploy a Web application.


To deploy a Web application, run the Windows Installer file created with the Web
Setup Project. If the Web application doesnt refer to components in the GAC or
doesnt require modifications to other parts of the system, you can also use FTP or
XCOPY to deploy the application.

By simply copying the application to the appropriate directory on the target machine,
the application should run without other modifications.

You may also run different versions of the same Web application side-by-side on the
same Web server.

Add assemblies to the Global Assembly Cache.


The Global Assembly Cache (GAC) is used to store assemblies that can be shared
among many applications. It can store one or more versions of the same assembly
(side-by-side deployment).

Assemblies must have a Strong Name because of the strict naming rules used to
ensure that the correct assembly is loaded when requested.

Administrator privileges are required to install or uninstall an assembly in the GAC.


Windows Installer or the .NET Framework configuration tool (MSCORCFG.MSC) can
be used to install assemblies.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
48
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

In development environments, the GACUtil can be used for testing purposes.

GACUtils options are:

/i or i Install an assembly into the GAC

/l or l List the contents of the GAC

/u or u Uninstall one or more assemblies

The .NET installer installs a shell-extension that displays extended information about
the assemblies on the GAC in Windows Explorer:

2003 All Rights Reserved BrainBuzz.com


05/07/2003
49
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Maintaining and Supporting a Web Application


Optimize the performance of a Web application.
There are several ways to optimize the performance of a Web application:

Use caching to store and retrieve data, fragments and whole pages without
re-executing them

Optimize database queries

Use tracing to determine how much time was taken by every piece of the
page and try to optimize them

Disable sessions that arent necessary, or use the fastest state provider that
is compatible with other issues (like Web farms, reliability, etc.)

Limit the use of exceptions

Use Response.Write to concatenate strings: this is faster than using string


concatenation

Use Page.IsPostBack to avoid recalculating some parts of the page

Limit the use of server controls

Limit the use of the viewstate

Diagnose and resolve errors and issues.


Use Tracing to look at which events are executed, and use the Visual Studio
Debugger to steps into page errors.

Remember to look at HTML source that is received by the browser, because its
possible to find what doesnt work by looking at the HTML code generated by Web or
HTML controls.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
50
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Configuring and Securing a Web Application


Configure a Web application.
ASP.NET offers a simple but powerful way to configure Web applications: information
is stored in XML-based text files, and is thus editable with a simple text editor and
also while the application is running (the new settings are applied at the first page
execution). The <processModel> section is the only part that cannot be edited at
runtime. Look here for a complete list of all the available elements.

Modify the Web.config file.


There can be multiple Web.config files in each virtual directory and sub-directory.
The settings are applied in hierarchical order (from the top level directory to the sub-
directories).

Modify the Machine.config file.


The Machine.config file is used to set machine-wide settings, and is at the top of the
hierarchy.

Add and modify application settings.


Application settings can be stored in the <appSettings> section of the Web.config
file.
<configuration>

<appSettings>

<add key="myPar" value="myParValue" />

</appSettings>

</configuration>

They can be read using the ConfigurationSettings.AppSettings static string collection.


String myParameter = ConfigurationSettings.AppSettings(myPar)

2003 All Rights Reserved BrainBuzz.com


05/07/2003
51
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Configure security for a Web application.


Select and configure authentication type. Authentication types
include Windows Authentication, None, forms-based,
Microsoft Passport, Internet Information Services (IIS)
authentication, and custom authentication.
Authentication is used to identify users by using credentials like a name and a
password and validating them against an authority.

ASP.NET implements authentication through authentication providers:

Windows authentication Windows authentication is performed by


IIS in three ways: basic, digest, and
integrated.
Where Basic is supported by all the
browsers, Digest by most of them and
Integrated only by Internet Explorer.

Form authentication An HTML form is invoked to authenticate


an unknown user. If the user supplies a
valid user name and password, it can
access all the authorized resources.

Passport authentication Is a centralized authentication service


provided (on a subscription base) by
Microsoft.

To enable an authentication provider for an ASP.NET application, simply add the


<authentication> element to the Web.config file:

<authentication mode= "[Windows/Forms/Passport/None]"/>

Using mode=None allows implementing a custom authentication all by code.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
52
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Configure authorization. Authorization methods include file-


based methods and URL-based methods.
Configure role-based authorization.
Authorization is used to check if a user has access to a particular resource.

Role-based security is based on two main concepts:

Identity Normally the users log on name

Principal Roles associated with a user, like Windows users and groups or
custom roles

There are two authorization providers:

File authorization Used with Windows authentication and uses windows ACLs
to determine if a user can access a resource.

URL authorization Used with all authentication providers and maps users
and roles to pieces of the URL, giving positive and negative authorization
assertions.

Here is an example of an URL authorization:

<authorization>

<allow users="xxx"/>

<deny users="yyy" />

<deny users="?" />

</authorization>

The above must be set in the Web.config file of the specified URL path. ? and * are
special identities associated with the anonymous user and with all the users.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
53
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Implement impersonation.
Impersonation is the ability to execute an ASP.NET application with a user that is not
the client user.

Impersonation is disabled by default and must be enabled by changing the


Web.config file:

<identity impersonate="true" userName=xxx password=yyy />

Configure and implement caching. Caching types include


output, fragment, and data.
Use a cache object, cache directives.
Caching is used to increment the performance of a Web application. You may cache
an entire page or a fragment of a page or data.

To cache an entire page, the @ OutputCache directive can be used and the Duration
and VaryByParam attributes are required. The VaryByParam attribute allows caching
multiple versions of a Page.

Its also possible to use a low-level set of APIs by using the HttpCachePolicy class,
available through the HttpResponse.Cache property or from the Page.Response
property of the Page object.

Its possible to cache a fragment of a page by encapsulating it in a Web control. Then


the @ OutputCache directive can be applied to it. You may also specify the
<PartialCaching(xxx)> attribute.

To cache data, the Cache object is used. To add an element, use the Cache.Add and
Cache.Insert methods. To retrieve an item, simply use the Cache(key) notation.

The Cache object can delete some objects if doesnt have enough memory. If an
object is deleted, trying to access it returns a null pointer. Typically, its a good idea
to catch this exception and recreate the object in the cache for a later use.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
54
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Configure and implement session state in various topologies


such as a Web garden and a Web farm.
A Session state can be stored in memory, in a session state service or in SQL Server.
The first is the fastest way; the last is the most secure.

The first can be used only with one Web Server, while the others can also be used
with a Web garden and Web farm.

To configure how to store the session state, use the Web.config file.

Use session state within a process.


To store sessions in memory, simply configure the <sessionState> element in the
Web.config file with the mode=inproc attribute.

Use session state with session state service.


To use the State Service, it must be installed on the target machine with the
aspnet_estate.exe program (it is installed by the ASP.NET Premium edition in the
folder Drive:\Program Files\ASP.NET\Premium\version\ directory).

Next, the <sessionState> element in the Web.config file must include the
mode=StateServer and stateConnectionString =
tcpip=remoteServer:42424 attributes.

Use session state with Microsoft SQL Server.


To use SQL Server, configure it by running the InstallSqlState.sql script on the
server. This prepares all the tables and the stored procedures (in the ASPState
database) used to store the session state.

Next, the <sessionState> element in the Web.config file must include the
mode=SQLServer and sqlConnectionString = data source=remoteServer;
user id=xxx; password= xxx attributes.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
55
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Install and configure server services.


Install and configure a Web server.
IIS is the Web server used to host ASP.NET pages. IIS can host multiple sites on a
single computer, and multiple virtual directories on a single site.

Remember to check the following security issues:

Check Web and NTFS permissions: if they are different, the most restrictive
ones are used.

Use IP address restriction on the administration pages if you enable remote


administration

Use the most restrictive permission possible: if you use the site only for static
content, enable only the read permission; if you use ASP but no other
executables, enable Script Only permissions instead of Script and Executables

Use Write permissions with extreme caution, especially if you use ASP or
other executables, because a malicious user can upload unsafe code to the
server and then execute it.

To authenticate users, use the most secure method. Basic Authentication sends the
password in clear, but it is compatible with all the browsers. Windows Integrated and
Digest are more secure but require Internet Explorer.

You can also use certificates to authenticate users. You can map the certificate to the
user one-to-one or one-to-many. The first is most secure, but the second is easier to
implement and maintain.

Set the number of users in the performance tab according to the expected traffic on
your site. The three possibilities are fewer than 10,000, fewer than 100,000 and
more than 100,000.

For more information about configuring IIS, see:

TECHNET- Deploying IIS

2003 All Rights Reserved BrainBuzz.com


05/07/2003
56
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Install and configure ASP.NET


After the installation of IIS, the installation of the .NET Framework on the machine
enables the execution of ASP.NET pages (that arent supported by IIS alone).

While IIS (in different versions) can be installed under Windows NT4, Windows 9x,
Windows 2000, Windows XP and Windows 2003, ASP.NET can run only on Windows
2000, XP or 2003.

For more information see MSDN - ASP.NET Platform Requirements

If IIS is not installed on the local machine when the .NET Framework was installed, it
must be installed to create and test a Web Application on the local machine, and
must also be registered with the aspnet_regiis.exe command that is present in one
of the subdirectories of Microsoft.NET\Framework under the Windows directory
(WINDOWS or WINNT).

See MSDN - Error: ASP.NET Not Installed and TECHNET ASP.NET Registration Tool.

Install and configure Microsoft FrontPage Server Extensions.


FrontPage Server Extensions are a set of ISAPI filters that enable remote
administration of web sites.

The Windows Component Update CD-ROM contains FP Server Extensions, which are
also available on the Microsoft site.

To install FrontPage Server Extensions, refer to the installation guide.

New features of Visual Basic.NET


Its very important to know the differences between VB6 and VB.NET and the new
features that VB.NET has, like inheritance, overloading, multithreading, structured
exception handling and so on.

The most important thing is that Visual Basic.NET is compliant to the Common
Language Specification (CLS). These specifications are used to standardize things
like data types, objects, classes, components and so on. The compliance with these
specifications allows a Visual Basic.NET class to inherit from a C# class or from
another CLS compliant language and vice-versa.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
57
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Here are some of the new or the improved features:

Inheritance Visual Basic.NET is a full featured, object-


oriented language, which supports inheritance.
Its possible to derive a class from another, or
from a hierarchy of classes.
Derived classes inherit properties, methods and
events from the base class, but can also extend
them. Its also possible to override inherited
methods with a completely new implementation.

Overriding This is the ability for a derived class to redefine


inherited methods. The Overrides keyword is
used to define an overridden method.
MyBase.methodName is used to call the
method of the original class.

Constructors and These are methods used to initialize new


Destructors instances of a class and to release resources
when the object reference goes out of scope or is
set to Nothing (the destructor is called by the
garbage collector when it needs memory). Sub
New defines a constructor, while Sub Finalize
defines a destructor.

Overloading This is the ability to define different methods


with the same name but with different
parameters. Properties can also be overloaded.

Delegates There are objects that can call the methods of


other objects. Delegates are used to call event
handlers, or in multithreaded applications.
Delegates are described as type-safe, object-
oriented function pointers.

Multithreading With Visual Basic.NET you can perform multiple


tasks at the same time and in different threads.

Shared Members Shared properties and fields are used to store


information that is common to all the objects
created from a class, while shared methods can
be called without creating an object from that
class.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
58
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

Interfaces Interfaces are like classes, but they dont provide


implementations. A class can implement more
than one interface at the same time.

Namespaces These are like prefixes that prevent naming


conflicts by organizing classes, interfaces, and
methods into hierarchies. For example, the Form
class is in the System.Windows.Forms
namespace.

Assemblies and Assemblies are logical containers of namespaces,


References classes and so on. Assemblies can span onto exe
files or dlls.
References allow you to use objects defined in
other assemblies.

Data Types There are new or changed data types in Visual


Basic.NET, like the Char data type, the Short
data type (that is 16 bit long), the Integer data
type (that is 32 bit long), the Decimal data type,
the String data type that is changed, and the
Variant data type that is no longer available.

Exception Visual Basic.NET has the support of Structured


Handling Exception Handling. This makes it easy to handle
errors by using a Try..Catch..Finally..End Try
syntax.

Attributes These are one of the most powerful things of the


.NET Framework. They allow extending the
behavior of a class or providing additional
information that isnt required for the code itself,
but that must be stored in some format.

Default properties Visual Basic.NET doesnt allow specifying default


properties, making Set and Let statements
obsolete. This requires a lot of changes in VB
code, because VB programmers have often
abused default properties. Default properties are
allowed only on parameterized properties.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
59
Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio.NET

There are many other things and details that are changed, like Arrays that now are
always zero-based, or Forms that now are full-fledged classes. Also, many other
important aspects are changed or new, like ADO.NET, Web Services, Internet
support, and so on.

There are also a lot of changes in the Visual Studio.NET IDE, and in the debugger.
They are much more powerful than their Visual Basic 6 equivalents.

The new object-oriented features of the language require rethinking how applications
are designed, making it quite impossible to port an application without rewriting it.

Special thanks to
Lorenzo Barbieri
for contributing this Cramsession.

2003 All Rights Reserved BrainBuzz.com


05/07/2003
60

S-ar putea să vă placă și