Вы находитесь на странице: 1из 3

PROGRAMMER’S WORLD C# MASTERCLASS EXTRA

Start programming on the web


This Series
Web
programming
Web development for a .NET developer using C#, beginning with an
with C#
introduction to web programming concepts and terminology
Tutorial One
Introduction to his month sees the start of a new tutorial series
web programming
and WinForms T on web programming: how to create interesting
and interactive website features using the ASP.
NET and Web Forms frameworks built into .NET. Along the
Tutorial Two way, we’ll look at what web programming features are
Using Web Matrix provided by VS.NET and what you can do with Web
Matrix – Microsoft’s free, community-supported ASP.NET
development tool. This month provides an introduction to
web programming concepts and terminology for those
PROJECT TIME previously confined to desktop programming.
In previous tutorials, we’ve put a lot of emphasis on
2 00HRS MINS desktop programming, but done very little web development.
In this new tutorial series, we try to redress the balance by
SKILL LEVEL focusing specifically on web development from the
perspective of a .NET developer using C#.
0 10
5 INTERMEDIATE
You should have
What do we mean by web development? When you
create a desktop application, you start by dropping WinForms
done some desktop components onto a design-time form, arranging them as
programming with C# required, modifying their behaviour and appearance through Amazon is essentially a set of cooperating web applications that
the use of properties, and then connecting them together provide a unified experience for the inveterate book browser.
YOU’LL NEED THIS
through event handlers, which produce the wanted
VS.NET 2003 or later, interaction with the end user. The end result is a self- This has some interesting repercussions. Think about
! and Web Matrix
contained program.
On the other hand, when you visit www.amazon.co.uk,
what happens when the user fills in a web-based form.
Strictly speaking, event processing is performed on the
FILES ON SUPERDISC you’re using a sophisticated web application rather than a server, but this requires a ‘round-trip’ to the server. In other
All project files needed to desktop one. An innovation of .NET is the ability to create words, the user clicks a button, checks a check-box or
complete this Masterclass web applications using the same, familiar RAD (Rapid whatever, necessitating that the server is informed of the
are on the Superdisc Application Development) paradigm. In other words, to create user action and requiring the server to render and return an
a simple web application, you use Web Forms rather than updated HTML page that reflects the new state of play. This
WinForms, but the overall approach is still the same; you add is called round-tripping, and posting an event to the server is
components to a form, set up their properties, link them naturally referred to as a postback. It goes without saying
together with event handlers and so forth. that you should code things in such a way as to minimise
It seems almost magical that things work out this way. round-tripping for performance reasons. Even if your client
After all, in a desktop application, the WinForms controls each connection is connected to the Internet via a broadband
render themselves using the underlying GDI+ graphics library. connection, the server might be very busy or preoccupied,
This gets mapped onto driver calls to the video display. which will obviously degrade response times; the bottom
However, a completely different mechanism is used by web line here is to minimise the server and client interaction
applications. The lingua franca of the Internet is HTML – the wherever possible.
hypertext markup language that we’re all familiar working From the perspective of the server-side code, a
with. When a Web Forms control renders itself, the result is mechanism is needed to determine whether this is the first
actually a chunk of HTML code that’s designed to create the time an ASP.NET page has been loaded, or whether this load
appropriate appearance and behaviour on the client is the result of a postback. In other words, is it the first time
machine. Thus, when a web page is ‘rendered’ on the client the remote browser has accessed the page, or has the user
machine, each of the individual components on that page clicked the Refresh button, hit ‘Submit’? This is done by
are responsible for supplying the necessary HTML to produce examining a property of the Page class called IsPostBack. Our
the wanted effect. hypothetical C# server-side code might look like this:

1 Understanding state and postbacks The code void Page_Load()


corresponding to each of the ASP.NET controls is running on {
the webserver and not on the client. Each ASP.NET control is if (!IsPostBack)
{
written as a specific class, typically authored in C#. All the
// Perform first-load processing...
browser sees, however, is a bunch of HTML. Moreover, HTML }
doesn’t itself have any concept of a state or persistent }
connection – it’s completely stateless.

170 PCPlus 235 | October 2005

PCP235.pcsharp 170 8/9/05 2:28:39 pm


MASTERCLASS EXTRA C# PROGRAMMER’S WORLD

So what is C#? Dave Jewell


dave.jewell@pcplus.co.uk
Microsoft’s latest, most innovative programming
language to date. Not simply a rehash of C++, it Dave is a freelance journalist,
provides unprecedented control over Microsoft consultant and programmer who’s
Windows and your own modern programs. written several programming books
and thousands of technical articles

As with the WinForms .NET components you’re used to, ASP. PASSING SHOT
NET components expose properties, methods and events. In Next month we’ll be focusing
the above code fragment, the Page_Load handler gets called on Web Matrix from Microsoft.
in response to a Load event. If the IsPostBack property This is a community-supported
returns false, then we know it’s not a load that results from a project that provides a high-
postback. This means it must be the first load of the page, quality, zero-cost tool for ASP.
and any appropriate first-time initialisation can be performed. NET website development. If
you can’t wait until next month
2 What’s in a Page? The Page class inhabits the System. but want to check it out for
yourself, point your browser at
Web.UI namespace and, as the name suggests, provides a
www.asp.net/webmatrix and
server-side encapsulation of a Web Forms page or .ASPX file. get downloading. It’s a trim 1.3
A Web Forms page consists of static HTML and/or one or MByte download, but does
more ASP.NET controls. As with regular desktop programming, assume that the .NET
there’s a design-time form where you can lay out the various framework is already installed.
ASP.NET controls which make up the page, and there’s also Here we’re building a web page that initially contains nothing but The website contains a lot of
separate ‘code-behind’ source which contains the server-side a ListBox component, also from the System.Web.UI namespace. tutorial information, a guided
script that implements the page. As with any other .NET tour and even a freely
source code, the code-behind file has the extension ‘.CS’ if it three entries of the list-box to ‘Starter’, ‘Main Course’ and downloadable Web Matrix
book in PDF format. And yes,
happens to be a C# file. ‘Desert’. I also modified the control’s background colour. The
you can program Web Matrix
If you’re using something like Visual Studio 2005 (or even resulting HTML looks like this: using C#.
the existing 2003 version), you’ll find that the IDE will
automatically handle the creation of the code-behind file as <asp:ListBox ID=‘ListBox1’ runat=‘server’
shown in the accompanying screenshot. Here, we have the BackColor=‘#C0C0FF’ Height=‘280px’
default web page with the designer view showing a simple OnSelectedIndexChanged=‘ListBox1_
SelectedIndexChanged’ Width=‘384px’>
list-box. This corresponds to the file Default.aspx. The
<asp:ListItem>Starter</asp:ListItem>
corresponding code-behind source is contained inside <asp:ListItem>Main Course</asp:ListItem>
Default.aspx.cs. <asp:ListItem>Desert</asp:ListItem>
If you look at the properties page on the right, you’ll see <asp:ListItem></asp:ListItem>
that the ListBox class is actually implemented inside System. </asp:ListBox>
Web.UI.WebControls along with the rest of the ASP.NET
components. To see all the web controls (and other goodies) As you can see, an ASP.NET control is introduced by the
contained within this namespace, you can use something <asp> tag. In this case, the list-box contains three ListItem
like Reflector to browse the metadata within the assembly. entries (actually four, the last one doesn’t have a caption set).
It’s instructive to add a few random Web Forms What’s interesting is that you can select different parts of this
components to a page and then swap over to the Source tab HTML from inside VS.NET, and the Properties window will
in order to see the HTML ‘source’ file that’s being generated. I change to reflect the currently selected item. For example,
tried adding a list-box to a page and then changing the first with a ListItem selected, you can modify its Enabled,

Running ASP on your development machine


IIS, PWS, XP Pro and more
If you want to do ASP.NET development then clicking ‘Add or remove Windows Panel | Administrative Tools | Internet
on your PC, then you’ll need a components’ on the left. In the list-box Information Services. From here, you
webserver to dish up those web pages that appears, choose Internet can modify many aspects of IIS
that you’ve lovingly crafted. The ideal Information Services (IIS) and click ‘OK’. operation (see the accompanying
solution is to use IIS, which You should end up with a directory, screenshot on the right) and stop or
unfortunately doesn’t come with XP Inetpub, on drive C that contains start the server.
Home Edition. This in itself is a good another folder called wwwroot. All file Although IIS is very powerful and You can access IIS using a
argument for getting XP Pro which, in references will be relative to this highly configurable, it can be like using management plug-in, which is
accessed via the Internet
my opinion, should be used for all directory by default. An absolute the proverbial sledge-hammer to crack a
Information Services icon on the
serious software development. There pathname of c:\Inetpub\wwwroot\ nut for simple Web projects. An smaller, Control Panel. Here, we can see
are various dirty hacks around for Site1\ … will be accessed as http:// but still very capable alternative is default website properties.
getting IIS working on Home Edition, but localhost/Site1/… from the perspective Personal Webserver, or PWS, which is
I wouldn’t recommend them. of your web browser. These pathname included as part of the Web Matrix
Assuming you’ve got XP Pro, you can mappings can be modified if desired. package. We’ll be looking at that next
install IIS by going to the Control Panel, To check if the server is running, or to month when we cover Web Matrix in
selecting ‘Add or remove programs’ and alter the configuration, go to Control more detail. ■

PCPlus 235 | October 2005 171

PCP235.pcsharp 171 8/9/05 2:28:41 pm


PROGRAMMER’S WORLD C# MASTERCLASS EXTRA

Understanding __ViewState field


How the server keeps tracks the state of each ASP.NET control
If you take the trouble to look at the into a string of ASCII characters so that it state information and the server will
source code of a web page that’s been can be passed back to the server. detect that the checkbox state has
implemented using ASP.NET (view page Here’s how it works. Suppose a changed. This will case the
source in your web browser), you’ll see checkbox is currently checked. Each OnCheckedChanged event to fire on the Here’s a typical __ViewState
some interesting stuff. For example, time the containing web page generates server, executing whatever event field strutting its stuff. Because
there’s a mysterious looking hidden a postback event, the view state handler you provide. The new view it’s a hashed dictionary object,
it’s not fit for human
field called __ViewState which looks information is returned to the server. If state information returned from the
consumption, but it provides the
like a long string of gobbledygook. This you happen to uncheck the checkbox, postback will then reflect the new state server with all it needs to know
is a dictionary object which is hashed this change will be reflected in the view of the checkbox. ■ about control state.

GOING FURTHER Selected, Text and Value properties via the Properties window
At first glance, ASP.NET and and the changes are immediately reflected in the HTML
web programming might look code. If you look at the C# code-behind source, you’ll see
intimidating (it still looks something like this:
pretty intimidating after a
second or third glance). But public partial class _Default : System.
help is at hand in the form of a Web.UI.Page
large number of ASP.NET titles, {
which you can pick up from protected void Page_Load(object sender,
Amazon using that oh-so- EventArgs e)
tempting ‘Buy now with 1- {
Click’ button. One of my }
favourites is ‘Build Your Own protected void ListBox1_SelectedIndexChang
ASP.NET Website Using C# & ed(object sender, EventArgs e) Reflector can be used to browse the assemblies that contain the
VB.NET’ by Z. Ruvalcaba. { implementations of the various ASP.NET controls.
Another is ‘Beginning ASP.Net }
1.1 E-Commerce: From Novice } client. If you examine the top of the .ASPX file generated by
to Professional’ by Darie and VS.NET, this is what you’ll see:
Watson. Read this, and you Here, the page has two defined property handlers; the Load
can implement a ‘Buy Now’
hander that we mentioned earlier and also a handler to <%@ Page Language=‘C#’
button for your own website. AutoEventWireup=‘true’ CodeFile=‘Default.
control what happens when the list-box selection is
changed. It’s easy to think of this in terms of plain-vanilla aspx.cs’ Inherits=‘_Default’ %>
desktop programming, but remember: this handler is invoked
on the server when the list-box selection is changed on the Crucially, this associates the .ASPX file with the C# containing
remote client machine. any defined event handlers and so forth. The
You might be perplexed by the partial keyword in the AutoEventWireup attribute (which is also new in ASP.NET 2.0)
above C# declaration. This is a new enhancement that was causes the ASP.NET system to automatically ‘wire up’ each of
added to the C# language in order to support ASP.NET 2.0. It’s the event handlers in the code file to the appropriate event
been added to VB.Net for the same reason. In essence, this exposed by the page.
keyword allows the declaration of a C# class declaration to In next month’s tutorial, we’ll get to grips with Web Matrix,
extend across more that one source. We’re telling the build some simple web pages and see how all this stuff
compiler: this is some of the declaration for the _Default works out in practice. The ASP.Net learning curve is a bit
NEXT MONTH class, but not all of it. This much ought to be obvious steep in places, but its well worth getting to grips with this
because, if you think about it, where are the declarations for technology. If you browse the web, you’ll find that more and
Next month, we’ll get to grips
with Web Matrix, Microsoft’s the list-box and those four ListItem entries? They simply don’t more third-party ASP.NET controls are available which can be
free but powerful development appear in the C# source file at all. used to create stunning web sites. To see what’s on offer, go
tool for creating websites There’s actually a lot of magic that happens behind the to www.asp.net and then click ‘Control Gallery’ from the
based around ASP.NET. scenes when the server receives a page request from a toolbar. You’ll be impressed with what’s now available. PCP

Web programming without the GUI


What else can you do besides create awesome websites?
You might be forgiven for thinking that useful stuff, especially if you’re a whether you’re accessing it with C#,
web programming is all about producing shareware developer. VB.NET, JavaScript or whatever. SOAP, in
great-looking websites. To a large extent Web services are based around SOAP turn, is based around XML.
it is, and this will be the main focus of which, if you’re unfamiliar with the term, SOAP support is already built right
this tutorial series. But there’s a lot more stands for Simple Object Access into Microsoft’s .NET framework. There’s
to explore than that. There’s been an Protocol. Put simply, SOAP provides a a class name lookup facility inside
explosion in so-called ‘web services’, standard mechanism for clients to Reflector; if you type ‘Soap’ into the
PayPal represent a convenient SOAP-based API’s that allow application interact with remote objects in a search box, you’ll see a cascade of class
way to pay for goods and code on one machine to invoke services platform independent and language names such as SoapServices,
services. With Web services, you
can add PayPal payment on a remote server. independent manner. When I say SoapFieldAttribute and
facilities to your own website. There are a wide assortment of Web ‘language independent’, I’m talking SoapMethodAttribute. All of this forms a
services available right now. If you want about both sides of the fence. As a web part of the System.Runtime.Remoting
to handle PayPal payments on your Web service consumer, you don’t care what namespace where the web services
site, then you can download and install programming language the remote support is implemented. You can read
the PayPal SDK from www.paypal.com/ object was written in, and the remote more on all these classes in the
sdk. Being able to do this is pretty object likewise doesn’t give a damn Microsoft documentation. ■

172 PCPlus 235 | October 2005

PCP235.pcsharp 172 8/9/05 2:28:42 pm

Вам также может понравиться