The My Keyword

The My keyword is a novel concept that was introduced in the .NET Framework 2.0 to quickly give you access to your application, your users, your resources, the computer, or the network on which the application resides. The My keyword has been referred to as a way of speed-dialing common but complicated resources to which you need access. Using the My keyword, you can quickly access a wide variety of items, such as user details or specific settings of the requester browser.

Though not really considered a true namespace, the My object declarations that you make work in the same way as the .NET namespace structure you are used to working with. To give you an example, first look at how you get the user's machine name using the traditional namespace structure:

Environment.MachineName.ToString()

For this example, you simply need to use the Environment class and use this namespace to get at the MachineName property. The following shows how you would accomplish this same task using the My keyword:

My.Computer.Info.MachineName.ToString()

Looking at this example, you may be wondering what the point is if the example that uses My is lengthier than the first example, which just works off of the Environment namespace. Remember that the point is not the length of what you type to access specific classes, but a logical way to find frequently accessed resources without spending a lot of time hunting for them. Would you have known to look in the Environment class to get the machine name of the user's computer? Maybe, but maybe not. Using My.Computer.Info.MachineName.ToString is a tremendously more logical approach; and once compiled, this namespace declaration will be set to work with the same class as shown previously without a performance hit.

If you type the My keyword in your Windows Forms application, IntelliSense provides you with seven items to work with: Application, Computer, Forms, Resources, Settings, User, and WebServices. Though this keyword works best in the Windows Forms environment, there are still things that you can use in the Web Forms world. If you are working with a Web application, then you will have three items off the My keyword: Application, Computer, and User. Each of these is described further in the following sections.

My.Application

The My.Application namespace gives you quick access to specific settings and points that deal with your overall application. Table 2.3 details the properties and methods of the My.Application namespace.

Table 2.3 My.Application Properties and Methods

Property/Method Description
ApplicationContext Returns contextual information about the thread of the Windows Forms application.
ChangeCulture A method that enables you to change the culture of the current application thread.
ChangeUICulture A method that enables you to change the culture that is being used by the Resource Manager.
Culture Returns the current culture being used by the current thread.
Deployment Returns an instance of the ApplicationDeployment object, which allows for programmatic access to the application's ClickOnce features.
GetEnvironmentVariable A method that enables you to access the value of an environment variable.
Info Provides quick access to the assembly of Windows Forms. You can retrieve assembly information such as version number, name, title, copyright information, and more.
IsNetworkDeployed Returns a Boolean value that indicates whether the application was distributed via the network using the ClickOnce feature. If True, then the application was deployed using ClickOnce—otherwise False.
Log Enables you to write to your application's Event Log listeners.
MinimumSplashScreenDisplayTime Enables you to set the time for the splash screen.
OpenForms Returns a FormCollection object, which allows access to the properties of the forms currently open.
SaveMySettingsOnExit Provides the capability to save the user's settings upon exiting the application. This method works only for Windows Forms and console applications.
SplashScreen Enables you to programmatically assign the splash screen for the application.
UICulture Returns the current culture being used by the Resource Manager.

Much can be accomplished using the My.Application namespace. For an example of its use, you will focus on the Info property. This property provides access to the information stored in the application's AssemblyInfo.vb file, as well as other details about the class file. In one of your applications, you can create a message box that is displayed using the following code (code file: ProVB_NamespacesModule1.vb):

System.Windows.Forms.MessageBox.Show("Company Name: " & 
   My.Application.Info.CompanyName & vbCrLf &
   "Description: " & My.Application.Info.Description & vbCrLf &
   "Directory Path: " & My.Application.Info.DirectoryPath & vbCrLf &
   "Copyright: " & My.Application.Info.Copyright & vbCrLf &
   "Trademark: " & My.Application.Info.Trademark & vbCrLf &
   "Name: " & My.Application.Info.AssemblyName & vbCrLf &
   "Product Name: " & My.Application.Info.ProductName & vbCrLf &
   "Title: " & My.Application.Info.Title & vbCrLf &
   "Version: " & My.Application.Info.Version.ToString())

From this example, it is clear that you can get at quite a bit of information concerning the assembly of the running application. Running this code produces a message box similar to the one shown in Figure 2.13.

Figure 2.13 Project properties displayed in a message box

2.13

Another interesting property to look at from the My.Application namespace is the Log property. This property enables you to work with the log files for your application. For instance, you can easily write to the system's Application Event Log by first changing the application's app.config file to include the following (code file: ProVB_Namespacesapp.config.txt):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.diagnostics>
        <sources>
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="EventLog"/>
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="EventLog"
             type="System.Diagnostics.EventLogTraceListener"
             initializeData="ProVBEventWriter" />
        </sharedListeners>
    </system.diagnostics>
</configuration>

Once the configuration file is in place, you can record entries to the Application Event Log. Note that writing to the Application Event Log is a privileged action, and you need to have started Visual Studio 2012 as an administrator on your machine. However, the code shown in the following simple example can leverage the configuration settings previously shown to leave a message within the event log (code file: ProVB_NamespacesModule1.vb):

     My.Application.Log.WriteEntry("Entered Form1_Load", _
       TraceEventType.Information, 1)

You could also just as easily use the WriteExceptionEntry method in addition to the WriteEntry method. After running this application and looking in the Event Viewer, you will see the event shown in Figure 2.14.

Figure 2.14 Details from the Event Log

2.14

The previous example shows how to write to the Application Event Log when working with the objects that write to the event logs. In addition to the Application Event Log, there is also a Security Event Log and a System Event Log. Note that when using these objects, it is impossible to write to the Security Event Log, and it is only possible to write to the System Event Log if the application does it under either the Local System or the Administrator accounts.

In addition to writing to the Application Event Log, you can just as easily write to a text file. As with writing to the Application Event Log, writing to a text file also means that you need to make changes to the app.config file (code file: app.config to support writing to filelog):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.diagnostics>
        <sources>
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="EventLog"/>
                    <add name="FileLog" />
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="EventLog"
             type="System.Diagnostics.EventLogTraceListener"
             initializeData="ProVBEventWriter" />
            <add name="FileLog"
             type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
             Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
             PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
             initializeData="FileLogWriter"/>
        </sharedListeners>
    </system.diagnostics>
</configuration>

Now with this app.config file in place, you simply need to run the same WriteEntry method as before. This time, however, in addition to writing to the Application Event Log, the information is also written to a new text file. You can find the text file at C:Users[username]AppDataRoaming[AssemblyCompany][AssemblyProduct][Version]. For instance, in my example, the log file was found at C:UsersWSheldonAppDataRoamingMicrosoftProVB_Namespaces1.0.0.0. In the .log file found, you will see a line such as the following:

DefaultSource     Information     1     Entered Form1_Load

By default, it is separated by tabs, but you can change the delimiter yourself by adding a delimiter attribute to the FileLog section in the app.config file:

<add name="FileLog"
     type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
     Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
     PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
     initializeData="FileLogWriter" delimiter=";" />

In addition to writing to Event Logs and text files, you can also write to XML files, console applications, and more.

My.Computer

The My.Computer namespace can be used to work with the parameters and details of the computer in which the application is running. Table 2.4 details the objects contained in this namespace.

Table 2.4 My.Computer Objects

Property Description
Audio This object enables you to work with audio files from your application. This includes starting, stopping, and looping audio files.
Clipboard This object enables you to read and write to the clipboard.
Clock This enables access to the system clock to get at GMT and the local time of the computer running the application. You can also get at the tick count, which is the number of milliseconds that have elapsed since the computer was started.
FileSystem This object provides a large collection of properties and methods that enable programmatic access to drives, folders, and files. This includes the ability to read, write, and delete items in the file system.
Info This provides access to the computer's details, such as amount of memory, the operating system type, which assemblies are loaded, and the name of the computer itself.
Keyboard This object provides information about which keyboard keys are pressed by the end user. Also included is a single method, SendKeys, which enables you to send the pressed keys to the active form.
Mouse This provides a handful of properties that enable detection of the type of mouse installed, including details such as whether the left and right mouse buttons have been swapped, whether a mouse wheel exists, and how much to scroll when the user uses the wheel.
Name This is a read-only property that provides access to the name of the computer.
Network This object provides a single property and some methods that enable you to interact with the network to which the computer running the application is connected. With this object, you can use the IsAvailable property to first verify that the computer is connected to a network. If so, then the Network object enables you to upload or download files, and ping the network.
Ports This object can provide notification when ports are available, as well as allow access to the ports.
Registry This object provides programmatic access to the registry and the registry settings. Using the Registry object, you can determine whether keys exist, determine values, change values, and delete keys.
Screen This provides the capability to work with one or more screens that may be attached to the computer.

My.Resources

The My.Resources namespace is a very easy way to get at the resources stored in your application. If you open the MyResources.resx file from the My Project folder in your solution, you can easily create as many resources as you wish. For example, you could create a single String resource titled MyResourceString and give it a value of St. Louis Rams.

To access the resources that you create, use the simple reference shown here:

My.Resources.MyResourceString.ToString()

Using IntelliSense, all of your created resources will appear after you type the period after the MyResources string.

My.User

The My.User namespace enables you to work with the IPrincipal interface. You can use the My.User namespace to determine whether the user is authenticated or not, the user's name, and more. For instance, if you have a login form in your application, you could allow access to a particular form with code similar to the following:

If (Not My.User.IsInRole("Administrators")) Then
   ' Code here
End If
You can also just as easily get the user's name with the following:
        
My.User.Name
In addition, you can check whether the user is authenticated:
        
If My.User.IsAuthenticated Then
   ' Code here
End If

My.WebServices

When not using the My.WebServices namespace, you access your Web services references in a lengthier manner. The first step in either case is to make a Web reference to some remote XML Web Service in your solution. These references will then appear in the Web References folder in the Solution Explorer in Visual Studio 2012. Before the introduction of the My namespace, you would have accessed the values that the Web reference exposed in the following manner:

Dim ws As New RubiosMenu.GetMenuDetails
Label1.Text = ws.GetLatestPrice.ToString()

This works, but now with the My namespace, you can use the following construct:

Label1.Text = My.WebServices.GetMenuDetails.GetLatestPrice.ToString()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset