P. 1
235.Programmers World.c#

235.Programmers World.c#

|Views: 2|Likes:
Published by Alexandre Semedo

More info:

Published by: Alexandre Semedo on May 26, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less







Start programming on the web
This Series

Web programming with C#
Tutorial One

Web development for a .NET developer using C#, beginning with an introduction to web programming concepts and terminology
his month sees the start of a new tutorial series on web programming: how to create interesting and interactive website features using the ASP . NET and Web Forms frameworks built into .NET. Along the way, we’ll look at what web programming features are 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 previously confined to desktop programming. In previous tutorials, we’ve put a lot of emphasis on desktop programming, but done very little web development. In this new tutorial series, we try to redress the balance by focusing specifically on web development from the perspective of a .NET developer using C#. What do we mean by web development? When you create a desktop application, you start by dropping WinForms components onto a design-time form, arranging them as required, modifying their behaviour and appearance through the use of properties, and then connecting them together through event handlers, which produce the wanted interaction with the end user. The end result is a selfcontained program. On the other hand, when you visit www.amazon.co.uk, you’re using a sophisticated web application rather than a desktop one. An innovation of .NET is the ability to create web applications using the same, familiar RAD (Rapid Application Development) paradigm. In other words, to create a simple web application, you use Web Forms rather than WinForms, but the overall approach is still the same; you add components to a form, set up their properties, link them together with event handlers and so forth. It seems almost magical that things work out this way. After all, in a desktop application, the WinForms controls each render themselves using the underlying GDI+ graphics library. This gets mapped onto driver calls to the video display. However, a completely different mechanism is used by web applications. The lingua franca of the Internet is HTML – the hypertext markup language that we’re all familiar working with. When a Web Forms control renders itself, the result is actually a chunk of HTML code that’s designed to create the appropriate appearance and behaviour on the client machine. Thus, when a web page is ‘rendered’ on the client machine, each of the individual components on that page are responsible for supplying the necessary HTML to produce the wanted effect.

Introduction to web programming and WinForms
Tutorial Two


Using Web Matrix


2 00


0 10


INTERMEDIATE You should have done some desktop programming with C#


Amazon is essentially a set of cooperating web applications that provide a unified experience for the inveterate book browser.


VS.NET 2003 or later, and Web Matrix

All project files needed to complete this Masterclass are on the Superdisc

This has some interesting repercussions. Think about what happens when the user fills in a web-based form. Strictly speaking, event processing is performed on the server, but this requires a ‘round-trip’ to the server. In other words, the user clicks a button, checks a check-box or whatever, necessitating that the server is informed of the user action and requiring the server to render and return an updated HTML page that reflects the new state of play. This is called round-tripping, and posting an event to the server is naturally referred to as a postback. It goes without saying that you should code things in such a way as to minimise round-tripping for performance reasons. Even if your client connection is connected to the Internet via a broadband connection, the server might be very busy or preoccupied, which will obviously degrade response times; the bottom line here is to minimise the server and client interaction wherever possible. From the perspective of the server-side code, a mechanism is needed to determine whether this is the first time an ASP.NET page has been loaded, or whether this load is the result of a postback. In other words, is it the first time the remote browser has accessed the page, or has the user clicked the Refresh button, hit ‘Submit’? This is done by examining a property of the Page class called IsPostBack. Our hypothetical C# server-side code might look like this:
void Page_Load() { if (!IsPostBack) { // Perform first-load processing... } }

1 Understanding state and postbacks The code corresponding to each of the ASP.NET controls is running on the webserver and not on the client. Each ASP.NET control is written as a specific class, typically authored in C#. All the 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.


PCPlus 235 | October 2005

PCP235.pcsharp 170

8/9/05 2:28:39 pm

Web. you can install IIS by going to the Control Panel. three entries of the list-box to ‘Starter’. If you look at the properties page on the right. ASP. and there’s also separate ‘code-behind’ source which contains the server-side script that implements the page. but I wouldn’t recommend them.NET. The website contains a lot of tutorial information. For example. and any appropriate first-time initialisation can be performed. should be used for all serious software development.uk Dave is a freelance journalist.UI namespace and. Here we’re building a web page that initially contains nothing but a ListBox component. there’s a design-time form where you can lay out the various ASP.Web.asp. We’ll be looking at that next month when we cover Web Matrix in more detail. In this case. The ideal solution is to use IIS. go to Control Panel | Administrative Tools | Internet Information Services. in my opinion. The resulting HTML looks like this: <asp:ListBox ID=‘ListBox1’ runat=‘server’ BackColor=‘#C0C0FF’ Height=‘280px’ OnSelectedIndexChanged=‘ListBox1_ SelectedIndexChanged’ Width=‘384px’> <asp:ListItem>Starter</asp:ListItem> <asp:ListItem>Main Course</asp:ListItem> <asp:ListItem>Desert</asp:ListItem> <asp:ListItem></asp:ListItem> </asp:ListBox> As you can see.NET components you’re used to. Here. As with regular desktop programming. methods and events. you’ll find that the IDE will automatically handle the creation of the code-behind file as shown in the accompanying screenshot. In the list-box that appears. PCPlus 235 | October 2005 171 PCP235. Inetpub. Assuming you’ve got XP Pro. most innovative programming language to date. then you’ll need a webserver to dish up those web pages that you’ve lovingly crafted. you can modify its Enabled. An absolute pathname of c:\Inetpub\wwwroot\ Site1\ … will be accessed as http:// localhost/Site1/… from the perspective of your web browser. we can see default website properties. also from the System. Web. ‘Main Course’ and ‘Desert’. which unfortunately doesn’t come with XP Home Edition. which is included as part of the Web Matrix package. XP Pro and more If you want to do ASP.ASPX file. choose Internet Information Services (IIS) and click ‘OK’. provides a server-side encapsulation of a Web Forms page or . zero-cost tool for ASP. an ASP. 2 What’s in a Page? The Page class inhabits the System. If the IsPostBack property returns false. What’s interesting is that you can select different parts of this HTML from inside VS.jewell@pcplus.3 MByte download. but still very capable alternative is Personal Webserver. To see all the web controls (and other goodies) contained within this namespace. This corresponds to the file Default. but does assume that the .NET framework is already installed. point your browser at www. or to alter the configuration. which is accessed via the Internet Information Services icon on the Control Panel. it provides unprecedented control over Microsoft Windows and your own modern programs. we have the default web page with the designer view showing a simple list-box. These pathname mappings can be modified if desired.cs. selecting ‘Add or remove programs’ and then clicking ‘Add or remove Windows components’ on the left. the Page_Load handler gets called in response to a Load event. There are various dirty hacks around for getting IIS working on Home Edition. a guided tour and even a freely downloadable Web Matrix book in PDF format. You should end up with a directory. Not simply a rehash of C++. If you can’t wait until next month but want to check it out for yourself.NET control is introduced by the <asp> tag. Dave Jewell dave. NET components expose properties. As with any other . on drive C that contains another folder called wwwroot. you’ll see that the ListBox class is actually implemented inside System. or PWS. the list-box contains three ListItem entries (actually four.WebControls along with the rest of the ASP.aspx.NET development on your PC. you can use something like Reflector to browse the metadata within the assembly. This in itself is a good argument for getting XP Pro which. consultant and programmer who’s written several programming books and thousands of technical articles As with the WinForms . This is a community-supported project that provides a highquality. And yes.NET controls. In the above code fragment. I also modified the control’s background colour.NET source code. A Web Forms page consists of static HTML and/or one or more ASP.pcsharp 171 8/9/05 2:28:41 pm . To check if the server is running.UI namespace. the last one doesn’t have a caption set). The corresponding code-behind source is contained inside Default.co.NET components.MASTERCLASS EXTRA C# PROGRAMMER’S WORLD So what is C#? Microsoft’s latest. the code-behind file has the extension ‘. From here. NET website development. with a ListItem selected.net/webmatrix and get downloading. It’s instructive to add a few random Web Forms components to a page and then swap over to the Source tab in order to see the HTML ‘source’ file that’s being generated. This means it must be the first load of the page.aspx. If you’re using something like Visual Studio 2005 (or even the existing 2003 version). All file references will be relative to this directory by default.CS’ if it happens to be a C# file. It’s a trim 1. you can program Web Matrix using C#. I tried adding a list-box to a page and then changing the first PASSING SHOT Next month we’ll be focusing on Web Matrix from Microsoft. ■ You can access IIS using a management plug-in. and the Properties window will change to reflect the currently selected item. Although IIS is very powerful and highly configurable.NET controls which make up the page.UI. then we know it’s not a load that results from a postback. PWS. as the name suggests. Running ASP on your development machine IIS. you can modify many aspects of IIS operation (see the accompanying screenshot on the right) and stop or start the server. it can be like using the proverbial sledge-hammer to crack a nut for simple Web projects. An smaller. Here.

you’ll see some interesting stuff.Remoting namespace where the web services support is implemented. ■ PayPal represent a convenient way to pay for goods and services. Selected. aspx. Text and Value properties via the Properties window and the changes are immediately reflected in the HTML code. There’s actually a lot of magic that happens behind the scenes when the server receives a page request from a Crucially. you’ll see something like this: public partial class _Default : System. With Web services. then you can download and install the PayPal SDK from www. To see what’s on offer. There’s been an explosion in so-called ‘web services’.pcsharp 172 8/9/05 2:28:42 pm . Ruvalcaba. It’s easy to think of this in terms of plain-vanilla desktop programming. We’re telling the compiler: this is some of the declaration for the _Default class.UI. The ASP. GOING FURTHER At first glance. If you browse the web. Microsoft’s free but powerful development tool for creating websites based around ASP. As a web service consumer. but not all of it. client. Here’s how it works.1 E-Commerce: From Novice to Professional’ by Darie and Watson. you can add PayPal payment facilities to your own website. where are the declarations for the list-box and those four ListItem entries? They simply don’t appear in the C# source file at all.NET system to automatically ‘wire up’ each of the event handlers in the code file to the appropriate event exposed by the page.cs’ Inherits=‘_Default’ %> NEXT MONTH Next month. All of this forms a part of the System. Being able to do this is pretty useful stuff. Because it’s a hashed dictionary object.NET controls are available which can be used to create stunning web sites.ASPX file generated by VS. but its well worth getting to grips with this technology.NET’ by Z. Web services are based around SOAP which. EventArgs e) { } } Reflector can be used to browse the assemblies that contain the implementations of the various ASP. SOAP. we’ll get to grips with Web Matrix.Page { protected void Page_Load(object sender. which you can pick up from Amazon using that oh-sotempting ‘Buy now with 1Click’ button.Net 1.ASPX file with the C# containing any defined event handlers and so forth. build some simple web pages and see how all this stuff works out in practice. PCP Web programming without the GUI What else can you do besides create awesome websites? You might be forgiven for thinking that web programming is all about producing great-looking websites.NET (view page source in your web browser). the Load hander that we mentioned earlier and also a handler to control what happens when the list-box selection is changed. I’m talking about both sides of the fence. The AutoEventWireup attribute (which is also new in ASP. if you’re unfamiliar with the term. go to www. One of my favourites is ‘Build Your Own ASP.paypal. especially if you’re a shareware developer. There are a wide assortment of Web services available right now. When I say ‘language independent’. SOAP support is already built right into Microsoft’s . the page has two defined property handlers. But help is at hand in the form of a large number of ASP. If you want to handle PayPal payments on your Web site. In next month’s tutorial. and this will be the main focus of this tutorial series. you’ll find that more and more third-party ASP. Read this.Runtime.NET and web programming might look intimidating (it still looks pretty intimidating after a second or third glance).NET framework.net and then click ‘Control Gallery’ from the toolbar.0) causes the ASP.NET. If you look at the C# code-behind source.PROGRAMMER’S WORLD C# MASTERCLASS EXTRA Understanding __ViewState field How the server keeps tracks the state of each ASP. 172 PCPlus 235 | October 2005 PCP235. Here. but it provides the server with all it needs to know about control state. This is a new enhancement that was added to the C# language in order to support ASP. stands for Simple Object Access Protocol. and the remote object likewise doesn’t give a damn whether you’re accessing it with C#.asp.NET. in turn. SOAP-based API’s that allow application code on one machine to invoke services on a remote server. we’ll get to grips with Web Matrix. It’s been added to VB. EventArgs e) { } protected void ListBox1_SelectedIndexChang ed(object sender.NET. is based around XML. JavaScript or whatever. this change will be reflected in the view state information and the server will detect that the checkbox state has changed. There’s a class name lookup facility inside Reflector.NET titles.NET Website Using C# & VB.NET 2. The new view state information returned from the postback will then reflect the new state of the checkbox.com/ sdk. you’ll see a cascade of class names such as SoapServices. it’s not fit for human consumption. you don’t care what programming language the remote object was written in.NET control If you take the trouble to look at the source code of a web page that’s been implemented using ASP. You might be perplexed by the partial keyword in the above C# declaration. This is a dictionary object which is hashed into a string of ASCII characters so that it can be passed back to the server.Net learning curve is a bit steep in places. ASP. But there’s a lot more to explore than that. In essence. VB. ■ Here’s a typical __ViewState field strutting its stuff. this keyword allows the declaration of a C# class declaration to extend across more that one source. the view state information is returned to the server. Suppose a checkbox is currently checked. and you can implement a ‘Buy Now’ button for your own website. Each time the containing web page generates a postback event. SOAP provides a standard mechanism for clients to interact with remote objects in a platform independent and language independent manner.NET controls. This will case the OnCheckedChanged event to fire on the server. SoapFieldAttribute and SoapMethodAttribute. To a large extent it is.0. this is what you’ll see: <%@ Page Language=‘C#’ AutoEventWireup=‘true’ CodeFile=‘Default.NET 2. If you examine the top of the . Put simply. Another is ‘Beginning ASP. If you happen to uncheck the checkbox. this associates the . You can read more on all these classes in the Microsoft documentation. You’ll be impressed with what’s now available. if you think about it. This much ought to be obvious because.Net for the same reason. For example. Web. but remember: this handler is invoked on the server when the list-box selection is changed on the remote client machine. if you type ‘Soap’ into the search box. there’s a mysterious looking hidden field called __ViewState which looks like a long string of gobbledygook. executing whatever event handler you provide.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->