The Example Application


Any one of the topics listed in the introduction to this chapter would, if covered in detail, fill a whole chapter on its own. The breadth of the .NET Class Library, and the number of classes in each namespace, can be intimidating until you begin to find your way around. The purpose of the example application, and this chapter as a whole, is to help you discover what features are available, how they are used, and where to look for more information when you need to perform tasks of greater complexity than those in the example application.

You will not see all the code in the example application listed in this chapter. Instead, you will see the important concepts described, along with the relevant sections of code. In addition, pointers will show you where to go to see the code in its entirety within the application source, and where to find out more details of the classes that it uses.

Figure 15.1 shows the application when you start it up. The best way to see it, and work with the code it contains, is to load the project from the Ch15 subfolder of the example files into Visual Studio.

Figure 15.1. The example application for this chapter


As you can see, the example allows you to create instances of seven different types of objects or select an existing file, perform up to three processes on that object, and then output it to one of four destinations. Throughout this chapter, you will see the way it works, what the results look like, and how the underlying code accomplishes these tasks.

There is a lot of code in the project. To help you find your way around, Table 15.1 contains a list and description of the main files.

Table 15.1. The Files in the Example Project

File Name and Location

Description

default.aspx

The interface file for the main page, containing the HTML, server controls, and other content.

default.aspx.cs

The code-behind file for the main page, containing the code that manages the main interface features and handles the interface events.

App_Code\Ch15DataProcess.cs

A class file that implements the main processes in the application. It contains a series of methods that demonstrate each topic in this chapter and that the interface code calls as required.

App_Code\PieChart.cs

A class file that generates a bitmap image of a pie chart.

App_Code\Point.cs

A class file that implements a generic collection of objects.

datafiles folder

The folder where the example generates its output files.

images folder

Two images used in the TReeView control you will see later in this chapter


Configuring the Example on Your Machine

At runtime, ASP.NET compiles the files in the App_Code folder automatically to take into account any edits you made to these files. However, before you run the example on your machine, there are a few setup tasks. First, open default.aspx.cs and edit the four String values near the top of the page to suit your machine and requirements (see Listing 15.1). These represent the URL of the Web page that the example will attempt to retrieve, and the URL for which it will attempt to retrieve the DNS entries. The final two values must be set to an e-mail address that is valid on your e-mail server or domain, so that the SMTP service or mail server will accept and send your messages, and the name or IP address of the SMTP mail server to use.

Listing 15.1. The Configuration Values in default.aspx.cs

// specify these values to suit your requirements String theWebPage = "http://your-own-site.com/"; String theDnsHost = "your-own-site.com"; String emailFromAddr = "from.you@your-own-site.com"; String smtpServerName = "your-smtp-server-name";

In fact, the classes in System.Net.Mail read SMTP configuration data from the <mailSettings> section of the web.config file. You can configure the default values here and remove the code that sets them from the example if you prefer. Listing 15.2 shows the syntax of the <mailSettings> section of web.config.

Listing 15.2. Configuring Your Mail Settings in web.config

<system.net>   <mailSettings>     <smtp from="from.you@your-own-site.com">       <network host="your-smtp-server-name" port="25"                userName="your-username" password="your-password"                defaultCredentials="true" />     </smtp>   </mailSettings> </system.net>

Using a Remote SMTP Server

The simplest setup is to use the local SMTP server on the machine where you are running the example (if it is Windows 2000 Server or Windows Server 2003). If you want to relay through a remote mail server, you should be sure to log on to your machine with an account that has relay permissions on the mail server.

You can specify credentials when you send e-mail messages if your account does not have permission to send e-mail through a remote SMTP server. Near to the end of the SendEmailMessage routine in the file Ch15DataProcess.cs, you can add code to generate a suitable Network-Credential instance, and replace the one used in the code. For sending messages under your default credentials, the code uses:

// add default credentials for accessing SMTP server sender.Credentials = CredentialCache.DefaultNetworkCredentials;


Instead, the code shown in Listing 15.3 creates a new NetworkCredential, adds it to a new CredentialCache, and then sets it on the SmtpClient that sends the message to the SMTP server. You specify the URL or server name of the target server, and the authentication method (such as "Basic" or "NTLM") that it requires. If needed, you can specify the domain in which the account resides as well, as shown in the listing.

Listing 15.3. Creating a NetworkCredential for the SMTP Server

NetworkCredential nc; nc = new NetworkCredential(username, password [, domain]); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("your-smtp-server-url"),"auth-type", nc); sender.Credentials = cc;

Setting Disk Access Permissions

The other task is to ensure that the account you are running the example under has read, write, and modify (change) permission for the datafiles subfolder where it will place its generated files. If you are running the example from within Visual Studio or VWD, you should set up permission for your own account. If you are running the example under IIS, you should set the permissions for the ASPNET and NETWORK SERVICE accounts.

The User Interface of the Example Application

As well as a demonstration of many techniques using the classes in the namespaces you saw listed at the start of this chapter, the example also shows how you can use two useful ASP.NET server controlsthe MultiView and TReeView. You saw the treeView used in Chapter 10, but this example uses it in a different way by populating the nodes dynamically on demand.

Using the MultiView Control

As you run the example, it appears to consist of three different pages. The first, shown in Figure 15.1, contains the controls to select the operation(s) you wish to perform. The second page, shown in Figure 15.2, displays a list of the drives, folders, and files on your system. The third page, which you will see later, displays the results of the selected operation.

Figure 15.2. The second page of the example displays drive and file information using a TreeView control


While these appear to be separate pages, they are in fact all just views of specific sections of a single page. The MultiView control allows you to define a series of sections in a page using View controls, and then activate one of these views dynamically at runtime. Listing 15.4 shows an outline of the code in the page default.aspx, and you can see the MultiView control and the three View controls (some of the content of each View control has been removed for clarity, but you can see it all by opening the page in Visual Studio or a text editor).

The ActiveViewIndex property of the MultiView control defines the View that will show when the page loads, with the View controls indexed from zero. The attribute ActiveViewIndex="0" you see in Listing 15.4 therefore means that the first view defined within the page will be visible when the page loads for the first time. After that, the viewstate of the page will maintain the ActiveViewIndex value so that the same view displays until you change it.

Listing 15.4. Using a MultiView Control to Display Separate Views of the Page content

<asp:MultiView  runat="server" ActiveViewIndex="0">   <asp:View  runat="server">     <asp:Panel  runat="server"          GroupingText="Select the type of item to create:">       ...     <asp:Button  runat="server" Text="Start"          OnClick="btnStart_Click" />   </asp:View>   <asp:View  runat="server">     <asp:Panel  runat="server"          GroupingText="Select an existing file:">       <div style="padding:5px">         <asp:TreeView>           ...         </asp:TreeView>       </div>     </asp:Panel>     <asp:Button  runat="server" Text="Cancel"          OnClick="btnCancel_Click" />   </asp:View>   <asp:View  runat="server">     <asp:Panel  runat="server"          GroupingText="Result:">      <div style="padding:5px">        <asp:Label  runat="server" />        ...      </div>    </asp:Panel>    <asp:Button  runat="server" Text="Back"         OnClick="btnCancel_Click" />    </asp:View>   </asp:MultiView>

In the example, code in an event handler that executes when clicking the Use an existing file option in the first view displays the page containing the treeView control shown in Figure 15.2, using this code:

MultiView1.SetActiveView(view2);


In a similar way, clicking any file in the treeView then executes an event handler that re-displays the first view, while clicking the Start button in the first view executes the selected process(es) and shows the third view containing the results. The code in the btnCancel_Click event handler, which buttons in the second and third views call, simply displays the first view again using:

MultiView1.SetActiveView(view1);


You can see that the MultiView is an extremely useful control for building pages that require separate "screens" as part of an overall process. In fact, it gives you the opportunity to build pages that work in a similar way to the MobilePage with its multiple sever-side <form> sections you saw in the previous chapter. The advantage is that ASP.NET automatically maintains the values in the controls in all views, irrespective of whether they are visible or not, making writing the code much simpler.

The downside is that this increases the viewstate of the page, and hence the amount of data that is sent back and forth over the network with each page request. It also, of course, increases the processing load on your server, though this is only likely to be noticeable in very large pages or very busy sites.

Styling and Dynamically Populating a TreeView Control

In Figure 15.2, you can see how the example uses a treeView control to display the contents of your system's hard disk. This is a common way to view disk information, and one of the styles included with ASP.NET, which you can apply using the Auto-Format option in the task pane for the TReeView in design view, provides the appearance you see here. You can also apply it directly by setting the ImageSet property to "XPFileExplorer", as shown in Listing 15.5.

Listing 15.5. The TreeView Control Using the ImageSet That Generates a File Explorer

<asp:TreeView  runat="server" ImageSet="XPFileExplorer"      NodeIndent="15" ShowLines="True" ExpandDepth="1"      PathSeparator="\" LeafNodeStyle-ChildNodesPadding="3"      NodeStyle-Font-Size="X-Small" EnableClientScript="false"      OnTreeNodePopulate="PopulateNode"      OnSelectedNodeChanged="SelectNode">   ... </asp:TreeView>

Notice that the declaration in Listing 15.5 sets the attributes EnableClientScript and OnTreeNodePopulate. The code in the example populates the treeView control dynamically, rather than using data binding as in earlier chapters. However, you must consider how the user will interact with the control, and how this may affect performance, when using any control that can potentially contain as much content as you see in Figure 15.2.

The example displays drive and file information, and experience of using some directory listing tools (especially over a network) will have shown that retrieving this information is not an instantaneous process. If you were to populate fully the TReeView with the contents of every drive and every folder when starting the application, and the user never activated that view, all that effort, processing cost, and delay would have been wasted. Even if you were to populate it only when activating this view (perhaps by handling the Activated event), users would still experience significant delays. In addition, the viewstate would be huge.

Far better is to populate only a small section at the root of the treeView by default, and then populate each drive and subfolder only as the user opens it. This process, called populate on demand, is how Windows Explorer works. You must disable client-side script in the treeView control so that the action of opening nodes in the tree causes a postback to the server. Then you handle the OnTreeNodePopulate event in your serverside code to populate each node as the user opens it by creating and adding treeNode instances. You will see how the example page does this in the section Reading Drive, Folder, and File Information later in this chapter.

You can implement populate-on-demand client-side by writing script that either stores all of the required data on the client at page load, or that fetches it in the background using callbacks as required. In this case, you would leave client-side scripting enabled on the control, and implement the required client-side event handlers. For more information, see: http://msdn.microsoft.com/library/en-us/dnvs05/html/treeview. asp and http://www.dotnetjunkies.com/Article/E80EC96F-1C32-4855-85AE-9E30EECF13D7.dcik




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net