ASP.NET Basics (part 1): Nothing But .Net

Get started with ASP.NET and the .NET Framework.

Nothing But .Net

If you're a Web programmer, you're probably already well versed with the intricacies of client-side scripting. But where there's a client, there must be a server...and where there is a server, there must be ASP.NET.

If you deal with Microsoft technologies, then you've probably already heard about .NET - it's the latest, greatest software platform to emerge from Redmond, and it promises to revolutionize the way applications work with each other. Built entirely on the premise that the Internet will serve as both the distribution medium and the basic architecture for new software applications, .NET allows applications written in different languages to talk to each other, share information and ultimately keep you more plugged-in.

It's a powerful concept...and, like all powerful concepts, it requires a fair amount of introspection to understand how it works. That's where this series of tutorials comes in - over the next few articles, I plan to bring you gently into the world of ASP.NET, providing you with theoretical explanations and code samples (lots of code samples) to help you get your feet wet with ASP.NET and learn how to leverage off it when building your next Web application.

First, though, let's start with the basics.

Checking Out The Menu

Server-side scripting is not new. It's been around for quite a while on the Web, and almost every major Web site uses some amount of server-side scripting. Amazon.com uses it to find the book you're looking for, Yahoo! uses it to store your personal preferences, and GeoCities uses it to generate page statistics. Despite this, you're probably wondering why server-side scripting is such a big deal - after all, you've probably seen what a few simple JavaScripts can do. The reason for its popularity is very simple - JavaScript runs within a client application, usually the browser, and as such can only access resources, such as the current date and time, on the client machine. Since server-side scripts run on the Web server, they can be used to access server resources such as databases, system variables and other useful thingamajigs.

Just as there are different flavors of client-side scripting, there are different languages that can be used on the server as well. Here's a quick list of some of the more popular ones:

  • In the early days of the WWW, Perl (http://www.perl.com) was the most popular language for scripting activities on the server. For the uninformed, Perl (an acronym for Practical Extraction and Report Language) is an interpreted language optimized for scanning arbitrary text files, extracting information from these files, and printing reports based on that information. While not many languages can compare with the pattern-matching capabilities of a well-written Perl script, newbies will find this language a touch intimidating when they are starting out!

  • Next up, ColdFusion, currently maintained by Macromedia (http://www.macromedia.com). ColdFusion syntax bears a remarkable resemblance to HTML, making it very easy for a budding web programmer to migrate to it. At the moment, it's available for both Windows NT and Linux. The only drawback: it ain't free!

  • Python (http://www.python.org) is an interpreted, object-oriented high-level scripting language for UNIX, often compared to Tcl, Perl or Java. It has modules, classes and interfaces to system calls, and is also extensible. It has been ported to Windows, DOS, OS/2 and the Macintosh, and has a devout following in the UNIX community.

  • One of today's most popular open-source languages for Web scripting is PHP (http://www.php.net). Very easy to use, it's free, widely available for UNIX and Windows systems, and particularly strong in the areas of database access, XML parsing and file management, and comes with large code repository of free, open-source classes in the form of the PEAR repository.

  • Active Server Pages, now aptly referred to as so-called "classic" ASP. Microsoft first introduced ASP in its IIS Web server, for the purpose of Web application programming and development. While ASP currently runs only on the Windows server platform, there have been successful attempts to port it to the UNIX platform using third party tools (such as Chilisoft ASP).

Sadly, the days of "classic" ASP are numbered. And with good reason - with ASP.NET and the much touted .NET framework, Microsoft aims to develop a "unified Web development platform that provides the services necessary for developers to build enterprise-class Web applications" (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconintroductiontoasp.asp).

In case you didn't quite understand that definition, don't worry about it - you're not the only one.

Put in plainer English, ASP.NET is a .NET-based development environment, which you can use to create distributed Web-based applications. These applications can be written in any .NET compatible language (including C#, Visual Basic.NET, and JScript.NET). While you can also use regular ASP code in your ASP.NET applications, it is far better to start from scratch (as it were) and leverage off the new .NET programming model, since that model includes a number of other benefits.

Let's take a closer look.

Building Blocks

.NET consists of a number of different subcomponents - base classes, operating system services, XML-based Web services, development tools - all conspiring and connecting with each other to create a common interface for software development. Using XML as the common language, .NET applications can run on a variety of different hardware and software configurations, and use a client-server paradigm to transfer data, execute tasks and communicate with each other in a Web environment.

Of the large number of subcomponents that make up the .NET universe, the one most relevant to this tutorial is the .NET Framework, which consists of the development tools and libraries needed to build .NET applications. This .NET Framework consists of two primary pieces:

  1. The .NET Framework classes, which provide a reusable code library that serves as the foundation for .NET development. These classes are designed to speed up development and deployment of .NET applications by providing reliable, well-tested base functions that all applications require - user interface components, input controls, a security and authentication framework, and so on.

  2. The Common Language Runtime (CLR), which provides a unified runtime environment for .NET applications. The CLR makes it possible to execute .NET applications written in a variety of different languages (including Visual Basic.NET, JScript.NET and C#) and internally takes care of many of the common headaches C programmers are always concerned about - data typing, memory management, exception handling - so as to improve the developer experience without tying a programmer to a particular language (Java programmers might find this somewhat familiar).

ASP.NET falls into the first piece of the .NET Framework, providing all the common functions (HTTP transaction management, Web forms and form processing, database access) needed by a typical Web-based application.

Putting The Pieces Together

In order to get started with ASP.NET, you're gonna need the following:

  1. An operating system which works with .NET, like Windows 2000 (Service Pack 2 or better), Windows XP Professional or Windows Server 2003.

  2. The IIS Web server 5.x or better.

  3. An Internet Web browser - Microsoft Internet Explorer 6.x is a good bet.

  4. The .NET Framework Redistributable, which contains the runtime environment and tools needed to run .NET application, and which is required if you plan to redistribute your application to other users.

  5. The .NET Framework SDK, which contains code samples, tutorials, documentation, command-line utilities, developer tools - you name it, it's all there! This SDK is critical to your .NET experience - I'll be using it over and over again throughout this tutorial.

You can download both the .NET Framework SDK and the .NET Framework Redistributable from http://www.asp.net/ or http://www.microsoft.com/net/

Installing the components above is usually a matter of clicking your way through dialog boxes and windows - you should usually have no difficulty with the installation process. In case you do, take a look at the installation documentation that ships with each components for troubleshooting information or online resource links.

Once you're all installed and ready to go, you can test your installation by opening up your browser (make sure the IIS service is running) and pointing it to http://localhost/quickstart/. If you are able to view the ASP.NET Quick Start tutorial,

it's time to pop the champagne.

Hard Choices

With the ASP.NET environment all loaded and ready for action, let's jump into some code without any further ado. Pop open your favourite text editor and copy the following lines of code into it:

<%@ Page Language="C#" %>
<html>
<head>
<title>Hello, Choice!</title>
</head>
<body>
<%
    // print some output
    Response.Write("Choice. The problem is choice.");
%>
</body>
</html>

Save the file on your hard drive as "choice.aspx" in a folder named (say) "ASPBasics". It is important to note here that all ASP.NET files must have the .aspx extension.

Next, in order to view this page via the IIS Web server, you'll need to create a so-called "virtual directory" with the Internet Service Manager application and map it to the folder above. Call this virtual directory (say) "ASPBasics" as well.

You should now be able to view the page created above by browsing to the URL http://localhost/ASPBasics/choice.aspx in your browser (in case you named the script or directory differently, or if your Web server is accessible by a name other than "localhost", you should make the appropriate changes to this URL). Here's what you should see:

Let's take a closer look at the code:

<%@ Page Language="C#" %>

This is the all-important "Page" directive, which must appear at the top of your ASP.NET program. Among other things, this directive is used to indicate the programming language used within the page. The default language for ASP.NET is VB.NET; however, I've chosen C# instead, for a number of different reasons:

  1. It's the language specially developed for the .NET Framework;

  2. It's completely object-oriented, thereby making it cleaner, easier to understand and a lot more fun to program in;

  3. For VB developers, there is no "unlearning" required (most VB programmers would have to unlearn quite a few concepts before jumping on the VB.NET bandwagon);

  4. I've always, always wanted to program in a language with a # in its name.

One way to include a block of C# code is to enclose it within <%...%> tags (similar to ASP and PHP code), like this:

<%
    ... some C# code ...
%>

You can also use the <script> element to include C# code - that's demonstrated in the next example.

So where's the C# code that I'm harping on, anyway?

<%
    // print some output
    Response.Write("Choice. The problem is choice.");
%>

As you might have guessed, this line of code simply outputs a line of text to the browser. Instead of "hello world", I decided to use a line from the latest installment of "The Matrix" trilogy. In case you haven't heard about "The Matrix"...it's a deeply-existential film about how the entire world is an illusion created by machines, humans are actually batteries powering the system, and a hero will rise to save us all from our fate. Woohoo!

OK, enough of the geek impersonation. Back to business...

Wanna have some fun? Remove the semi-colon from the end of the line in the example above and reload it in the browser. You should see the following ugly error message:

Yup, life in the .NET world is pretty rigid. But hey, it gets better from here!

Command And Control

One bane of ASP programming was the "spaghetti" style of coding, in which HTML and in-line ASP code were often fighting for space and attention. More often than not, maintaining such code was a nightmarish experience, and one best handled after a few strong cups of coffee.

ASP.NET provides a more elegant solution in the form of "server controls". Take a look:

<script language="C#" runat="server">
void Page_Load()
{
    quote.Text="Choice. The problem is choice.";
}
</script>
<html>
<head>
<title>Hello, Choice!</title>
</head>
<body>
<asp:label id="quote" runat="server" />
</body>
</html>

Save this as "label.aspx" in your "ASP101" folder and view it in your browser - you should see something like this:

The example above is much easier to read compared to the earlier one, because I've managed to separate the dynamic C# code from the static HTML tags, thereby making it easier to comprehend (and easier to maintain in the long run).

<script language="C#" runat="server">
// snip
</script>

If you're familiar with JavaScript, you already know about the <script> element, which makes it possible to embed JavaScript client-side code within an HTML file. ASP.NET takes this one step further and allows the developer to embed server-side code within an HTML page, as seen in the above code snippet.

The "runat" attribute within the <script> element, which contains the value "server", indicates that the code within the <script> element should be executed on the server and not the client. As earlier, I have to indicate the language using the "language" attribute.

Don't worry too much about the code within the <script> element at the moment, I'll be coming back to it in a moment. Instead, proceed downwards, to the second unfamiliar element in the page:

<asp:label id="quote" runat="server" />

In ASP.NET-lingo, this is called a "server control". Server controls are very similar to the regular HTML elements your normally use, with the main difference being that they are actually created at run-time on the server.

Confused? Take a look at the source code of the page generated by the example above - you'll see that ASP.NET automatically converts the server control into an equivalent <span>:

<span id="quote">...</span>

Note that the "id" attribute in the rendered version has the same name as the "id" attribute given to the server control in the ASP.NET source code. This "id" is a unique identifier that can be used to refer to the server control in your C# code...as I have done a few lines above:

<script language="C#" runat="server">
void Page_Load()
{
    quote.Text="Choice. The problem is choice.";
}
</script>

The code within the Page_Load() function is automatically executed by the Web server when the page is loaded. In this particular example, the code sets the "Text" attribute of the server control named "quote" to the line of text "Choice. The problem is choice."

When the server loads the page, it looks for a server control named "quote" within the page and, on finding it, sets its "Text" attribute to the value specified. The server control is automatically converted in an equivalent HTML element - a <span> - and the value of the "Text" attribute is written inside it.

A number of other attributes of the "label" server control are also available - drop by http://www.gotdotnet.com/quickstart/aspplus/samples/classbrowser/cs/classbrowser.aspx?namespace=System.Web.UI.WebControls for a complete list

Server controls are an important aspect of programming in ASP.NET. I'll be exploring them in-depth as we move along, I've only included the example above to give you an idea of how they can be used.

Naming Names

Let's move on to variables. Variables are the bread and butter of every programming language...and ASP.NET has them too. A variable can be thought of as a programming construct used to store both numeric and non-numeric data; this data can then be used in different places in your C# code.

The .NET Framework and all its programming languages - C#, VB.NET, Jscript.NET et al - support a number of different variable types: integers, floating point numbers, strings and arrays. Unlike some scripting languages, which can automatically determine variable type based on the data it holds, .NET languages require you to explicitly define the type of each variable before using it.

Every variable must have a name - this name is used to refer to the variable, to perform operations on it, and to retrieve the data it contains. In C#, a variable name is preceded by a keyword indicating the variable type, and must begin with a letter, optionally followed by more letters and numbers. Variable names are case-sensitive, and reserved keywords cannot be used as variable names. For example, "popeye", "one_two_three" and "bigPirateShip" are all valid variable names, while "byte" and "123" are invalid variable names.

The following example demonstrates how variables can be used in a ASP.NET document:

<script language="c#" runat="server">
void Page_Load()
{
    string name;    // define a variable as a string type
    name = "Neo";   // put some initial value into it

    whoami.Text = "I am " + name + ". Welcome to my world.";
}
</script>
<html>
<head><title>Who am I?</title></head>
<body>
<asp:label id="whoami" runat="server" />
</body>
</html>

Here's the output:

As you can see, I have first defined a variable named "name", set things up so that it will hold string data, and assigned a value ("Neo") to it. In my HTML code, I have defined a "label" server control called "whoami". In the Page_Load() function, I have used basic string concatenation to incorporate the value of the "name" variable into the "Text" property of the "whoami" label.

If you alter the value assigned to the "name" variable, the output of the page generated will change to reflect the new name. Try it and see for yourself!

You can also define a variable without assigning a value to it, or assign a value to it at a later stage - for example, the following code snippets are equivalent.

string name;        // define the variable
name = "The One";   // and initialize it
string name="The One";   // define and initialize a variable simultaneously

C# is a strongly typed language - in simple English, this means that each variable can only store a particular type of data. For example, I have defined the variable as a "string" datatype. I cannot store a number in this variable; if I try, as in the example below, I'll see an ugly error message:

// define a variable as string and initialize it to a number
string num = 1;

Define the number as a string, though, and it works out fine:

// define a variable as string and
// initialize it to a number stored as a string value
string num = "1";

Of course, the drawback of the above solution is that the "name" variable does not store the value "1" as a number and hence cannot be used for operations like addition, subtraction or multiplication.

Linking Out

And that's about it for the moment. In this introductory article, I gave you a quick overview of all the popular server-side scripting technologies, followed by a quick introduction to Microsoft's .NET vision. I also explained the basic components of the .NET architecture, and the process of installation and configuration of the .NET SDK.

Here are a few links for more information on .NET:

An introduction to ASP.NET from MSDN, at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconintroductiontoasp.asp

Getting started with ASP.NET, at http://msdn.microsoft.com/asp.net/using/gettingstarted/default.aspx?pull=/library/en-us/dndotnet/html/techmap_webapps.asp

.NET reference material, at http://www.gotdotnet.com

ASP.NET reference material, at http://www.asp.net

Next up, some code: the first example offered a quick understanding of the anatomy of an ASP.NET script. This was followed by the introduction of ASP.NET server controls, a useful feature introduced by Microsoft to help developers separate the presentation layer and the business logic of an ASP.NET program. And finally an introduction to variables in C#, with a fast example of string concatenation.

Of course, there is a lot more to variables than simple strings - C# has all the datatypes befitting a full-fledged programming language, and I shall tell you more about these in the next part of this series. Until then, have fun, and I'll see you soon.

Note: Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!

This article was first published on21 Jul 2003.