Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp .NET Developer's Handbook (2002) [eng]

.pdf
Скачиваний:
42
Добавлен:
16.08.2013
Размер:
4.94 Mб
Скачать

Notice that the web service includes a description, as do each of the methods. You can use the Service Description link to view the XML used to describe the service to ensure it's correct. Generally, you'll find that the automated Web Services Description Language (WSDL) code provided by the IDE works fine. We'll discuss the inner workings of WSDL and SOAP in more detail throughout Chapter 16.

The point of interest now is the four method links. Each of these links will help you test and use the associated web service method. Click on the DoAdd link and you'll see a dialog similar to the one shown in Figure 14.9.

Figure 14.9: Each web service provides a testing area on the website.

Notice that there are actually two sections to this dialog. First is the testing section. You can enter two values into the fields provided, then click Invoke to see the result. Second is an advice section for accessing the web service from an application using SOAP, HTTP GET, or HTTP POST access techniques. The information shows how to format your message, and you can use this information for troubleshooting the messages as they pass from machine-to-machine.

Using the Antechinus C# Editor

Many developers have expressed dissatisfaction with the editor provided with Visual Studio

.NET for C# development, which isn't a surprise for anyone who's developed applications for long. The editor, along with other tools such as third-party libraries, represents the developer's custom tool for creating code. Since each one of us is different, it's not surprising that a one- size-fits-all approach to the editor doesn't work.

More than a few developers are also looking for alternatives to the rather steep purchase price of Visual Studio .NET. Not every developer is convinced that .NET programming is in their future and the Visual Studio .NET package could represent an expensive experiment. Because the .NET Framework and the .NET Framework SDK are free for the price of a download, all that a developer really needs is a good editor to get started coding C#.

Of course, using a general editor deprives the developer of the features that a C#-specific editor can provide, such as context-sensitive help and keyword highlighting, so any alternative a developer chooses must provide some basic level of functionality. The Antechinus C# Editor (http://www.c-point.com/download2.htm) from CPoint Pty Ltd does provide all of the required functionality for a C# editor, yet has a different interface from the one provided by Visual Studio .NET. This section will briefly explore the Antechinus C# Editor. You'll also find a copy of this product in the \Antechinus folder of the CD. The example code used in this section appears in the \Chapter 14\Antechinus folder of the CD. Figure 14.10 shows an example of the Antechinus C# Editor with a project file loaded.

Figure 14.10: The Antechinus C# Editor provides a simpler interface than the one provided by Visual Studio .NET.

Note The Antechinus C# Editor relies on the .NET Framework, so you'll need to install the released version of the .NET Framework to use it. The installation program provided on the CD won't install the .NET Framework for you. However, if you install Visual Studio

.NET or the .NET Framework SDK before you install the Antechinus C# Editor, you'll have the required support.

The first difference you'll notice when using the Antechinus C# Editor is that it deals with source code files and doesn't rely on a solution file as the center of the application universe. This is actually a big plus, because many of the examples you'll see online lack any kind of solution file, so the Visual Studio .NET IDE has to build one as part of "importing" the application. You do have complete control over the project settings using the Project Options dialog box shown in Figure 14.11. Many developers find this method of setting project options easier than the relatively complex set of dialogs and folders provided with Visual Studio .NET.

Figure 14.11: The Project Options dialog box gives you complete control over the project options.

Note Some of the options demonstrated in this section are only available to registered users. For example, the trial version lacks support for using projects. However, even with the trial version you can create individual files and compile them into an executable. (You can't create multiple file examples without project support.) The trial version will also show features such as key word highlighting. In short, the editor itself is fully functional, but you'll find some of the functionality required to create complete applications is missing.

The Antechinus C# Editor is missing what some developers would consider an exceptionally important feature—there's no designer support. This means you have to code the forms by hand. Some developers actually find this easier, but you'll need to consider this omission from a productivity standpoint. Moving objects around in a graphical environment is easier than moving them around by modifying coordinates in source code. Still, not every project involves a visual interface. You can create a multitude of components and controls without worrying too much about graphics. Listing 14.4 shows an example of the code required to create a simple dialog box application. I followed some of the techniques employed by the Visual Studio .NET IDE, but also made the application cleaner whenever possible.

Listing 14.4: The Antechinus Can Work on Any Application Type

namespace Sample

{

using System;

using System.Drawing; using System.Collections;

using System.ComponentModel; using System.Windows.Forms; using System.Data;

public class SimpleDialog : System.Windows.Forms.Form

{

// Declare the components for the dialog box. private System.Windows.Forms.Button btnTest; private System.Windows.Forms.Button btnOK;

public SimpleDialog()

{

// Required for Windows Form Designer support

InitializeComponent();

}

private void InitializeComponent()

{

//Initialize the components. Start with btnTest. this.btnTest = new System.Windows.Forms.Button(); this.btnTest.Location = new System.Drawing.Point(325, 35); this.btnTest.Name = "btnTest";

this.btnTest.Size = new System.Drawing.Size(70, 20); this.btnTest.TabIndex = 1;

this.btnTest.Text = "Test"; this.btnTest.Click +=

new System.EventHandler(this.Test_Click);

//Initialize btnOK.

this.btnOK = new System.Windows.Forms.Button(); this.btnOK.Location = new System.Drawing.Point(325, 10); this.btnOK.Name = "btnOK";

this.btnOK.Size = new System.Drawing.Size(70, 20); this.btnOK.TabIndex = 0;

this.btnOK.Text = "OK";

this.btnOK.Click += new System.EventHandler(this.OK_Click);

// Create the dialog box.

this.ClientSize = new System.Drawing.Size(400, 250); this.Icon = new Icon("Icon1.ICO"); this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.btnTest,

this.btnOK});

this.Name = "SimpleDialog";

this.Text = "Antechinus C# Editor Demonstration";

}

protected void OK_Click (object sender, System.EventArgs e)

{

this.Close();

}

protected void Test_Click(object sender, System.EventArgs e)

{

MessageBox.Show("This is a test message.", "Test Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

}

class DialogExample

{

static void Main() // Entry point

{

Application.Run(new SimpleDialog());

}

}

}

The code begins by creating the two controls you'll see on the dialog box. The constructor calls InitializeComponent(), which initializes the two components and adds them to the form. Notice that the code doesn't contain any of the extras you'll find in a similar Visual Studio

.NET application (see the Simple2 application example in Chapter 1 for comparison).

There are a few extras in this listing. For example, the code loads an icon from disk to display on the form. Normally, Visual Studio .NET would place the icon in a resource and load it from there. If you want the icon to also appear within Windows Explorer, you'll need to add it to project options using the /win32icon:Icon1.ICO switch.

In sum, the Antechinus C# Editor is a good alternative to the Visual Studio .NET IDE—if you don't plan to work on large applications that require a lot of graphics. This is the perfect editor for someone who writes a lot of component and control code or works on website code. It's also a good way to get to know C# without a lot of extra widgets to get in the way. Using this editor forces you to learn about the code that the Visual Studio .NET editor creates (and sometimes botches) in the background.

Where Do You Go From Here?

This chapter has concentrated on web applications and web services that run under IIS. By now you realize that most developers will need to learn both types of programming projects to work in the distributed application environment of today. Of course, the type of project you concentrate on will depend on the company you work for. Many companies are more interested in supporting users on the road right now, which makes the web application more appealing. However, once users gain the support they need, you can bet that companies will begin developing web services to leverage the resources they have available to offer to other companies. This is especially true of companies that are already service-oriented.

We did look at more than just programming principles in this chapter. While your first task is to learn how to create the two types of distributed applications, you'll also need to learn how to optimize the applications. For example, it's important to experiment with various types of page caching. Using a cache can significantly improve the performance of your application. You'll also want to try the Antechinus C# Editor to see if it helps you become more productive—a developer's personal tools can make the difference between high productivity and frustration.

Chapter 15 will move away from the general web development discussed in this chapter and onto the benefits of using specific technologies—ASP.NET in this case. In fact, you'll find the next three chapters all help you develop strategies for using specific technologies. We'll look at XML and SOAP in Chapter 16. Chapter 17 will tell you how to work with mobile devices. In short, once you finish this series of chapters, you'll have a better idea of how to use specific Microsoft technologies to accomplish the goals your company has for distributed application development.

Chapter 15: ASP and ASP.NET Application

Development

Overview

There was a time that Microsoft introduced a technology called the Internet Server Application Programming Interface (ISAPI) and deemed it the next big programming platform. ISAPI still exists, but has never seen the light of day for many developers because it proved difficult to use and manage. Active Server Pages (ASP), while less robust and efficient, is extremely popular because it's both easy to develop and to manage. In sum, many developers use ASP today because it's the path of least resistance—a development methodology that's easy to understand.

Unfortunately, ASP is far from a perfect technology. Performance is a major concern, as is flexibility. ASP.NET is designed to make life better by adding functionality that you won't find in ASP. This chapter helps you understand the differences between ASP and ASP.NET. You'll learn how these new features will help you create better applications in less time.

We'll also look at several programming examples in this chapter. It's interesting to note that some developers see ASP.NET as a browser-only technology. However, the lines between browser and desktop applications have continued to blur as Internet content continues to find its way into desktop applications. For example, many desktop applications now rely on help data stored on a website, rather than on the local hard drive, to ensure the information the user gets is current.

Tip Visual Studio .NET doesn't always place your Web Solution files in an easy-to-find location. You can change this location by opening the Options dialog using the Tools Options command. Open the \Environment\Projects and Solutions folder within the Options dialog, and you'll see a Visual Studio Project Location field. Type the location for your project in this field or use the Browse button to locate the correct location using an Explorer-like interface. Note that other settings in this dialog include use of the Task List and Output windows, as well as the method used to save changes to your source files prior to building the application. Make sure you set the Visual Studio Project Location field value before you begin a project, so the solution file ends up in the right location.

An Overview of the Controls and Components

Working with ASP.NET requires an understanding of the controls and components that Microsoft provides. This difference isn't always clear because controls for the desktop environment often have the same names as controls for ASP.NET. The functionality of the two controls might be similar, but the behavior of the two controls is likely to be different. In addition to control, programming, and environmental differences, you'll also run into some new controls—some of which are indispensable in the distributed application environment.

The following sections provide you with an overview of ASP.NET controls and components from the desktop developer perspective. In short, given that you know about the controls used on the desktop, this section tells you what you need to know in order to use the controls in the web environment. Of course, the big issue is learning how ASP.NET differs from both the desktop environment and the ASP programming environment that preceded it.

Understanding the Environmental Differences

Controls and components under ASP.NET differ from those used in desktop applications, but they also have many similarities. As you saw in the simple control example in the "Web Control Example" section of Chapter 14, controls used for ASP.NET development share many similarities with their desktop counterparts. Both control types include features such as properties, methods, and events. You also have to render the control to see it on screen in both environments.

Likewise, the "Creating the Web Service" section of Chapter 14 provided a basic understanding of how components work under ASP.NET. Components seldom present a user interface of any type—it doesn't matter if the component resides on the desktop or as part of a web application. Components generally perform grunt work in an application, such as accessing databases or performing intricate calculations. In addition, both web and desktop components can reside on the client or the server—it all depends on where you install the component for a desktop application or where you cache it in a web application.

However, to say that the controls and components you use with ASP.NET are precisely the same as their desktop counterparts is absurd. The most obvious difference is utility—a web application has different developmental and environmental requirements than a desktop application. For one thing, there's no state storage in a web application. You have to pass a property bag, which is just a glorified cookie, to ensure your web application retains some sense of state from call to call.

The limitations of the browser display also have an important role to play in the functionality of controls. Unlike desktop screens, which normally provide a 1024 x 768 display area as a minimum, developers for browser displays might have to contend with something as small as 640 x 480 in the desktop. With more users requesting data from Personal Digital Assistants (PDAs) and cellular telephones, the display area is becoming miniscule indeed.

One of the best ways to see the differences between desktop and web controls is to compare the two versions of the DataGrid control (discussed in the "Working with the DataGrid" section of the chapter). You'll immediately notice some significant differences in the two control implementations, even though both controls purportedly perform the same task and were created by the same vendor. For example, the web version of the DataGrid provides public properties for controlling the use of paging—something that the desktop version doesn't even support. Unfortunately, this means you can't just move a copy of your code from one environment to the other and expect it to work—moving from the desktop to the Web means changing your code, even if the control does have the same name.

Understanding Coding Differences

Let's look at some specific implementation differences for web components and controls. (You'll find the source code for this section of the chapter in the \Chapter 15\CompControl folder on the CD.) The first problem is to record control and component property values in a persistable manner. ASP.NET accomplishes this task using entries within the ASPX page (rather than as part of the Code Behind, explained in the "Understanding Code Behind" section of the chapter). Here's an example of a label, pushbutton, and textbox using default settings.

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 31px;POSITION: absolute; TOP: 51px" runat="server"></asp:TextBox>

<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 31px;POSITION: absolute; TOP: 95px" runat="server" Text="Button"></asp:Button> <asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 31px; POSITION:

absolute; TOP: 17px" runat="server">Label</asp:Label>

Note The code for each control in an ASPX file normally appears on a single line. The source code lines in the book are split to make them easier to read. Consequently, instead of seeing six lines in the source code file as you do in the book, you'd see three. Because the IDE automatically reformats the code in the ASPX file, there wasn't any way to format both the book and the source file so they'd appear the same.

As you format these controls, the text in the ASPX file changes to reflect the new control settings. This is the technique that ASP.NET uses to persist the control properties for each call to the application. Here's the code for the same three controls. The only difference is that I've formatted them for use in the sample application.

<asp:textbox id="txtInput" style="Z-INDEX: 101; LEFT: 31px; POSITION: absolute; TOP: 51px" runat="server" ToolTip="Type a larger or smaller number to create an error.">0</asp:textbox>

<asp:button id="btnTest" style="Z-INDEX: 103; LEFT: 31px; POSITION: absolute; TOP: 95px" runat="server" Text="Test" ToolTip="See if there are any errors."></asp:button>

<asp:label id="Label1" style="Z-INDEX: 102; LEFT: 31px; POSITION: absolute; TOP: 17px" runat="server">Enter a number between 0 and 9:</asp:label></form>

The settings now reflect some changes in configuration from the base control setup. All of the basic settings are still in place, but the ASPX page now contains new settings to ensure the page displays as intended. Something you should note is that the <asp:button> tag lacks any entry for the event hander for the button, even though the page had an event handler at the time. Only property values appear in the ASPX file—ASP.NET looks into the Code Behind page to find non-property entries, such as event handlers and methods. You'll find the event handler entry in the InitializeComponent() method, as shown here. (Contrast this code with the InitializeComponent() code for a desktop application, and you'll notice that the desktop application uses this method to handle all component initialization needs.)

private void InitializeComponent()

{

this.btnTest.Click += new System.EventHandler(this.btnTest_Click); this.Load += new System.EventHandler(this.Page_Load);

}

An Overview of Validators

The Windows Forms control list also differs from the Web Forms control list. For example, you'll find a list of basic dialog box types in the Windows Forms control list that doesn't make sense for inclusion in the Web Forms list. However, some control entries aren't quite as clear cut. For example, Microsoft includes a series of validator controls in the Web Forms list that could possibly see use in a Windows Forms project.

A validator ensures the user enters the right type of data and in the proper range. All validators require an error message found in the Text property that the user will see and use to

correct the error on the web page. In addition, all validators provide a ControlToValidate property that you use to associate the control with the validator. Visual Studio .NET supports several validator types, but here are the four types you'll commonly use for applications.

CompareValidator The CompareValidator accepts two controls as input and then compares the value of each control. If the two controls don't match the condition you specify, the CompareValidator displays an error message. The name of the second control appears in the ControlToCompare property. The Operator property defines the comparison between the two controls. For example, if you choose the GreaterThan option, the value of the control listed in the ControlToValidate property must be greater than the value of the control listed in the ControlToCompare property. A Type property ensures the second control contains data of the correct type, but this is almost superfluous because the two controls won't compare if their types don't match.

RangeValidator The RangeValidator ensures that the input in a control falls within a range of values. The MinimumValue and MaximumValue properties contain the limit of values the user can input. You'll use the Type property to determine what type of data the control will accept. The RangeValidator accepts common types including string, integer, double, date, and currency. If the input doesn't fall within the selected range of values or is of the wrong type, the control will display an error message.

RegularExpressionValidator The RegularExpressionValidator uses an expression to validate the content or format of the input. You'll find that the Microsoft help topics at mshelp://MS.VSCC/MS.MSDNVS/script56/html/jsgrpRegExpSyntax.htm tend to focus on the format of the expression, as do the built-in expressions. However, the example in this section will show you how to build an expression that defines the content of the expression. The expression used for comparison with the input of the target control appears in the ValidationExpression property. Click the ellipses in this property to display the Regular Expression Editor dialog box shown in Figure 15.1.

Figure 15.1: The Regular Expression Editor helps you choose a predefined expression or create one of your own.

RequiredFieldValidator This is the easiest of validators to understand. If the target control is blank, the validator displays an error message. Some developers will use an asterisk in place of the error message and simply display one error message for all required fields. However, the use of a custom error message for each control means that you can provide example input for each data entry control.

Notice that I haven't mentioned any need for application code. All four validators perform their job without any coding on your part. The only work you need to perform is configuring the validator as described in the list. The validator performs the rest of the work for you at that point.

All of the validators provide client-side support. This feature will force the client to fix any errors in the form before the browser will send it to the server. Using a validator means that your server will have to react to fewer poorly formatted messages and that the server will work more efficiently. Of course, validators can only check for problems that they're designed to detect.

You can use multiple validators on one field to ensure the application detects as many problems as possible. In addition, the CustomValidator enables you to create special validators that can react to some unique conditions. Unfortunately, the CustomValidator requires you create code to make it functional, which makes a CustomValidator the custom programming solution for special situations only.

A Validator Example

Now it's time to apply what you've learned so far. This example concentrates on using validators under various conditions. In fact, we'll use all four of the common validators described in the previous section. Figure 15.2 shows the layout for a web page.

Figure 15.2: Using validators means setting aside space for text that might never appear on screen.

Notice the form contains two textboxes. You can't see it very well in the figure, but there are two pushbuttons that appear beneath two labels immediately below the two textboxes. Overlapping controls enables you to display more information on screen if the information has a short life span. The first textbox has a RequiredFieldValidator and a RangeValidator associated with it.

The second textbox uses all four validators to ensure the input is correct. The RequiredFieldValidator ensures the user enters some data. The RangeValidator ensures the data is within the specified range limit. The CompareValidator ensures that the second textbox contains a value greater than the first textbox. Finally, the RegularExpressionValidator ensures that the input value is even. We'll use the following regular expression to perform this task.