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

Beginning Visual Basic 2005 (2006)

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

Chapter 11

Try It Out

Scanning Favorites

1.Using the Solution Explorer, create a new class called WebFavoriteCollection. This class will be instantiated to an object that can hold a number of WebFavorite objects.

2.Add the highlighted code in your class:

Public Class WebFavoriteCollection

Inherits CollectionBase

Public Sub Add(ByVal Favorite As WebFavorite)

‘Add item to the collection

List.Add(Favorite)

End Sub

Public Sub Remove(ByVal Index As Integer) ‘Remove item from collection

If Index >= 0 And Index < Count Then

List.Remove(Index)

End If

End Sub

Public ReadOnly Property Item(ByVal Index As Integer) As WebFavorite

Get

‘Get an item from the collection by its index

Return CType(List.Item(Index), WebFavorite)

End Get

End Property

End Class

3.Create another new class called Favorites. This will be used to scan the Favorites folder and return a WebFavoriteCollection containing a WebFavorite object for each favorite in the folder. Like the WebFavorite class, this class will implement the IDisposable interface. Enter the following highlighted code and press Enter to add the properties and methods of the IDisposable interface to your class:

Public Class Favorites

Implements IDisposable

4.Next, add this member below the code for the IDisposable interface:

‘Public member

Public FavoritesCollection As WebFavoriteCollection

5.You need a read-only property that can return the path to the user’s Favorites folder. Add the following code to the Favorites class:

Public ReadOnly Property FavoritesFolder() As String

Get

‘Return the path to the user’s Favorites folder Return Environment.GetFolderPath( _

356

Advanced Object-Oriented Techniques

Environment.SpecialFolder.Favorites)

End Get

End Property

6.Finally, you need a method that’s capable of scanning through the Favorites folder looking for files. When it finds one, it will create a WebFavorite object and add it to the Favorites collection. You provide two versions of this method — one that automatically determines the path of the favorites by using the FavoritesFolder property and one that scans through a given folder. To create this overloaded method, add the following code to the Favorites class:

Public Sub ScanFavorites()

‘Scan the Favorites folder

ScanFavorites(FavoritesFolder)

End Sub

Public Sub ScanFavorites(ByVal folderName As String)

‘If the FavoritesCollection member has not been instantiated ‘then instaniate it

If FavoritesCollection Is Nothing Then FavoritesCollection = New WebFavoriteCollection

End If

‘Process each file in the Favorites folder For Each strFile As String In _

My.Computer.FileSystem.GetFiles(folderName)

‘If the file has a url extension...

If strFile.EndsWith(“.url”, True, Nothing) Then

Try

‘Create and use a new instanace of the ‘WebFavorite class

Using objWebFavorite As New WebFavorite ‘Load the file information objWebFavorite.Load(strFile)

‘Add the object to the collection FavoritesCollection.Add(objWebFavorite)

End Using

Catch ExceptionErr As Exception ‘Return the exception to the caller

Throw New Exception(ExceptionErr.Message) End Try

End If

Next

End Sub

To make all of this work, you need to have the Favorites Viewer project create an instance of a Favorites object, scan the favorites, and add each one it finds to the list. This will be done in the next Try It Out.

357

Chapter 11

How It Works

There’s a lot to take in there, but a good starting point is the WebFavoriteCollection class. This illustrates an important best practice when working with lists of objects. As you saw in Chapter 5, you can hold lists of objects in one of two ways: in an array or in a collection.

When building classes that work with lists, the best practice is to use a collection. You should build collections that are also tied into using whatever types you’re working with, so in this example you built a WebFavoriteCollection class that exclusively holds a collection of WebFavorite objects.

You derived WebFavoriteCollection from CollectionBase. This provides the basic list that the collection will use:

Public Class WebFavoriteCollection

Inherits CollectionBase

To fit in with the .NET Framework’s way of doing things, you need to define three methods on a collection that you build. The Add method adds an item to the collection:

Public Sub Add(ByVal Favorite As WebFavorite)

‘Add item to the collection

List.Add(Favorite)

End Sub

The List property is a protected member of CollectionBase that only code within classes inheriting from CollectionBase can access. You access this property to add, remove, and find items in the list. You can see from the Add method here that you specified that the item must be a WebFavorite object. This is why you’re supposed to build collections using this technique — because you can add objects only of type WebFavorite; anyone who has hold of a WebFavoriteCollection object knows that it will contain objects only of type WebFavorite. This makes life much easier for users, because they will not get nasty surprises when they discover it contains something else, and therefore reduces the chance of errors. The Remove method that you built removes an item from the list:

Public Sub Remove(ByVal Index As Integer)

‘Remove item from collection

If Index >= 0 And Index < Count Then

List.Remove(Index)

End If

End Sub

The Item method lets you get an item from the list when given a specific index:

Public ReadOnly Property Item(ByVal Index As Integer) As WebFavorite

Get

‘Get an item from the collection by its index

Return CType(List.Item(Index), WebFavorite)

End Get

End Property

So how do you populate this collection? Well, in the Favorites class you built an overloaded method called ScanFavorites. The second version of this method takes a folder and examines it for files that end in .url. But before you look at that, you need to look at the FavoritesFolder property.

358

Advanced Object-Oriented Techniques

Since the location of the Favorites folder can change depending on the currently logged-in user, you have to ask Windows where this folder actually is. To do this, you use the shared GetFolderPath method of the System.Environment class:

Public ReadOnly Property FavoritesFolder() As String

Get

‘Return the path to the user’s Favorites folder

Return Environment.GetFolderPath( _

Environment.SpecialFolder.Favorites)

End Get

End Property

The GetFolderPath method uses one of the constants from the Environment.SpecialFolder enumeration. This enumeration provides constants for many different special folders that you are likely to need access to when writing applications.

When the application asks this class to load in the favorites from the Favorites folder, it calls Scan Favorites. The first version of this method accepts no parameters. It looks up the location of the user’s Favorites folder and passes that to the second version of this overloaded method:

Public Sub ScanFavorites()

‘Scan the Favorites folder

ScanFavorites(FavoritesFolder)

End Sub

The first thing that the second version of this overloaded method does is check to ensure that the

FavoritesCollection member has been instantiated using the WebFavoriteCollection class. If it hasn’t, it instantiates this member using that class.

Public Sub ScanFavorites(ByVal folderName As String)

‘If the FavoritesCollection member has not been instantiated ‘then instaniate it

If FavoritesCollection Is Nothing Then FavoritesCollection = New WebFavoriteCollection

End If

Now you want to get a list of files in the Favorites folder and process them. You do this by calling the GetFiles method in the FileSystem class and passing it the path and name of the Favorites folder. This class exists in the My.Computer namespace as indicated by the following code.

The GetFiles method returns an array of filenames, and you process this array using a For Each . . .

Next loop. You declare the variable, strFile, in-line in the For Each loop, as indicated in the following code, and this variable will be set to a filename in the Favorites folder for each iteration of the loop.

‘Process each file in the Favorites folder For Each strFile As String In _

My.Computer.FileSystem.GetFiles(folderName)

Within the loop, you first test the filename to see whether it is a Favorites file by checking to see whether it contains a .url file extension. The strFile variable is derived from the String class; thus you can use the EndsWith method to determine whether the filename ends with the .url file extension.

359

Chapter 11

The EndsWith method is an overloaded method, and the version that you are using here accepts three parameters. The first parameter accepts the value to be compared to the end of the string, and here you supply the text .url. The next parameter accepts a Boolean value indicating whether the EndsWith method should ignore the case of the text when making the comparison. You do want to ignore the case when making the comparison, so you pass a value of True for this parameter. The final parameter accepts the culture information that will be used when making the comparison. Passing a value of Nothing here indicates that you want to use the current culture information defined on the user’s computer.

‘If the file has a url extension...

If strFile.EndsWith(“.url”, True, Nothing) Then

If the filename being processed does contain the .url file extension, then you want to load the file information and have it added to the Favorites collection. Since you are using the WebFavorite class and this class reads the file, the potential for an exception exists. Therefore, you need to encapsulate the next block of code in a Try . . . Catch block to handle any exceptions that might be thrown by the

WebFavorite class.

The first thing that you do in the Try block is use a Using . . . End Using block to declare, instantiate, use, and destroy the WebFavorite class. Remember that you can use the Using statement only with a class that implements the IDisposable interface, which is why you added that interface to the Web Favorite class.

The first thing that you do in the Using . . . End Using block is call the Load method on the objWeb Favorite object, passing it the filename of the favorite’s shortcut file. Then you add the objWeb Favorite to the Favorites collection.

Try

‘Create and use a new instanace of the ‘WebFavorite class

Using objWebFavorite As New WebFavorite ‘Load the file information objWebFavorite.Load(strFile)

‘Add the object to the collection FavoritesCollection.Add(objWebFavorite)

End Using

The Catch block contains the necessary code to handle an exception that might be thrown by the WebFavorite class and to return that exception to the caller of this method. This is done by throwing a new Exception, passing it the message received in the ExceptionErr variable.

Catch ExceptionErr As Exception

‘Return the exception to the caller

Throw New Exception(ExceptionErr.Message)

End Try

End If

Next

End Sub

360

Advanced Object-Oriented Techniques

In this next Try It Out, you’ll implement the functionality in your form to use the Favorites class to gather all of your Internet Favorites and the WebFavorite class to load those shortcuts in the list view control on your form.

Try It Out

Creating an Instance of a Favorites Object

1.In the form code, select (Form1 Events) in the Class Name combo box and select Load in the Method Name combo box. Add the highlighted code:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

Try

‘Create and use a new instanace of the Favorites class Using objFavorites As New Favorites

‘Scan the Favorites folder objFavorites.ScanFavorites()

‘Process each objWebFavorite object in the ‘favorites collection

For Each objWebFavorite As WebFavorite In _ objFavorites.FavoritesCollection

‘Declare a ListViewItem object

Dim objListViewItem As New ListViewItem

‘Set the properties of the ListViewItem object objListViewItem.Text = objWebFavorite.Name objListViewItem.SubItems.Add(objWebFavorite.Url) ‘Add the ListViewItem object to the ListView lstFavorites.Items.Add(objListViewItem)

Next

End Using

Catch ExceptionErr As Exception

‘Display the error

MessageBox.Show(ExceptionErr.Message, “Favorites Viewer”, _

MessageBoxButtons.OK, MessageBoxIcon.Warning)

End Try

End Sub

2.Run the project and you should see something like Figure 11-6.

How It Works

Since both the Favorites and WebFavorite classes can throw an exception, you must handle any exceptions that might be thrown. Therefore, all of your code is encapsulated in a Try . . . Catch block. You use a Using . . . End Using statement to declare, instantiate, and destroy the object created using the Favorites class. Regardless of whether this class throws an exception, the Using statement will destroy the objFavorites object that it declares.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

361

Chapter 11

Try

‘Create and use a new instanace of the Favorites class Using objFavorites As New Favorites

Figure 11-6

Inside the Using . . . End Using block you have the objFavorites object scan the users Favorites folder by calling the ScanFavorites method. The effect here is that a new WebFavoritesCollection object will be created and filled and will be accessible through the FavoritesCollection property.

‘Scan the Favorites folder objFavorites.ScanFavorites()

After the ScanFavorites method has finished, you take each WebFavorite in the Favorites Collection and add it to the list view control on your form. You do this by first declaring a ListView Item and then setting the Text property to the Favorite name. Then you add the URL of the favorite to the SubItems collection, and finally you add the objListViewItem to the Items collection of the list view control.

‘Process each objWebFavorite object in the ‘favorites collection

For Each objWebFavorite As WebFavorite In _ objFavorites.FavoritesCollection

‘Declare a ListViewItem object

Dim objListViewItem As New ListViewItem

‘Set the properties of the ListViewItem object objListViewItem.Text = objWebFavorite.Name objListViewItem.SubItems.Add(objWebFavorite.Url) ‘Add the ListViewItem object to the ListView lstFavorites.Items.Add(objListViewItem)

Next

End Using

362

Advanced Object-Oriented Techniques

You wrap up this code with the Catch block, which will handle any exceptions thrown and display the exception message in a message box dialog box.

Catch ExceptionErr As Exception

‘Display the error

MessageBox.Show(ExceptionErr.Message, “Favorites Viewer”, _

MessageBoxButtons.OK, MessageBoxIcon.Warning)

End Try

End Sub

That’s it! Now you can display a list of the favorites installed on the user’s machine. However, you can’t actually view favorites, so let’s look at that now.

Viewing Favorites

Now that all of your code is in place to retrieve and display a list of favorites, in the next Try It Out you’ll to add some code to display the selected favorite in the LinkLabel control on your form and then add some code to the control to process the selected link in Internet Explorer.

Try It Out

Viewing Favorites

1.In the Code Editor for Form1, click lstFavorites in the Class Name combo box and the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

Private Sub lstFavorites_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles lstFavorites.Click

‘Update the link label control Text property

lnkUrl.Text = “Visit “ & lstFavorites.SelectedItems.Item(0).Text

‘Clear the default hyperlink lnkUrl.Links.Clear()

‘Add the selected hyperlink to the LinkCollection lnkUrl.Links.Add(6, lstFavorites.SelectedItems.Item(0).Text.Length, _

lstFavorites.SelectedItems.Item(0).SubItems(1).Text)

End Sub

2.Next, click lnkUrl in the Class Name combo box and select the LinkClicked event in the Method Name combo box. Add the following highlighted code to the LinkClicked event:

Private Sub

lnkUrl_LinkClicked(ByVal sender As Object, _

ByVal e

As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _

Handles

lnkUrl.LinkClicked

‘Process the selected link

Process.Start(e.Link.LinkData)

End Sub

363

Chapter 11

3.Run the project. You should now see that when a URL is selected from the list, the LinkLabel control changes to reflect the name of the selected item. (Refer to Figure 11-4.) If you click the link, Internet Explorer will open the URL in the LinkLabel control’s LinkCollection.

How It Works

When you click an item in the list view control, the Click event is fired for that control. You added code the Click event to load the link label control with the selected link. You start by first setting the Text property of the LinkLabel control. This is the text that will be displayed on the form as shown in Figure 11-4.

You set the Text property using the static text “Visit followed by the actual favorite name. The Favorite name is retrieved from the list view control’s Item collection. Each row in the list view control is called an item and the first column contains the text of the item. Each column past the first column in a row is called a sub item and is a sub item of the item (the text in the first column). The text that gets displayed in the link label is taken from the Text property of the Item collection.

Private Sub lstFavorites_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles lstFavorites.Click

‘Update the link label control Text property

lnkUrl.Text = “Visit “ & lstFavorites.SelectedItems.Item(0).Text

The Links property of the LinkLabel control contains a LinkCollection that contains a default hyperlink consisting of the text that is displayed in the LinkLabel control. You want to clear this collection and set it using the correct hyperlink for the selected Favorite. You do this by calling the Clear method on the Links property.

‘Clear the default hyperlink lnkUrl.Links.Clear()

Finally, you want to add your hyperlink using the subitem of the selected item in the ListView control. The Add method of the Links property is an overloaded method, and the method that you are using here expects three parameters: start, length, and linkdata. The start parameter specifies the starting position of the text in the Text property that you want as the hyperlink, and the length parameter specifies how long the hyperlink should be.

You do not want the word “Visit” to be part of the hyperlink, so you specify the starting position to be 6, which also accounts for the space after the word “Visit”. Then you specify the length parameter using the Length property of the Text property of selected item in the list view control. Finally, you need to specify the linkdata parameter by specifying the selected subitem from the list view control. This sub item contains the actual URL for the favorite.

‘Add the selected hyperlink to the LinkCollection lnkUrl.Links.Add(6, lstFavorites.SelectedItems.Item(0).Text.Length, _

lstFavorites.SelectedItems.Item(0).SubItems(1).Text)

End Sub

When a hyperlink on the LinkLabel control is clicked, it fires the LinkClicked event, and this is where you have placed your code to process the hyperlink of the favorite being displayed in this control. The LinkLabelLinkClickedEventArgs class contains information about the link label and, in particular, the actual hyperlink in the LinkCollection.

364

Advanced Object-Oriented Techniques

To retrieve the hyperlink, you access the LinkData property of the Link property. Then you pass this data to the Start method of the Process class, which will cause a browser to be opened and to display the selected hyperlink.

Private Sub

lnkUrl_LinkClicked(ByVal sender As Object, _

ByVal e

As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _

Handles

lnkUrl.LinkClicked

‘Process the selected link Process.Start(e.Link.LinkData)

End Sub

An Alternative Favorite Viewer

You know that building separate classes promotes code reuse, but let’s prove that. If code reuse is such a hot idea, you should be able to build another application that can use the functionality in the classes to find and open favorites without having to rewrite or change any of the code.

In this case, you might have given a colleague the Favorites, WebFavorite, and WebFavorite Collection classes, and that colleague should be able to build a new application that uses this functionality without having to understand the internals of how Internet shortcuts work or how Windows stores the user’s favorites.

Building a Favorites Tray

In this section, you build an application that displays a small icon on the system tray. Clicking this icon will open a list of the user’s favorites as a menu, as shown in Figure 11-7. Clicking a favorite automatically opens Internet Explorer to the URL.

Figure 11-7

To demonstrate this principle of code reuse, you need to create a new Visual Basic 2005 project.

Try It Out

Building a Favorites Tray

1.Using Visual Studio, select File Add New Project from the menu and create a new Visual Basic 2005 Windows Application project called Favorites Tray.

365