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

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
219
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 10

When we say that each class must inherit directly from exactly one class, we mean that each class can mention only one class in its Inherits statement. The class that it’s inheriting from can also inherit from another class. So, for example, you could create a class called Porsche that is inherited from SportsCar. You could then say that it indirectly inherits from Car, but it directly inherits from only one class — SportsCar. In fact, many classes indirectly inherit from lots of classes — but there is always a direct ancestry, where each class has exactly one parent.

You may want to have some functionality in different classes that are not related to each other by inheritance. You can solve the problem by putting that functionality in an interface that both classes implement, like the IDisposable interface you encountered in Chapter 9.

Summar y

In this chapter, you looked at how to start building your own objects. You kicked off by learning how to design an object in terms of the properties and methods that it should support and then built a class that represented a car. You then started adding properties and methods to that class and used it from within your application.

Before moving on to the subject of inheritance, you looked at how an object can be given a constructor — a block of code that’s executed whenever an object is created. The discussion of inheritance demonstrated a number of key aspects of object-oriented design, including polymorphism and overriding.

To summarize, you should know how to:

Create properties and methods in a class

Provide a constructor for your class to initialize the state of your class

Inherit another class

Override properties and methods in the inheriting class

Create your own namespace for a class

Exercises

Exercise 1

Modify your Car class to implement the IDisposable interface. In the Main procedure in Module1, add code to dispose of the objCar object after calling the DisplaySportsCarDetails procedure.

Exercise 2

Modify the code in the Main procedure in Module1 to encapsulate the declaration and usage of the SportsCar class in a Using . . . End Using statement. Remember that the Using . . . End Using statement automatically handles disposal of objects that implement the IDisposable interface.

346

11

Advanced Object-Oriented

Techniques

In Chapter 10, you looked at how you can build your own objects. Prior to that, you had been mostly using objects that already existed in the .NET Framework to build your applications. In this chapter, you’ll be taking a look at some more object-oriented software development techniques.

In the first half of this chapter, you create your own classes. You will create a single-tier application like the others we have discussed so far in this book. The idea of creating two-tier applications, as opposed to single-tier applications, will be introduced in Chapter 13. You will then learn about creating your own shared properties and methods. These are very useful when you want a method or property to apply to a class as a whole rather than a specific instance of that class. Finally, you look at memory management in Visual Studio 2005 and what you can do to clean up your objects properly.

In this chapter, you will:

Create classes that can be used by multiple applications

Learn about shared properties and methods

Learn about memory management in the .NET Framework

Building a Favorites Viewer

In the first half of this chapter, you’re going to build a simple application that displays all your Internet Explorer favorites and provides a button that you can click to open the URL in Internet Explorer. This application illustrates a key point regarding code reuse and some of the reasons why building code in an object-oriented fashion is so powerful.

Chapter 11

Internet Shortcuts and Favorites

You’re most likely familiar with the concepts of favorites in Internet Explorer. What you may not know is how Internet Explorer stores those favorites. In fact, the Favorites list is available to all other applications — provided you know where to look.

Windows applications have the option of storing data in separate user folders within a main folder called C:\Documents and Settings. In Figure 11-1 you can see that my computer has a couple of user folders: Margie and Thearon.

Administrator is the default administrator on your computer for users who are using a Windows 2000 operating system or Windows XP Professional. All Users contains items available to all users, irrespective of who they log in as. And Default User is a special folder that Windows uses whenever a new user logs onto the computer for the first time.

Figure 11-1

Depending on how the security of your computer is configured, you may not be able to access the C:\Documents and Settings folder. If you can, open the folder whose name matches the name that you supply when you log on. In the screenshots throughout this chapter, I’ve used Thearon. (If you cannot consistently open the folder, ask your system administrator to help you log in as a different user or give you the appropriate permissions.) If you open this folder, you’ll find another group of folders. You’ll see something like Figure 11-2 (though it may look different depending upon how your login is configured).

You’ll notice that on my computer some of these folder icons appear as faint icons, whereas others appear as normal folder icons. My computer is configured to show all folders, so you may find that on your machine the faint folders do not appear because these are normally hidden. This doesn’t matter, because the one you’re specifically looking for — Favorites — will appear whatever your system settings are.

This folder (Thearon on my computer) is where Windows stores a lot of folders that are related to the operation of your computer for your login account, for example:

Cookies stores the cookies that are placed on the computer by Web sites that you visit.

Desktop stores the folders and links that appear on your desktop.

348

Advanced Object-Oriented Techniques

Favorites stores a list of Internet Explorer favorites.

My Documents stores the default location for storing Microsoft Office and other application data.

Start Menu stores a list of folders and links that appear when you press the Start button.

User Data stores specific user data related to the applications that you run.

Figure 11-2

It’s the Favorites folder that you’re interested in here, so open it. You’ll see something like Figure 11-3 (obviously, this list will be different on your computer, because you’ll have different favorites).

Figure 11-3

You’ll notice that the links inside this folder relate to the links that appear in the Favorites menu in your browser. If you double-click one of those links, you’ll see that Internet Explorer opens and navigates to the URL that the favorite points to.

349

Chapter 11

You can be fairly confident at this stage that, if you have a folder of links that appear to be favorites, you can create an application that opens this folder and can do something with the links — namely, iterate through all of them, add each of them to a list, find out what URL it belongs to, and provide a way to open that URL from your application. In the example that follows, you’re going to ignore the folders and just deal with the favorites that appear in the root Favorites folder.

Your final application will look like Figure 11-4.

Figure 11-4

Using Classes

So far in this book, you’ve built basic applications that do something, but most functionality that they provide has been coded into the applications’ forms. Here, you’re about to build some functionality that can load a list of favorites from a user’s computer and provide a way to open Internet Explorer to show the URL. However, you do it in a way that means you can use the list of favorites functionality elsewhere.

The best way to build this application is to create a set of classes that include the following classes:

WebFavorite, which represents a single favorite and has member variables such as Name and Url

Favorites, which can scan the favorites list on the user’s computer, creating a new Web Favorite object for each favorite

WebFavoriteCollection, which contains a collection of WebFavorite objects

These three classes provide the back-end functionality of the application — in other words, all classes that do something but do not present the user with an interface. This isolates the code in the classes and allows you to reuse the code from different parts of the application — code reuse. You also need a front end to this application, which, in this case, will be a Windows form with a couple of controls on it.

In the next few sections, you build your classes and Windows application and come up with the application shown in Figure 11-4. You start by building the Windows Application project in the following Try

It Out.

350

Advanced Object-Oriented Techniques

Try It Out

Creating Favorites Viewer

1.Open Visual Studio 2005 and create a new Visual Basic Windows Application project called

Favorites Viewer.

2.Modify Form1, setting these properties:

Set Size to 464, 280.

Set StartPosition to CenterScreen.

Set Text to My Favorites.

3.Add a ListView control to the form and size it to look similar to Figure 11-5 and set these properties:

Set Name to lstFavorites.

Set Anchor to Top, Bottom, Left, Right.

Set View to Details.

4.Select the Columns property in the Properties window for the lstFavorites control. Click the ellipsis dots (...) button to display the ColumnHeader Collection Editor dialog box.

5.Click the Add button. Set these properties on the new column header:

Set Name to hdrName.

Set Text to Name.

Set Width to 250.

6.Click the Add button again to add a second column. Set these properties on the new column header:

Set Name to hdrUrl.

Set Text to URL.

Set Width to 250.

7.Click OK to close the editor.

8.Add a LinkLabel control to the bottom of the form and set these properties:

Set Name to lnkUrl.

Set Anchor to Bottom, Left, Right.

Set TextAlign to MiddleLeft.

9.Your completed form should now look similar to the one shown in Figure 11-5.

How It Works

All that you’ve done here is to build the basic shell of the application, the form that will display the results of the processing. You started by modifying some basic properties of the form and then added two controls: a list view and a link label. The ListView control will be used to display the name and URL of each favorite in your Favorites folder. The LinkLabel control will be used to launch a browser with the selected favorite URL in the list.

351

Chapter 11

Figure 11-5

That’s the basics of the form put together. In the next Try It Out, you look at how you can add the backend classes. In previous chapters, you learned how to add classes to a Visual Studio 2005 project, so you will use this knowledge to create the back end of your application.

Try It Out

Building WebFavorite

1.Using the Solution Explorer, right-click Favorites Viewer. Select Add Class from the menu to display the Add New Item – Favorites Viewer dialog box. Enter a name of WebFavorite.vb and then click the Add button.

2.Add this namespace import declaration to the top of the code listing:

Imports System.IO

Public Class WebFavorite

3.This class will need to implement the IDisposable interface, so add this Implements statement. When you press Enter, Visual Studio 2005 inserts the members and methods associated with the IDisposable interface:

Public Class WebFavorite

Implements IDisposable

4.Now add these two members after the IDisposable interface code inserted by Visual Studio 2005:

#End Region

‘Public Members

Public Name As String

Public Url As String

5.Now add the Load method, which will load the member variables in this class:

Public Sub Load(ByVal fileName As String)

‘Declare variables

352

Advanced Object-Oriented Techniques

Dim strData As String

Dim strLines() As String

Dim strLine As String

Dim objFileInfo As New FileInfo(fileName)

‘Set the Name member to the file name minus the extension Name = objFileInfo.Name.Substring(0, _

objFileInfo.Name.Length - objFileInfo.Extension.Length)

Try

‘Read the entire contents of the file

strData = My.Computer.FileSystem.ReadAllText(fileName)

‘Split the lines of data in the file

strLines = strData.Split(New String() {ControlChars.CrLf}, _ StringSplitOptions.RemoveEmptyEntries)

‘Process each line looking for the URL For Each strLine In strLines

‘Does the line of data start with URL= If strLine.StartsWith(“URL=”) Then

‘Yes, set the Url member to the actual URL Url = strLine.Substring(4)

‘Exit the For...Next loop Exit For

End If

Next

Catch IOExceptionErr As IOException ‘Return the exception to the caller

Throw New Exception(IOExceptionErr.Message) End Try

End Sub

How It Works

It will be useful to examine how the WebFavorite class populates itself when the Load method is invoked.

The first thing you do is declare the variables needed by this method. The strData variable will be used to receive the entire contents of the favorite’s shortcut file. The strLines() variable will be used to create an array containing each individual line of data from the strData variable, and the strLine variable will be used to iterate through the array of lines. Finally, the objFileInfo object will be used to get the file information from the full path and filename passed to this method.

Public Sub Load(ByVal fileName As String) ‘Declare variables

Dim strData As String Dim strLines() As String Dim strLine As String

Dim objFileInfo As New FileInfo(fileName)

Next, the Name member is set to just the filename of the favorite’s shortcut file; for example Extensible Markup Language (XML). This is the name of the favorite that shows up on the Favorites list in the browser. The fileName parameter that will be passed to this method will contain the complete path to

353

Chapter 11

the file, the filename, and the file extension (for example, C:\Documents and Settings\Thearon\ Favorites\Extensible Markup Language (XML).url). What you have to do is extract only the filename from the complete path.

You do this by using the objFileInfo object, which has been initialized to an instance of the File Info class with the fileName variable passed to it. The FileInfo class provides several methods that return the various parts of the complete file path and name, such as only the filename and only the file extension.

You use the Name property of the objFileInfo object to get just the filename and extension of the file without the path, and you use the Substring method of the Name property to extract the filename minus the file extension. To supply the parameters to the Substring method, you also use the Length property of the Name property in the objFileInfo object to determine how long the filename is and the Length property of the Extension property to determine how long the file extension is.

So basically what you’re saying here is, “Take a substring, starting at the first character, and continue for the complete length of the string minus the length of the Extension property.” This, in effect, removes the .url from the end. Remember that the array of characters that make up a string is zero-based; thus you specify a starting position of 0 for the SubString method.

‘Set the Name member to the file name minus the extension Name = objFileInfo.Name.Substring(0, _

objFileInfo.Name.Length - objFileInfo.Extension.Length)

You read the entire contents of the file next into the strData. Because you are reading from a file, you’ll want to encapsulate the logic in a Try . . . Catch block to handle any IO exceptions that might occur.

The first thing that you do in this Try . . . Catch block is read the entire contents of the file into the strData variable. This is done using the My.Computer namespace and the ReadAllText method of the FileSystem class. This method will handle all the details of opening the file, reading the entire contents, closing the file, and releasing the resources used to perform these operations.

Try

‘Read the entire contents of the file

strData = My.Computer.FileSystem.ReadAllText(fileName)

After the contents of the file have been read, the strData variable will contain something similar to the data shown here. This is the data from the C:\Documents and Settings\Thearon\Favorites\Extensible Markup Language (XML).url shortcut file.

[DEFAULT]

BASEURL=http://www.w3.org/XML/

[InternetShortcut]

URL=http://www.w3.org/XML/

Modified=B0C9EC877EB3C401E2

Now that you have the entire contents of the favorite’s shortcut file in a single string variable, you want to split the contents of the strData variable into separate lines. This is done using the Split method of the String class, from which the strData variable is derived. The Split method is an overloaded method, and the version that you are using here accepts an array of strings that separate each line as the first parameter and the split options as the second parameter.

354

Advanced Object-Oriented Techniques

The data in the strData variable is separated with a carriage return and line feed character combination, and thus you provide a string array containing only one entry, ControlChars.CrLf, as the first parameter of the Split method. The split options parameter of the Split method is a value in the StringSplitOptions enumeration that let you specify how empty elements are handled. Here you specify the RemoveEmptyEntries constant of that enumeration, to remove any empty entries in the array that gets returned.

‘Split the lines of data in the file

strLines = strData.Split(New String() {ControlChars.CrLf}, _ StringSplitOptions.RemoveEmptyEntries)

Next you need to process each line of data in the strLines array using a For . . . Next loop. You are looking for the line of data that begins with “URL=”. Using an If . . . Then statement, you check the strLine variable to see whether it begins with the specified text. The StartsWith method of the String class, the class from which the strLine variable is derived, returns a Boolean value of True if the string that is being tested contains the string that is passed to this method and a value of False if it does not.

If the line of data being tested starts with the text “URL=”, then it is the actual URL that you want to save in the Url member of the class. This is done by using the SubString method to get the URL in the strLine variable minus the beginning text. In order to do this, you pass a starting position of 4 to the SubString method, telling it to start extracting data starting at position 4, because positions 0 – 3 contain the text “URL=”. Once you find the data that you are looking for and set the Url member, there’s no need to process the rest of the strLines array, so you exit the For . . . Next loop.

‘Process each line looking for the URL For Each strLine In strLines

‘Does the line of data start with URL= If strLine.StartsWith(“URL=”) Then

‘Yes, set the Url member to the actual URL Url = strLine.Substring(4)

‘Exit the For...Next loop Exit For

End If

Next

The Catch block will handle any IO exception that might be thrown. Here you want to return the exception back to the caller of this method, so you throw a new Exception and pass it the Message property of the IOExceptionErr variable. This gracefully handles any IO exceptions in this class and returns the message of the exception to the caller.

Catch IOExceptionErr As IOException

‘Return the exception to the caller

Throw New Exception(IOExceptionErr.Message)

End Try

End Sub

Scanning Favorites

So that you can scan the favorites, in the next Try It Out you add a couple of new classes to the project. The first, WebFavoriteCollection, will be used to hold a collection of WebFavorite objects. The second, Favorites, will physically scan the Favorites folder on the computer, create new WebFavorite objects, and add them to the collection.

355