Programming ASP.NET


Useful Links

www.asp.net = Official asp.net page

I refer to the book Programming ASP.NET, By Dan Hurwitz, Jesse Liberty, Publisher: O'Reilly, Pub Date: October 2005

Ch 1 .NET Framework 2.0

 

Ch 2 Visual Studio 2005

File -> New Web Site.... "ASP.NET Web Site"... Browse (File System)... Visual C#

Choosing File System causes VS2005 to run the web app using its own internal web server and not IIS. A persistent virtual directory for the web app is not created and IIS is not part of the picture. In fact, you don't even need to have IIS installed on the development machine. (Of course, IIS is required on any deployment servers.)

The downside to using File System as the Location is that web pages created this way cannot be run from a browser, only through VS2005 (since there is no virtual directory to reference after "localhost" in the browser address box). This is true even when redirecting users to another page programatically with the Response.Redirect or Server.Response methods.

(Drag)... Label... (Drag)... Button...

VS2005 took your double-click as an instruction to create an event handler for the "default" event of the button (for example).

Example001: changing a label text

Label1.Text = "Hello Visual Studio 2005";

Run the application by choosing Debug -> Start Debugging.

VS2005 will notice that you do not have debugging enabled and will offer to create a new web.config file with debugging enabled.

 

Projects and Solutions

A typical .NET web application consists of many items:

VS2005 organizes these items into a folder that represents the web site.

In addition to web sites, VS2005 can create projects.

 

Solutions

Solutions typically contain one or more projects and/or web sites.

Miscellaneous files are independent of the solution or project. "Tools -> Options -> Environment -> Documents"

Solutions are defined by a solution file, created by VS2005 and named for the solution with a .sln extension.
VS2005 also creates a .suo file with the same name as the .sln file (e.g., mySolution.sln and mySolution.suo). The .suo file contains data used to customize the IDE on a per-user and per-solution basis.
"Tools -> Options -> Projects and Solutions -> General" and change the default Visual Studio projects location.

Projects and Files

Page .....................=>.aspx
User Control..........=> .ascx
Web Service..........=> .asmx
Master Page..........=> .master

The script contained within content files can be contained in script blocks delimited by <script> tags or in-line with HTML delimited by <% %> tags. The script can be run client-side or server-side. If the script is written in JavaScript or VBScript, as indicated by a language attribute in the script block, it is sent to the browser and run client-side. If the script block contains a runat="server" attribute, then the code it contains, written in the .Net language specified in the Language attribute of the Page directive, is compiled and run server-side.

IDE

"Tools -> Customize."

 

Ch 3 Controls

4 types of web controls

ASP.NET server controls can be either declared in a content file (a page file, user control file, or master page file) similar to classic HTML elements, or they can be programmatically instantiated and manipulated in C# (or other .NET language) assemblies.

Each web page and server control is represented by a class derived from the System.Web.UI.Control class. For example, the ASP.NET Button control is represented by the Button class, and the HTML Button control is represented by the HtmlButton class.

ASP.NET is event-driven

Events are implemented with delegates. A delegate is an object that encapsulates the description of a method to which you may assign responsibility for handling the event.

Postback events cause the form to be posted back to the server immediately. These include click-type events, such as Button.Click. In contrast, many events (typically change events such as TextBox.TextChanged, or selection events, such as CheckBox.CheckedChanged) are considered non-postback because the event is not posted back to the server immediately.

The Visual Studio 2005 (VS2005) IDE can automatically handle much of the work required to implement events in ASP.NET.

When you add the control, you can see its events by clicking on the control in Design view and then clicking on the events button (the lightning bolt) in the Properties window.

A single event handler can handle events from several different controls.

ASP.NET Server Control

The primary control type used in ASP.NET is the ASP.NET server control.

Server controls may have methods and event handlers associated with them, and this code is processed on the server.

The ASP.NET server controls include all the functionality provided by HTML controls and much more. This includes basic controls such as buttons, labels, checkboxes, and tables, advanced data controls (such as data sources, lists, data grids, and grid views), validation controls, security and login controls, and rich controls (such as the Calendar, AdRotator, Menu and DynamicImage controls).

syntax:

<asp:controlType id="ControlID" runat="server" thisProperty="this value" thatProperty="that value"/>

<asp:TextBox ID="txtBookName" runat="server" Width="250px" Text="Enter a book name."/>

In addition, many ASP.NET server controls can make use of inner HTML

<asp:TextBox ID="txtBookName" runat="server" Width="250px">Enter a book name.</asp:TextBox>

Like all HTML and ASP pages, ASP.NET is generally not case-sensitive. The one glaring exception is that C# is always case-sensitive.

You can place server-side code in-line (without being wrapped within a <script> block) in a content file by enclosing the code within the <% %> characters

Example002_ServerControl

<h2>The date and time is <% =DateTime.Now.ToString( ) %>.</h2>

1. Drag a TextBox control from the Toolbox
Change the ID property to ... txtBookName etc

2. Drag a Button control from the Toolbox
Change its ID to btnBookName and its Text property to Book Name.

3. Drag a Label control onto the page.
Change its ID to lblBookName and set its Text property to blank.

Type a book name into the text box, click the button, and have that book name display as the Text property of the label.

double-click the button....

lblBookName.Text = txtBookName.Text;


Comments:

HTML
<!-- text to be commented goes in here -->

JavaScipt
// commented text follows //
/* multiline
comment */

C#
// commented text follows //
/* multiline
comment */

VS2005 and VBScript
' commented text follows a single quotation mark
REM comments can also follow the REM keyword

Transact SQL
-- commented text follows two dashes
/* multiline
comment */

XML Commenting
/// In C#, the XML comments follow three slashes.
''' In VS2005, comments follow three single quotes.

Page (.aspx) or user control (.ascx) file
These characters actually indicate server-side code, but behave as comments since they do not render unless there is valid code.
<% The comments go here. %>

ASP.NET and Browsers

ASP.NET considers browsers to be either uplevel or downlevel. Uplevel browsers support script Versions 1.2 (ECMA Script, JavaScript, JScript), Cascading Style Sheets (CSS) and HTML 4.0; typical uplevel browsers would include Internet Explorer 4.0 and later releases. Downlevel browsers, on the other hand, support only HTML 3.2.

ASP.NET can tell you which browser is being used to display the page. This information is made available via the HttpRequest.Browser property. HttpRequest.Browser returns a HttpBrowserCapabilities object whose many properties include a number of Booleans, such as whether the browser supports cookies, frames, and so forth.

Browser only sees HTML pages. Server convert controls to HTML files.


CSS Styles

Example003_CSS

Right-click ... application root in the Solution Explorer ... Add New Item.

Select ... Style Sheet ... leave the default name.

Add CSS Code

Go to the Source view of the page file. Add the following <style> element inside the <head> element.

<style>@import url(StyleSheet.css ); </style>

Set the CssClass property of the Button to button and of the Label to body.

<asp:Button ID="Button1" runat="server" Text="Button" CssClass="button"></asp:Button>
<asp:Label ID="Label1" runat="server" CssClass="body"> This is some sample text. </asp:Label>

 

HTML Server Controls

Normal HTML controls such as <h1>, <a>, and <input> are not processed by the server but are sent directly to the browser for display. Standard HTML controls can be exposed to the server and made available for server-side processing by turning them into HTML server controls.

To convert an HTML control to an HTML server control, simply add the attribute runat="server". In addition, you will probably want to add an id attribute.

<input type="text" id="BookTitle" size="40" runat="server">

2 main reasons for using HTML server controls rather than ASP.NET server controls:

Example 004 HtmlServerControls

Drag an HTML table control. Give it two columns and six rows.

Drag an HTML button. Give the button ID and runat="server" attributes.

For the first row in the table, enter the text string Name in the first column and an Input (text) control in the second column.
Give that input control an ID of txtName. The next three rows should be similar, with input controls named txtStreet, txtCity, and txtState. Leave the fifth row in the table as an empty spacer. Leave the second column in the last row empty but give it an ID of tdInnerHtml.
Be certain that all the named controls also have the runat="server" attribute as well.

Double-click the button.

string strHtml = "";
strHtml += txtName.Value + "<br/>";
strHtml += txtStreet.Value + "<br/>";
strHtml += txtCity.Value + ", " + txtState.Value;
tdInnerHtml.InnerHtml = strHtml;

rather than the traditional onClick attribute used in conventional HTML or ASP pages, the button has an onServerClick attribute


Client-Side Processing

Calling client-side code from any ASP.NET server control is possible.
In addition, the ASP.NET Button server control has a property, OnClientClick, that lets you specify client-side script to execute when the button is clicked.

Conventional and server HTML controls expose a number of events that can execute script when they are raised.

example005_ClientSideProcessing

1. Add JavaScript script block between the closing </head> tag and the opening <body> tag:

</script><script language=javascript>
function ButtonTest( )
{
alert("Button clicked - client side processing");
}

function DoChange( )
{
document.getElementById("btnSave").disabled=false;
}
</script>

2. Add the following controls to the form: an HTML button, two ASP.NET buttons, an HTML input text box, and an ASP.NET TextBox.

3. Rename the button controls, and add the attributes

<input id="btnHTML" runat=server type="button"
value="HTML Button"
onclick="javascript:ButtonTest( );"
onserverclick="btnHTML_ServerClick"/>

<asp:Button ID="btnServer" runat="server"
Text="ASP.NET Button"
OnClientClick="javascript:ButtonTest( );" />

<input id="txtHTML" type="text" runat="server"
onchange="javascript:DoChange( );" />

<asp:TextBox ID="TextBox1" runat="server"
onchange="javascript:DoChange( );"></asp:TextBox>

<asp:Button ID="btnSave" runat="server"
Text="Save" Enabled=false />

4. Double-click btnHTML

txtHTML.Value = "An HTML server control";

5. Double-click btnServer

txtHTML.Value = "An ASP.NET server control";

Initially, the Save button will be disabled (grayed out). Clicking the HTML button will cause the JavaScript function ButtonTest to execute, popping up a dialog box with the message "Button clicked - client side processing." Once that dialog is cleared, then the server-side code will run, populating the HTML input box with the string "An HTML server control." Similarly, clicking on the ASP.NET Server button will pop up the same dialog box, then populate the HTML input box with the string "An ASP.NET server control." Changing the contents of either text box and tabbing out of the text box will enable the Save button.

The ability to call client-side script from an ASP.NET server control, other than using the Button.OnClientClick property, is essentially an undocumented feature.

 

Ch 4 Basic Controls

Maybe

.....

Ch 5 Advanced Controls

Maybe

.....

Ch 6 Web Site Fundamentals

Code Behind

You can interweave content, such as HTML, text, server controls, and program code in a single file, as was done with traditional ASP. This is known, cleverly, as the single-file model.

Example06_001_SingleFile - show how to put everything in a single file.

The single-file model can produce source control nightmares and difficult-to-maintain pages. ASP.NET addresses these problems by giving developers the ability to separate the executable code from the presentation code. You write the content in a content file, and you write the program logic in the code-behind file (with a .cs or .vb extension, depending on your language choice). The term "code-behind" refers to the "code file behind the form."

Access modifiers

Moving to Another Page

There are four different ways to do this:

Server.Transfer

The TRansfer method of the HttpServerUtility class takes a URL of an .aspx or .htm page (but not .asp) as a string argument and posts back to the server. Execution of the current page is terminated and execution of the new page begins.

Server.Transfer does not verify that the current user is authorized to view the target page. If this is important for your application, you will need to use one of the other techniques.

View state will not be preserved from page to page even though view state is stored within a hidden form variable. View state is page-scoped and invalidates when transferred to another page via Server.Transfer.

Response.Redirect

The Redirect method of the HttpResponse class is the programmatic equivalent of a HyperLink. It takes a URL of an .aspx or .htm page (but not .asp) as a string argument and performs a client-side redirect without posting back to the server. Consequently, it is faster than Server.Transfer. Since it is a completely new server request, it forces complete authentication and authorization. Data can be transferred using Session or Application state.

Cross-Page Posting

A page can be submitted to the server and post directly back to another page. This is implemented via the PostBackUrl property of specific controls. It can only transfer to another .aspx page, not .asp or .htm. Controls from the previous page are available by using the Page.PreviousPage property.

Example06_003_CrossPagePostingSimple

1. Drag three Button controls, name them btnServerTransfer, btnRedirect, and btnCrossPage.

2. double-click first two buttons to give them default Click event handlers. btnCrossPage does not have any event handler code. However, for that button, set the PostBackUrl property to TargetPage.aspx.

3. enter the event handlers for first 2 buttons

Server.Transfer("TargetPage.aspx");

Response.Redirect("TargetPage.aspx");

4. add a new web page to the project and call it TargetPage.aspx. give it some text... <h1>Target Page</h1>

5. Differences:
5.1 Server.Transfer : URL - old page (post to the server)
5.2 Reponse.Redirect : URL - new page (does NOT post to the server, no server-side code can execute)
5.3 Cross-Page Posting: URL - new page (post to the server, done by setting the PostBackUrl property of the button)

Retrieving data from the previous page

You could stash cross-page data in session state (described later in this chapter), but that consumes server resources and should be used cautiously with large objects.

The Page class exposes the PreviousPage property to provide a reference to the previous page object. 2 different ways of retrieving data from this Page reference.

A strongly typed object has a very specific collection of public members, with each member being of a specific type. Under these circumstances, you could retrieve a public member of a Page, say a property called Password, of type string, with the following line of code:

string str = PreviousPage.Password;

Under normal circumstances, i.e., by default, the Page object returned by the PreviousPage property is not strongly typed.
In this case, to retrieve the contents of a control, you must use late-binding, i.e., use reflection to determine what controls are in the Page's Controls collection at runtime and find a specific control using the FindControl method of the Page. However, late-binding imposes a performance penalty, and so should be avoided if possible.

In order to strongly type the PreviousPage Page object, the content file of the target page (i.e., the page being transferred to) must have an additional directive, PreviousPageType, added at the top of the file. The PreviousPageType directive has two possible attributes, of which only one may be used at a time on a page:

TypeName: A string representing the type of the previous page

VirtualPath: A string representing the relative URL of the previous page

Example06_004_CrossPagePostingAccessingPrevious

1. Continue from the previous example. Example06_003_CrossPagePostingSimple. create a new website.

2. To default.aspx, add a DropDownList named ddlFavoriteActivity populated with a number of activities

3. Set the AutoPostback property of the DropDownList to TRue so you can see the that when the form is posted normally, it comes back to itself.

<asp:DropDownList ID="ddlFavoriteActivity" runat="server" AutoPostBack="true">
</asp:DropDownList>

4. Since the Page object returned by the PreviousPage property can only access public members, you must publicly expose ddlFavoriteActivity.

5. The best way to do this is to create in the Page class a public, read-only property of type DropDownList. To do that, edit Default.aspx.cs to add the code.

public DropDownList FavoriteActivity
{
get { return ddlFavoriteActivity; }
}

6. Modify the content page of the Target page, TargetPage.aspx, adding the code

top of page:
<%@ PreviousPageType VirtualPath="Default.aspx" %>

middle page:
Your favorite activity is <asp:Label ID="lblActivity" runat="server" Text="unknown" />

You added a PreviousPageType directive, with the VirtualPath attribute set to the URL of the original page.

7. add code to TargetPage code-behind file.

protected void Page_Load(object sender, EventArgs e)
{

if (Page.PreviousPage != null)
{
lblActivity.Text =
PreviousPage.FavoriteActivity.SelectedItem.ToString( );
}
}

If the PreviousPage property has been set, by posting the request to the server using either Server.Transfer or cross-page posting, then lblActivity will be populated by retrieving the SelectedItem property of ddlFavoriteActivity via the FavoriteActivity property.

The implication of this entire process is that any page can only be transferred to by a single other page since the previous page name is hardcoded in the PreviousPageType directive if you are to use strongly typed Page objects and the PreviousPage property. However, this is not the case. You can transfer or post from any page as long as they all have the same signature, i.e., the specific list of public members and types.

If all the pages you need to transfer from do not have the same signature, or if you cannot know at design time the name of a page to specify the types, you will have to use late-binding techniques (or, more likely, session state).

Another Example... some other day perhaps when I am free...

..................................

Ch 7 Tracing, Debugging, and Error Handling

................

Ch 8 Validation

Need to read

..................

Ch 9 Web Data Access

extract data from the database

  1. Install MS SQL Server 2005 Express (or something similar)
  2. Install MS SQL Server 2005 Management Studio, to access and management database

Example09_001_WebNorthWind (working with the Customers table in the NorthWind database)

1. rename default.aspx to Customers.aspx.

2. explicitly creating a database connection.

.................

Appendix B Relational Database - Crash Course

.....................

Ch 10 ADO.NET

Must do as it deals with insert / updat / delete inividual database records
..................

Ch 11 Form-Based Security

Need to read

.................

Ch 12 Master Pages and Navigation

.............

Ch 13 Personalization

.............

Ch 14 Custom and User Control

.............

Ch 15 Creating Web Services

.............

Ch 16 Consuming Web Services

.............

Ch 17 Caching and Performance

.............

Ch 18 Application Logic and Configuration

.............

Ch 19 Deployment

Need to read

.............