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

Professional Visual Studio 2005 (2006) [eng]

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

Chapter 24

Using My in Code

Utilizing the My objects in your application code is straightforward in most Windows and web-based projects (see the “Contextual My” section later in this chapter). Because the underlying real namespace is implicitly referenced and any necessary objects are created for you automatically, all you need to do is reference the object property or method you wish to use.

The fully qualified name is documented as Microsoft.VisualBasic.MyServices, but as you’ll see in a moment, for project types that do not implicitly support My, you can still use it through the

Microsoft.VisualBasic.Devices namespace.

As an example, consider the following code snippet that evaluates the user identity and role attached to the thread running an application:

Private Sub OK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles OK.Click

If My.User.IsAuthenticated Then

If My.User.IsInRole(“Administrators”) Then My.Application.Log.WriteEntry(“User “ & My.User.Name & _

“ logged in as Administrator”, TraceEventType.Information)

Else

My.Application.Log.WriteEntry(“User “ & My.User.Name & _

“ does not have correct priveleges.”, TraceEventType.Error)

End If End If

...

End Sub

The code is fairly straightforward, with the various My object properties and methods defined with readable terms such as IsAuthenticated and WriteEntry. However, the code to attach to the current principal, extract the authentication state, determine what roles it belongs to, and then write to an application log were all reasonably nontrivial tasks prior to the introduction of My to the developer’s toolbox.

Every My object provides vital shortcuts to solve commonly faced scenarios by both Windows and web developers, as this example intimates. Microsoft did a great job in creating this namespace for developers and has definitely brought the concept of ease of use back home to Visual Basic programmers in particular.

Using My in C#

Although My is widely available in Visual Basic projects, other languages such as C# can take advantage of the shortcuts as well. As previously mentioned, this is because the My namespace actually sits on a real .NET Framework 2.0 namespace called Microsoft.VisualBasic.Devices for most of its objects. For example, if you want to use the My.Audio or My.Keyboard objects in a Windows application being developed in C# you can.

To access the My objects, you will first need to add a reference to the main Visual Basic library (which also contains other commonly used Visual Basic constructs such as enumerations and classes) in your project. The simplest way to do this is to right-click the References node in the Solution Explorer for the project to which you’re adding My support, and choose Add Reference from the context menu.

316

The My Namespace

After a moment, the References dialog window will be displayed, defaulting to the .NET components. Scroll through the list until you locate Microsoft.VisualBasic and click OK to add the reference. At this point you’re ready to use My, but you’ll need to prefix all of your references to My objects with the rather wordy Microsoft.VisualBasic.Devices namespace prefix. To keep your coding to a minimum, you can add a using statement to implicitly reference the objects. The result is code similar to the following listing:

using System;

...

using System.Windows.Forms;

using Microsoft.VisualBasic.Devices;

namespace WindowsApplication1

{

public partial class Form1 : Form

{

...

private void Form1_Load(object sender, EventArgs e)

{

Keyboard MyKeyboard = new Keyboard(); if (MyKeyboard.ScrollLock == true)

{

MessageBox.Show(“Scroll Lock Is On!”);

}

}

}

}

Note that not all My objects are available outside Visual Basic. However, there is usually a way to access the functionality through other standard Visual Basic namespace objects. A prime example of this issue is the FileSystemProxy, which is used by the My.Computer object to provide more efficient access to the FileSystem object.

Unfortunately for C# developers, this proxy class is not available to their code (although interestingly J# programmers can harness it). Rather than utilize My for this purpose, C# programmers still can take advantage of Visual Basic’s specialized namespace objects. In this case, C# code should simply use the

Microsoft.VisualBasic.FileIO.FileSystem object to achieve the same results.

Contextual My

While ten My objects are available for your use, only a subset is ever available in any given project. In addition, some of the My classes have a variety of forms that provide different information and methods depending on the context.

By dividing application development projects into three broad categories, you can see how the My classes logically fit into different project types. The first category of development scenarios is Windows-based applications. Three kinds of projects fall into this area — Windows applications for general application development, Windows Control Libraries used to create custom user controls for use in Windows applications, and Windows Services that are designed to run in the services environment of Windows itself. The following table shows which classes these project types can access:

317

Chapter 24

My Class

Applications

Control Libraries

Services

 

 

 

 

My.Application

Available

Available

Available

My.Computer

Available

Available

Available

My.Forms

Available

Available

 

My.Log

 

 

 

My.Request

 

 

 

My.Resources

Available

Available

Available

My.Response

 

 

 

My.Settings

Available

Available

Available

My.User

Available

Available

Available

My.WebServices

Available

Available

Available

 

 

 

 

As you can see, the available classes are logical — for example, there’s no reason why Windows Services applications need general access to a My.Forms collection, as they do not have Windows Forms.

All three project types use a variant of the My.Computer class related to Windows applications. It is based on the server-based version of My.Computer, which is used for web development but includes additional objects usually found on client machines, such as keyboard and mouse classes. The My.User class is also a Windows version, which is based on the current user authentication (well, to be accurate, it’s actually based on the current thread’s authentication).

However, each of the three project types for Windows development uses different variations of the My.Application class. The lowest common denominator is the Library version of My.Application, which provides you with access to fundamental features in the application such as version information and the application log. The Windows Control Library projects use this version.

Windows Services projects use a customized version of My.Application that inherits from this Library version and add extra methods for accessing information such as command-line arguments. Windows Application projects take this console version and add even more information for accessing the forms found in the application, among other things.

Web development projects can use a very different set of My classes. It doesn’t make sense for them to have My.Application or My.Forms, for instance, as they cannot have this Windows client-based information. Instead, you have access to the web-based My objects, as indicated in the following table:

My Class

Sites

Control Libraries

My.Application

 

 

My.Computer

Available

Available

My.Forms

 

 

My.Log

Available

 

318

 

 

 

The My Namespace

 

 

 

 

 

My Class

Sites

Control Libraries

 

 

 

 

 

My.Request

Available

 

 

My.Resources

 

Available

 

My.Response

Available

 

 

My.Settings

 

Available

 

My.User

Available

Available

 

My.WebServices

 

Available

 

 

 

 

The Web Project styles use a different version of the My.Computer object. In these cases, the information is quite basic and excludes all the normal Windows-oriented properties and methods. In fact, these two project types use the same My.Computer version as Windows Services.

My.User is also different from the Windows version. It associates its properties with the identity of the application context.

Finally, some project types don’t fit directly into either the Windows-based application development model or the web-based projects. Project types such as console applications and general class libraries (DLLs) fall into this category, as do solutions that begin empty or fit into any other type not covered by the previous categories. Empty solutions do not have access to any part of the My namespace, while these other project types have access to another set of My objects, as shown in the following table:

My Class

Class Library

Console App

 

 

 

My.Application

Y* 2

Y*3

My.Computer

Available

Available

My.Forms

 

 

My.Log

 

 

My.Request

 

 

My.Resources

Available

Available

My.Response

 

 

My.Settings

Available

Available

My.User

Available

Available

My.WebServices

Available

Available

 

 

 

The first thing you’ll notice in this table is that projects that don’t fit into any of the standard types do not have direct access to any of the My objects at all. This doesn’t prevent you from using them in a similar fashion, as discussed earlier with C# usage of My.

319

Chapter 24

The My.Computer object that is exposed to class libraries and console applications is the same version as the one used by the Windows project types — you get access to all the Windows properties and methods associated with the My.Computer object. The same goes for My.User, with any user information being accessed relating to the thread’s associated user identity.

What can these different objects do for you? The next section delves into each of the main My objects and describes how they can be used in your projects to make your coding much more efficient.

Default Instances

Several of the My objects use default instances of the objects in your project. A default instance is an object that is automatically instantiated by the .NET runtime, which you can then reference in your code. For example, instead of defining and creating a new instance of a form, you can simply refer to its default instance in the My.Forms form collection. My.Resources works in a similar fashion by giving you direct references to each resource object in your solution, while My.WebServices provides proxy objects for each web service reference added to your project so you don’t even need to create those.

Using the default instances is straightforward — simply refer to the object by name in the appropriate collection. To show a form named Form1, you would use My.Forms.Form1.Show, while calling a web service named CalcWS would be achieved by using the My.WebServices.CalcWS object.

My.Application

The My.Application object gives you immediate access to various pieces of information about the application. At the lowest level, My.Application allows you to write to the application log through the subordinate My.Application.Log as well as to add general information that is common to all Windows-based projects in the My.Application.Info object.

As mentioned earlier, if the context of My.Application is a Windows service, it also includes information related to the command-line arguments and the method of deployment. Windows Forms applications have all this information in the contextual form My.Application and enable the accessing of various forms-related data.

Prior to My, all of this information was accessible through a variety of methods but it was difficult to determine where some of the information was. Now the information is all consolidated into one easy-to- use location. To demonstrate the kind of data you can access through My.Application, try the following sample task:

1.Start Visual Studio 2005 and create a basic Windows application. Add a button to the form. You’ll use the button to display information about the application.

2.Double-click the My Project node in the Solution Explorer to access the Solution properties. In the Application page, click Assembly Information and set the Title, Copyright, and Assembly Version fields to something you’ll recognize and click OK to save the settings.

3.Return to the Form1 Design view and double-click it to have Visual Studio automatically generate a stub for the button’s Click event. Add the following code:

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click

320

The My Namespace

Dim ApplicationMessage As String = vbNullString

With My.Application

With .Info

ApplicationMessage &= .Title & vbCrLf

ApplicationMessage &= .Version.ToString & vbCrLf

ApplicationMessage &= .Copyright & vbCrLf

End With

ApplicationMessage &= .CommandLineArgs.Count & vbCrLf

ApplicationMessage &= .OpenForms(0).Name

End With

MessageBox.Show(ApplicationMessage)

End Sub

This demonstrates the use of properties available to all My-compatible applications in the My.Application.Info object, then to Windows Services and Windows Forms applications with the CommandLineArgs property, and then finally information that’s only accessible in Windows Forms applications.

4.Run the application and click the button on the form and you will get a dialog similar to the one shown in Figure 24-2.

Figure 24-2

Using the information in My.Application is especially useful when you need to give feedback to your users about what version of the solution is running. It can also be used internally to make logical decisions about what functionality should be performed based on active forms and version information.

My.Computer

My.Computer is by far the largest object in the My namespace. In fact, it has ten subordinate objects that can be used to access various parts of the computer system, such as keyboard, mouse, and network. Besides these ten objects, the main property that My.Computer exposes is the machine name, through the conveniently named Name property.

321

Chapter 24

My.Computer.Audio

The My.Computer.Audio object gives you the capability to play system and user sound files without needing to create objects and use various API calls. There are two main functions within this object:

PlaySystemSound will play one of the five basic system sounds.

Play will play a specified audio file. You can optionally choose to have the sound file play in the background and even loop continuously. You can halt a background loop with the Stop method.

The following snippet of code illustrates how to use these functions:

My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)

My.Computer.Audio.Play(“C:\MySoundFile.wav”, AudioPlayMode.BackgroundLoop)

My.Computer.Audio.Stop()

My.Computer.Clipboard

The Windows clipboard has come a long way since the days when it could only store simple text. Now you can copy and paste images, audio files, file and folder lists, and text. The My.Computer.Clipboard object provides access to all of this functionality, giving you the ability to store and retrieve items of the aforementioned types as well as custom data specific to your particular application.

Three main groups of methods are used in My.Computer.Clipboard Contains, Get, and Set. The Contains methods are used to check the clipboard for a specific type of data. For example, ContainsAudio will have a value of True if the clipboard contains audio data. GetAudio will retrieve the audio data in the clipboard (if there is some), and the other Get methods are similar in functionality for their own types. Finally, SetAudio stores audio data in the clipboard, while the other Set methods will do the same for the other types of data.

The only exceptions to this are the ContainsData, GetData, and SetData methods. These three methods enable you to store and retrieve custom data for your application in any format you like, taking a parameter identifying the custom data type. The advantage of using these is that if you have sensitive data that you allow the user to copy and paste within your application, you can preclude it from being accidentally pasted into other applications by using your own format.

To reset the clipboard entirely, use the Clear method.

My.Computer.Clock

Previously, an often frustrating task for some developers was converting the current system time to a standard GMT time, but with My.Computer.Clock it’s easy. This object exposes the current time in both local and GMT formats as Date type variables with LocalTime and GmtTime properties.

In addition, you can retrieve the system timer of the computer with the TickCount property.

322

The My Namespace

My.Computer.FileSystem

Accessing the computer file system usually involves creating multiple objects and having them all refer to each other in ways that sometimes appear illogical. The My.Computer.FileSystem object does away with all the confusion with a central location for all file activities, whether it’s just file manipulation such as copying, renaming, or deleting files or directories, or reading and writing to a file’s contents.

The following sample routine searches for files containing the word loser in the C:\Temp directory, deleting each file that’s found:

Dim foundList As System.Collections.ObjectModel.ReadOnlyCollection (Of String) foundList = My.Computer.FileSystem.FindInFiles(“C:\Temp”, “loser”, True, _

FileIO.SearchOption.SearchTopLevelOnly)

For Each thisFileName As String In foundList

My.Computer.FileSystem.DeleteFile(thisFileName)

Next

My.Computer.Info

Similar to the Info object that is part of My.Application, the My.Computer.Info object exposes information about the computer system. Notably, it returns memory status information about the computer and the installed operating system. The important properties are listed in the following table:

Property

Description

 

 

AvailablePhysicalMemory

The amount of physical memory free on the computer

TotalPhysicalMemory

The total amount of physical memory on the computer

AvailableVirtualMemory

The amount of virtual addressing space available

TotalVirtualMemory

The total amount of virtual addressable space

OSFullName

The full operating system, such as Microsoft Windows XP

 

Professional

OSPlatform

The platform identifier, such as Win32NT

OSVersion

The full version of the operating system

 

 

My.Computer.Keyboard and My.Computer.Mouse

The My.Computer.Keyboard and My.Computer.Mouse objects return information about the currently installed keyboard and mouse on your computer, respectively. The Mouse object will let you know if there is a scroll wheel, how much the screen should scroll if it’s used, and whether the mouse buttons have been swapped.

My.Computer.Keyboard provides information about the various control keys such as Shift, Alt, and Ctrl, as well as keyboard states such as Caps Lock, Num Lock, and Scroll Lock. You can use this information to affect the behavior of your application in response to the specific combination of keys.

323

Chapter 24

The My.Computer.Keyboard object also exposes the SendKeys method that many Visual Basic programmers use to simulate keystrokes.

My.Computer.Network

At first glance, the My.Computer.Network object may look underwhelming. It has only a single property that indicates whether the network is available or not — IsAvailable. However, in addition to this property, My.Computer.Network has three methods that can be used to send and retrieve files across the network or web:

Ping: Use Ping to determine whether the remote location you intend to use is reachable with the current network state.

DownloadFile: Specify the remote location and where you want the file to be downloaded.

UploadFile: Specify the file to be uploaded and the remote location’s address.

Of course, networks can be unstable, particularly if you’re talking about the web; and that’s where the

NetworkAvailabilityChanged event comes to the rescue. The My.Computer.Network object exposes this event for you to handle in your application, which you can do by defining an event handler routine and attaching it to the event:

Public Sub MyNetworkAvailabilityChangedHandler( ByVal sender As Object, _ ByVal e As Devices.NetworkAvailableEventArgs)

... do your code. End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

AddHandler My.Computer.Network.NetworkAvailabilityChanged, _

AddressOf MyNetworkAvailabilityChangedHandler

End Sub

You can then address any network work your application might be doing when the network goes down, or even kick off background transfers when your application detects that the network has become available again.

My.Computer.Ports

The My.Computer.Ports object exposes any serial ports available on the computer through the SerialPortNames property. You can then use OpenSerialPort to open a specific port and write to it using standard I/O methods.

My.Computer.Registry

Traditionally, the Windows registry has been dangerous to play around with — so much so, in fact, that Microsoft originally cordoned off Visual Basic programmers’ access to only a small subset of the entire registry key set.

My.Computer.Registry provides a reasonably safe way to access the entire registry. You can still mess things up, but because its methods and properties are easy to use, there’s less likelihood of such a mistake happening.

324

The My Namespace

Each of the main root keys in the registry is referenced by a specific property of My.Computer.Registry, and you can use GetValue and SetValue in conjunction with these root properties to enable your application access to any data that the end user can access.

For instance, to determine whether a particular registry key exists, you can use the following snippet:

If My.Computer.Registry.GetValue(“HKEY_LOCAL_MACHINE\MyApp”, “Value”, Nothing) _

Is Nothing Then

MessageBox.Show(“Value not there.”)

End If

My.Forms and My.WebSer vices

My.Forms gives you access to the forms in your application. The advantage this object has over the old way of using your forms is that it provides a default instance of each form so you don’t need to define and instantiate them manually. Whereas before you would write

Dim mMyForm As New Form1

mMyForm.Show

now you can simply code

My.Forms.Form1.Show

Each form has a corresponding property exposed in the My.Forms object. You can determine which forms are currently open using the My.Application.OpenForms collection.

My.WebServices performs a similar function but for, you guessed it, the web services you’ve defined in your project. If you add a reference to a web service and name the reference MyCalcWS, you can use the My.WebServices.MyCalcWS instance of the web service proxy, rather than instantiate your own each time you need to call it.

My For the Web

When building web applications, you can use the My.Request and My.Response objects to set and retrieve the HTTP request and HTTP response information. This is a godsend to any developer who has tried to maintain these objects in the past and found it difficult to remember where the information was located.

These objects are basically System.Web.HTTPRequest and System.Web.HTTPResponse classes, but you don’t have to worry about the context of which page has what data because they’re referring to the current page.

My.Resources

.NET applications can have many types of embedded resource objects. Visual Studio 2005 has an easy way of adding resource objects in the form of the Resources page of My Project in Visual Basic, or the corresponding Properties area in C#. My.Resources makes using these resources in code just as easy.

325