Thursday, January 3, 2008

ASP.NET Web Forms
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 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:

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):

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.

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.

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(" !!!")


Event Handler Delegates

Sub MyButton_Click(Sender As Object,
E As EventArgs)
...
End Sub



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


Add or Remove Event Handlers to Events

AddHandler Control.Change, AddressOf Me.ChangeEventHandler
RemoveHandler Control.Change, AddressOf Me.ChangeEventHandler


Casting

Dim obj As MyObject
Dim iObj As IMyObject
obj = Session("Some Value")
iObj = CType(obj, IMyObject)




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(...), ...



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



Implementing an Interface

Public Class MyClass : Implements IEnumerable
...

Function IEnumerable_GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
...
End Function
End Class

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



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

Arrays
Dim a(2) As String
a(0) = "1"
a(1) = "2"
a(2) = "3"

Dim a2(2,2) As String
a(0,0) = "1"
a(1,0) = "2"
a(2,0) = "3"





Initialization

Dim s As String = "Hello World"
Dim i As Integer = 1
Dim a() As Double = { 3.00, 4.00, 5.00 }



If Statements

If Not (Request.QueryString = Nothing)
...
End If



Case Statements

Select Case FirstName
Case "John"
...
Case "Paul"
...
Case "Ringo"
...
Case Else
...
End Select




For Loops

Dim I As Integer
For I = 0 To 2
a(I) = "test"
Next


While Loops

Dim I As Integer
I = 0
Do While I < 3
Console.WriteLine(I.ToString())
I += 1
Loop


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

Asp.net Basics

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


Statements

Response.Write("foo")



Comments

' This is a comment

' This
' is
' a
' multiline
' comment


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



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



Declaring Simple Properties

Public Property Name As String

Get
...
Return ...
End Get

Set
... = Value
End Set

End Property



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



Enumerating a Collection

Dim S As String
For Each S In Coll
...
Next



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!")

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

What is ASP.NET?
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:

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, drag-and-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 COM-based 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.

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