Getting Started Introduction What is ASP.NET? Language Support ASP.NET Web Forms Introducing Web Forms Working with Server Controls Applying Styles to Controls Server Control Form Validation Web Forms User Controls Data Binding Server Controls Server-Side Data Access Data Access and Customization Working with Business Objects Authoring Custom Controls Web Forms Controls Reference Web Forms Syntax Reference
Welcome to the ASP.NET QuickStart Tutorial The ASP.NET QuickStart is a series of ASP.NET samples and supporting commentary designed to quickly acquaint developers with the syntax, architecture, and power of the ASP.NET Web programming framework. The QuickStart samples are designed to be short, easy-to-understand illustrations of ASP.NET features. By the time you have completed the QuickStart tutorial, you will be familiar with: ●
●
●
ASP.NET Web Services Introducing Web Services Writing a Simple Web Service Web Service Type Marshalling Using Data in Web Services Using Objects and Intrinsics The WebService Behavior HTML Pattern Matching ASP.NET Web Applications Application Overview Using the Global.asax File Managing Application State HttpHandlers and Factories Cache Services Caching Overview Page Output Caching Page Fragment Caching Page Data Caching Configuration Configuration Overview
ASP.NET Syntax. While some of the ASP.NET syntax elements will be familiar to veteran ASP developers, several are unique to the new framework. The QuickStart samples cover each element in detail. ASP.NET Architecture and Features. The QuickStart introduces the features of ASP.NET that enable developers to build interactive, world-class applications with much less time and effort than ever before. Best Practices. The QuickStart samples demonstrate the best ways to exercise the power of ASP.NET while avoiding potential pitfalls along the way.
What Level of Expertise Is Assumed in the QuickStart? If you have never developed Web pages before, the QuickStart is not for you. You should be fluent in HTML and general Web development terminology. You do not need previous ASP experience, but you should be familiar with the concepts behind interactive Web pages, including forms, scripts, and data access.
Working with the QuickStart Samples
The QuickStart samples are best experienced in the order in which they are presented. Each sample builds on concepts discussed in the preceding sample. The sequence begins with a simple form submittal and builds up to integrated application scenarios.
Copyright 2001 Microsoft Corporation. All rights reserved.
Configuration File Format Retrieving Configuration Deployment Deploying Applications Using the Process Model Handling Errors Security Security Overview Authentication & Authorization Windows-based Authentication Forms-based Authentication Authorizing Users and Roles User Account Impersonation Security and WebServices Localization Internationalization Overview Setting Culture and Encoding Localizing ASP.NET Applications Working with Resource Files Tracing Tracing Overview Trace Logging to Page Output Application-level Trace Logging Debugging The SDK Debugger Performance Performance Overview Performance Tuning Tips Measuring Performance ASP to ASP.NET Migration Migration Overview Syntax and Semantics Language Compatibility COM Interoperability Transactions Sample Applications
A Personalized Portal An E-Commerce Storefront A Class Browser Application IBuySpy.com Get URL for this page
What is ASP.NET? Getting Started Introduction What is ASP.NET? Language Support ASP.NET Web Forms Introducing Web Forms Working with Server Controls Applying Styles to Controls Server Control Form Validation Web Forms User Controls Data Binding Server Controls Server-Side Data Access Data Access and Customization Working with Business Objects Authoring Custom Controls Web Forms Controls Reference Web Forms Syntax Reference ASP.NET Web Services Introducing Web Services Writing a Simple Web Service Web Service Type Marshalling Using Data in Web Services Using Objects and Intrinsics The WebService Behavior HTML Pattern Matching
ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications. ASP.NET offers several important advantages over previous Web development models: ●
●
●
ASP.NET Web Applications Application Overview Using the Global.asax File Managing Application State HttpHandlers and Factories ●
Cache Services Caching Overview Page Output Caching Page Fragment Caching Page Data Caching Configuration Configuration Overview
Enhanced Performance. ASP.NET is compiled common language runtime code running on the server. Unlike its interpreted predecessors, ASP.NET can take advantage of early binding, just-in-time compilation, native optimization, and caching services right out of the box. This amounts to dramatically better performance before you ever write a line of code. World-Class Tool Support. The ASP.NET framework is complemented by a rich toolbox and designer in the Visual Studio integrated development environment. WYSIWYG editing, dragand-drop server controls, and automatic deployment are just a few of the features this powerful tool provides. Power and Flexibility. Because ASP.NET is based on the common language runtime, the power and flexibility of that entire platform is available to Web application developers. The .NET Framework class library, Messaging, and Data Access solutions are all seamlessly accessible from the Web. ASP.NET is also language-independent, so you can choose the language that best applies to your application or partition your application across many languages. Further, common language runtime interoperability guarantees that your existing investment in COMbased development is preserved when migrating to ASP.NET. Simplicity. ASP.NET makes it easy to perform common tasks, from simple form submission and client authentication to deployment and site configuration. For example, the ASP.NET page framework allows you to build user interfaces that cleanly separate application logic from presentation code and to handle events in a simple, Visual Basic like forms processing model. Additionally, the common language runtime simplifies development, with managed code services such as automatic reference counting and garbage collection.
Configuration File Format Retrieving Configuration
●
Deployment Deploying Applications Using the Process Model Handling Errors Security Security Overview Authentication & Authorization Windows-based Authentication Forms-based Authentication Authorizing Users and Roles User Account Impersonation Security and WebServices Localization Internationalization Overview Setting Culture and Encoding Localizing ASP.NET Applications Working with Resource Files
●
●
Tracing Tracing Overview Trace Logging to Page Output Application-level Trace Logging Debugging The SDK Debugger Performance Performance Overview Performance Tuning Tips Measuring Performance ASP to ASP.NET Migration Migration Overview Syntax and Semantics Language Compatibility COM Interoperability Transactions Sample Applications
●
Manageability. ASP.NET employs a text-based, hierarchical configuration system, which simplifies applying settings to your server environment and Web applications. Because configuration information is stored as plain text, new settings may be applied without the aid of local administration tools. This "zero local administration" philosophy extends to deploying ASP.NET Framework applications as well. An ASP.NET Framework application is deployed to a server simply by copying the necessary files to the server. No server restart is required, even to deploy or replace running compiled code. Scalability and Availability. ASP.NET has been designed with scalability in mind, with features specifically tailored to improve performance in clustered and multiprocessor environments. Further, processes are closely monitored and managed by the ASP.NET runtime, so that if one misbehaves (leaks, deadlocks), a new process can be created in its place, which helps keep your application constantly available to handle requests. Customizability and Extensibility. ASP.NET delivers a well-factored architecture that allows developers to "plug-in" their code at the appropriate level. In fact, it is possible to extend or replace any subcomponent of the ASP.NET runtime with your own custom-written component. Implementing custom authentication or state services has never been easier. Security. With built in Windows authentication and per-application configuration, you can be assured that your applications are secure.
The remainder of the QuickStart presents practical examples of these concepts.
Copyright 2001 Microsoft Corporation. All rights reserved.
Links to the Web:
Welcome
|
ASP.NET
|
Windows Forms
|
How Do I...?
Support |
Search |
microsoft.com
Hide TOC | I want my samples in...
VB
Language Support Languages Declare a variable Issue a statement Comment my code Declare a simple property Use an indexed property Declare an indexed property Declare an enumeration Enumerate a collection or array Declare and use a method Define custom attributes Declare and use an array Statically initialize a variable Write an if statement Write a case statement Write a for loop Write a while loop Handle exceptions Concatenate a string Declare an event Declare an event handler Add an event handler Cast a variable to a type Convert a variable to type Declare a class or interface Inherit from a base class Implement an interface Class with a main method Write a standard module Back to Index
The Microsoft .NET Platform currently offers built-in support for three languages: C#, Visual Basic, and JScript. The exercises and code samples in this tutorial demonstrate how to use C#, Visual Basic, and JScript to build .NET applications. For information regarding the syntax of the other languages, refer to the complete documentation for the .NET Framework SDK. The following table is provided to help you understand the code samples in this tutorial as well as the differences between the three languages:
Variable Declarations Dim x As Integer Dim s As String Dim s1, s2 As String Dim o 'Implicitly Object Dim obj As New Object() Public name As String VB
Statements Response.Write("foo") VB
Comments
Get URL for this page ' This is a comment ' ' ' ' '
This is a multiline comment
VB
Accessing Indexed Properties Dim s, value As String s = Request.QueryString("Name") value = Request.Cookies("Key").Value 'Note that default non-indexed properties 'must be explicitly named in VB
VB
Declaring Indexed Properties ' Default Indexed Property Public Default ReadOnly Property DefaultProperty(Name As String) As String Get Return CStr(lookuptable(name)) End Get End Property
VB
Declaring Simple Properties Public Property Name As String Get ... Return ... End Get Set ... = Value End Set End Property VB
Declare and Use an Enumeration ' Declare the Enumeration Public Enum MessageSize Small = 0 Medium = 1 Large = 2 End Enum ' Create a Field or Property Public MsgSize As MessageSize ' Assign to the property using the Enumeration values MsgSize = small VB
Enumerating a Collection Dim S As String For Each S In Coll ... Next VB
Declare and Use Methods
' Declare a void return function Sub VoidFunction() ... End Sub ' Declare a function that returns a value Function StringFunction() As String ... Return CStr(val) End Function ' Declare a function that takes and returns values Function ParmFunction(a As String, b As String) As String ... Return CStr(A & B) End Function ' Use the Functions VoidFunction() Dim s1 As String = StringFunction() Dim s2 As String = ParmFunction("Hello", "World!") VB
Custom Attributes ' Stand-alone attribute <STAThread> ' Attribute with parameters
' Attribute with named parameters VB
Arrays Dim a(2) As String a(0) = "1" a(1) = "2" a(2) = "3" Dim a(2,2) As String a(0,0) = "1" a(1,0) = "2" a(2,0) = "3" VB
Initialization Dim s As String = "Hello World" Dim i As Integer = 1 Dim a() As Double = { 3.00, 4.00, 5.00 } VB
If Statements
If Not (Request.QueryString = Nothing) ... End If VB
Case Statements Select Case FirstName Case "John" ... Case "Paul" ... Case "Ringo" ... Case Else ... End Select
VB
For Loops Dim I As Integer For I = 0 To 2 a(I) = "test" Next VB
While Loops Dim I As Integer I = 0 Do While I < 3 Console.WriteLine(I.ToString()) I += 1 Loop VB
Exception Handling Try ' Code that throws exceptions Catch E As OverflowException ' Catch a specific exception Catch E As Exception ' Catch the generic exceptions Finally ' Execute some cleanup code End Try VB
String Concatenation
' Using Strings Dim s1, s2 As String s2 = "hello" s2 &= " world" s1 = s2 & " !!!" ' Using StringBuilder class for performance Dim s3 As New StringBuilder() s3.Append("hello") s3.Append(" world") s3.Append(" !!!") VB
Event Handler Delegates Sub MyButton_Click(Sender As Object, E As EventArgs) ... End Sub VB
Declare Events ' Create a public event Public Event MyEvent(Sender as Object, E as EventArgs) ' Create a method for firing the event Protected Sub OnMyEvent(E As EventArgs) RaiseEvent MyEvent(Me, E) End Sub VB
Add or Remove Event Handlers to Events AddHandler Control.Change, AddressOf Me.ChangeEventHandler RemoveHandler Control.Change, AddressOf Me.ChangeEventHandler VB
Casting Dim obj As MyObject Dim iObj As IMyObject obj = Session("Some Value") iObj = CType(obj, IMyObject) VB
Conversion Dim i As Integer Dim s As String Dim d As Double
i = 3 s = i.ToString() d = CDbl(s) ' See also CDbl(...), CStr(...), ... VB
Class Definition with Inheritance Imports System Namespace MySpace Public Class Foo : Inherits Bar Dim x As Integer Public Sub New() MyBase.New() x = 4 End Sub Public Sub Add(x As Integer) Me.x = Me.x + x End Sub Overrides Public Function GetNum() As Integer Return x End Function End Class End Namespace ' vbc /out:libraryvb.dll /t:library ' library.vb VB
Implementing an Interface Public Class MyClass : Implements IEnumerable ... Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator ... End Function End Class VB
Class Definition with a Main Method Imports System Public Class ConsoleVB Public Sub New() MyBase.New() Console.WriteLine("Object Created") End Sub Public Shared Sub Main()
Console.WriteLine("Hello World") Dim cvb As New ConsoleVB End Sub End Class ' vbc /out:consolevb.exe /t:exe console.vb VB
Standard Module Imports System Public Module ConsoleVB Public Sub Main() Console.WriteLine("Hello World") End Sub End Module ' vbc /out:consolevb.exe /t:exe console.vb VB
Copyright 2001 Microsoft Corporation. All rights reserved.
Introducing Web Forms Getting Started Introduction What is ASP.NET? Language Support ASP.NET Web Forms Introducing Web Forms Working with Server Controls Applying Styles to Controls Server Control Form Validation Web Forms User Controls Data Binding Server Controls Server-Side Data Access Data Access and Customization Working with Business Objects Authoring Custom Controls Web Forms Controls Reference Web Forms Syntax Reference ASP.NET Web Services Introducing Web Services Writing a Simple Web Service Web Service Type Marshalling Using Data in Web Services Using Objects and Intrinsics The WebService Behavior HTML Pattern Matching ASP.NET Web Applications Application Overview Using the Global.asax File Managing Application State HttpHandlers and Factories Cache Services Caching Overview Page Output Caching Page Fragment Caching Page Data Caching Configuration Configuration Overview
What is ASP.NET Web Forms? Writing Your First Web Forms Page Using ASP <%%> Render Blocks Introduction to Server Controls Handling Server Control Events Using Custom Server Controls Lists, Data, and Databinding Form Validation Controls Code-Behind Web Forms Section Summary
What is ASP.NET Web Forms? The ASP.NET Web Forms page framework is a scalable common language runtime programming model that can be used on the server to dynamically generate Web pages. Intended as a logical evolution of ASP (ASP.NET provides syntax compatibility with existing pages), the ASP.NET Web Forms framework has been specifically designed to address a number of key deficiencies in the previous model. In particular, it provides: ●
●
●
The ability to create and use reusable UI controls that can encapsulate common functionality and thus reduce the amount of code that a page developer has to write. The ability for developers to cleanly structure their page logic in an orderly fashion (not "spaghetti code"). The ability for development tools to provide strong WYSIWYG design support for pages (existing ASP code is opaque to tools).
This section of the QuickStart provides a high-level code walkthrough of some key ASP.NET Web Forms features. Subsequent sections of the QuickStart drill down into more specific details.
Writing Your First Web Forms Page ASP.NET Web Forms pages are text files with an .aspx file
Configuration File Format Retrieving Configuration Deployment Deploying Applications Using the Process Model Handling Errors Security Security Overview Authentication & Authorization Windows-based Authentication Forms-based Authentication Authorizing Users and Roles User Account Impersonation Security and WebServices Localization Internationalization Overview Setting Culture and Encoding Localizing ASP.NET Applications Working with Resource Files Tracing Tracing Overview Trace Logging to Page Output Application-level Trace Logging Debugging The SDK Debugger Performance Performance Overview Performance Tuning Tips Measuring Performance ASP to ASP.NET Migration Migration Overview Syntax and Semantics Language Compatibility COM Interoperability Transactions Sample Applications
name extension. They can be deployed throughout an IIS virtual root directory tree. When a browser client requests .aspx resources, the ASP.NET runtime parses and compiles the target file into a .NET Framework class. This class can then be used to dynamically process incoming requests. (Note that the .aspx file is compiled only the first time it is accessed; the compiled type instance is then reused across multiple requests). An ASP.NET page can be created simply by taking an existing HTML file and changing its file name extension to .aspx (no modification of code is required). For example, the following sample demonstrates a simple HTML page that collects a user's name and category preference and then performs a form postback to the originating page when a button is clicked:
VB Intro1.aspx [Run Sample] | [View Source] Important: Note that nothing happens yet when you click the Lookup button. This is because the .aspx file contains only static HTML (no dynamic content). Thus, the same HTML is sent back to the client on each trip to the page, which results in a loss of the contents of the form fields (the text box and drop-down list) between requests.
Using ASP <% %> Render Blocks ASP.NET provides syntax compatibility with existing ASP pages. This includes support for <% %> code render blocks that can be intermixed with HTML content within an .aspx file. These code blocks execute in a top-down manner at page render time. The below example demonstrates how <% %> render blocks can be used to loop over an HTML block (increasing the font size each time):
A Personalized Portal An E-Commerce Storefront A Class Browser Application IBuySpy.com Get URL for this page
VB Intro2.aspx [Run Sample] | [View Source] Important: Unlike with ASP, the code used within the above <% %> blocks is actually compiled--not interpreted using a script engine. This results in improved runtime execution performance. ASP.NET page developers can utilize <% %> code blocks to dynamically modify HTML output much as they can today with ASP. For example, the following sample demonstrates how <% %> code blocks can be used to interpret results posted back from a client.
VB Intro3.aspx [Run Sample] | [View Source] Important: While <% %> code blocks provide a powerful way to custom manipulate the text output returned from an ASP.NET page, they do not provide a clean HTML programming model. As the sample above illustrates, developers using only <% %> code blocks must custom manage page state between round trips and custom interpret posted values.
Introduction to ASP.NET Server Controls In addition to (or instead of) using <% %> code blocks to program dynamic content, ASP.NET page developers can use ASP.NET server controls to program Web pages. Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a runat="server" attribute value. Intrinsic HTML tags are handled by one of the controls in the System.Web.UI.HtmlControls namespace. Any tag that doesn't explicitly map to one of the controls is assigned the type of
System.Web.UI.HtmlControls.HtmlGenericControl. The following sample uses four server controls: