My Walkthroughs

 

Joseph Binder and Cat Francis
Microsoft Corporation

July 2004

Applies to
   Microsoft Visual Basic .NET
   Microsoft Visual Basic .NET My features
   Microsoft Visual Studio 2005

Summary: This paper lists core My features in Visual Basic .NET and provides common examples of how to consume each feature. (11 printed pages)

Contents

Introduction
Retrieving Application Information
Application Logging
Performing Network Tasks
Additional Tasks
Working with Files
Parsing Text Files
Working with the Registry
Getting Information About the Computer
Using Resources
Reading and Changing Application Settings
Handling Application Events
Getting Information about the User
Conclusion

Introduction

These scenarios provide coverage of core My features and exemplify the patterns in which we expect the features to be consumed.

Retrieving Application Information

Through the My.Application.AssemblyInfo object, My provides access to information pertinent to your application, such as its title, description, copyright message, and more.

To Access Application Information

  1. Create a new Windows application.
  2. In the Project menu, open the Project Designer by clicking Properties (the last item in the list).
  3. On the Application tab, click the Assembly Information button to open the Assembly Information dialog box. Enter text for the title, copyright, and remaining forms.
  4. Place textboxes or labels on the main form of the application to display the information entered in the Project Designer.
  5. In the Form_Load event handler, use My to populate the controls with the appropriate information. For example, this code displays the description text in Label1.
    Label1.Text = My.Application.AssemblyInfo.Description
    

Application Logging

My.Application.Log provides a simple, accessible entry point into the powerful logging functionality in the .NET Framework. Its default behavior provides logical routing and formatting of log messages, while the configuration model leveraged from the System.Diagnostic.TraceSource allows the formatting, filtering, and routing of My.Application.Log to be customized by the user.

To Write a Log Message Using the Default Configuration

  1. Create a new Windows application.

  2. In the Application Startup event handler, write a log message using My.Application.Log.WriteEntry. This code writes the string Application starting.

    My.Application.Log.WriteEntry("Application starting")
    

  3. In the Application Shutdown event handler, use My.Application.Log.WriteEntry again to write an entry. This code writes the string Application shutting down.

    My.Application.Log.WriteEntry( "Application shutting down" )
    

  4. Run the application.

  5. Close the application.

  6. Open the log file (it appears in the Application Data directory) and verify that the messages were written.

To Write a Log Message Using a Custom Configuration

  1. Create a new Windows application.

  2. Open the app.config file by clicking it in the Solution Explorer.

  3. In the Form_Load event handler for the application, write the following lines of code.

    My.Application.Log.WriteEntry( "Error Message", TraceLevel.Error )
    My.Application.Log.WriteEntry( "Info Message", TraceLevel.Info )
    

  4. Open the following directory under your Documents And Settings directory: \Application Data\Microsoft Corporation\Microsoft Visual Studio\8.0. 40607

  5. Open WindowsApplication1.log and verify that the file contains the messages Error Message and Info Message.

Additional Tasks

My.Application.Log is built atop a powerful and extensible framework for logging and tracing. The log's configuration is outlined in the app.config file included in your project. If you're interested in exploring some more functionality in this area, try the following tasks:

  1. Using the app.config file in your project as a guide, configure My.Application.Log to write to an XML file using the System.Diagnostics.XmlWriterTraceListener class.
  2. Modify the app.config file to write to the application Event Log using the System.Diagnostics.EventLogTraceListener class.
  3. Implement a custom listener (such as a listener that writes entries to a database) and tie it into My.Application.Log using the above configuration file. Verify that log messages are written to the listener.
  4. Add TraceOutputOptions for each listener—make the FileLogTraceListener print the process and thread IDs, for example.
  5. Implement a System.Diagnostics.TraceSwitch to tell My.Application.Log what types of messages should be filtered out.

Performing Network Tasks

My.Computer.Network allows users to perform common network-related tasks, such as uploading and downloading files, pinging remote hosts, querying network connectivity, and so on.

To Download a File

  1. Create a new Windows application.

  2. Add a button to the main form.

  3. In the button_clicked handler, add the following code, which uses My.Computer.Network.DownloadFile to download the file roadmap.aspx.

       My.Computer.Network.DownloadFile( _
         "https://msdn.microsoft.com/vstudio/productinfo/roadmap.aspx", _
        "c:\temp")

  4. Run the application. Press the button you added to the form.

  5. Close the application and verify that "roadmap.aspx" is saved in "C:\Temp".

Many client applications must perform differently, based on network connection status. For example, data-driven, rich client applications may store all data changes locally until the computer is connected to the network. The My event model raises an event whenever the network connection status changes.

To Make Your Application Network Aware

  1. Create a new Windows application.

  2. Open the MyEvents.vb file, available from the View Code button in the Application Designer.

  3. Add a handler for the NetworkAvailabilityChanged and insert the following code.

    If (e.IsNetworkAvailable) Then
       MsgBox( "Your computer is now connected to the network." )
    Else
       MsgBox( "Your computer is no longer connected to the network." )
    End If
    

  4. Run the application. Notice that a message box is displayed when your network availability changes. Experiment by connecting and disconnecting the network cable connected to your computer (it may take up to 20 seconds for the text to change).

Additional Tasks

  1. Change the example code so it supplies a username and password.
  2. My.Computer.Network.UploadFile and My.Computer.Network.DownloadFile also support FTP. Modify the above example to download a file from FTP.

Working with Files

My.Computer.FileSystem exposes solutions to tasks that involve: reading and writing files; copying, deleting, and moving files and directories; and obtaining information related to files, directories, and drives.

To Copy a File

  1. Create a new console application.

  2. Use My.Computer.FileSystem.CopyFile (sourceFile, destDirectory) to copy files from one location to another. This code copies the file test.txt from C:\Temp to C:\Logs.

    My.Computer.FileSystem.CopyFile("C:\Temp\test.txt", "C:\Logs")
    

  3. Run the application and verify that the file has been copied into the specified directory.

  4. Update the code to expose the copy file dialog seen when copying files with Explorer. This code copies the file, overwriting the file if it already exists, and exposing the Copy File dialog.

    My.Computer.FileSystem.CopyFile("C:\Temp\test.txt", "C:\Logs", True, True)
    

To Read All Text in a File

  1. Create a new Windows application.

  2. Add a textbox and a button to the form.

  3. In the button_clicked handler, use My.Computer.FileSystem.ReadAllText to populate the textbox. This code reads text from the file "info.txt".

    Textbox1.text = My.Computer.FileSystem.ReadAllText("C:\Temp\story.txt")
    

  4. Run the application and verify that the text appears in the textbox when you click the button.

To Get Volume Information

  1. Add a label to the application created in the previous procedure.
  2. In the form's load event, use My.Computer.FileSystem.Drives to get a DriveInfo object for the drive, and to set the text of the label equal to the TotalSize property. This code gets a DriveInfo object and uses it to populate the label.
    Dim test As System.IO.DriveInfo
    test = My.Computer.FileSystem.GetDriveInfo("C:")
    Label1.Text = test.TotalSize
    

Parsing Text Files

In addition to atomic and iterative IO, My.Computer.FileSystem also exposes an API designed to parse text files that are structured using fixed-width columns or delimiters. For this walkthrough, you'll need a sample text file with a format like the following.

   3/2/1985   ERR   An error occurred
   4/5/1995   INF   Here is some information

You can also substitute your own structured text file to parse, or export the contents of the Application Event Log as delimited text file.

To Parse a Text File

  1. Create a new Windows application.

  2. Add a DataGridView with a column for each column in the text file. In the above example, there are three columns.

  3. In the form load event, use the TextFieldParser, which can be accessed with My.Computer.FileSystem.OpenTextFieldParser(filename) to populate the table with the contents of the file. The following code does so with the new Using statement.

    Using myReader As _
    My.Computer.FileSystem.OpenTextFieldParser("c:\someFile.txt")
    MyReader.TextFieldType = FieldType.Delimited
    MyReader.Delimiters = New String(){vbTab}
    'Loop through all of the fields in the file.
    'If any lines are corrupt, report an error and 'continue parsing.
    While Not MyReader.EndOfData Try Me.DataGridView1.Rows.Add( MyReader.ReadFields() ) Catch ex As MalformedLineException MsgBox("Line " & ex.Message & _ " is invalid. Skipping") End Try End While End Using

  4. Run the application and verify that the information is appearing in grid.

Additional Tasks

  1. Use the GetFiles method to locate all files ending with .vb on your hard drive.
  2. Use the GetFileInfo, GetDirectoryInfo, and GetDriveInfo info to create the WindowsExplorer Properties window.
  3. Read lines in a text file iteratively using OpenTextFileReader.

Working with the Registry

My.Computer.Registry provides methods and properties that can be used to get and set values in registry keys. To use these properties, you must have Read and Write permission from the RegistryPermissionAccess Enumeration. Any code running with full trust (under the default security policy, this is any code installed on the user's local hard drive) has the necessary permissions to access the registry.

To Set a Registry Value

  1. Create a Windows application.

  2. Add code to set the value, specifying key and value, as in the following code.

    My.Computer.Registry.SetValue _
    ("HKEY_CURRENT_USER\MyTestKey", _
    "MyTestKeyValue","This is a test value.")
    

  3. Open the registry to verify that the specified value was set.

To Get a Registry Value

  1. Using the previous example, add code to read the value, specifying the path and the name. This code reads the value Name from the key HKEY_CURRENT_USER\Software\MyApp.
    readValue = My.Computer.Registry.GetValue _
    ("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
    

Getting Information About the Computer

How much virtual memory is available on this computer? What operating system is it running? My.Computer.Info provides answers to these questions. The properties exposed by the My.Computer.Info object return information about the computer where the application is deployed, as determined at run time.

To Determine a Computer's Total Physical Memory

  1. Create a Windows application.
  2. Add a label to the form.
  3. In the form's load event, use My.Computer.Info.AvailablePhysicalMemory property to supply the text for the label. This code assigns the AvailablePhysicalMemory property to Label1.
    Label1.text = My.Computer.Info.AvailablePhysicalMemory
    

To Determine a Computer's Amount of Available Memory

  1. Using the above example, add another label.
  2. Use the TotalPhysicalMemory property to supply the text for your second label. This code assigns the TotalPhysicalMemory property to Label2.
    Label1.text = My.Computer.Info.TotalPhysicalMemory
    

To Determine a Computer's Operating System Version and Name

  1. Using the above examples, add a third label.
  2. Use the OSFullName, OSPlatform, and OSVersion properties to supply the text for the label. This code displays the information in Label3.
    TextBox1.Text = My.Computer.Info.OSFullName & vbCrLf & _
    My.Computer.Info.OSPlatform & vbCrLf & My.Computer.Info.OSVersion
    

Using Resources

My.Resources is the programmatic link to resources added to a project via the Managed Resource Editor. All resources exposed through My.Resources are strongly-typed to the format specified in the Resource Editor.

To Add an Image to a Form

  1. Create a new Windows Application.

  2. Add a button to the form.

  3. Open the Resource Editor by double-clicking the My Project node in the Solution Explorer and selecting the Resources tab.

  4. Add an image as a resource. This will be used as the background image for the button.

  5. In the form's load event, add code to set the background image for the button to the new image. This code sets the background image of Button1 to the image buttonpicture.

    Button1.BackgroundImage = My.Resources.buttonpicture
    

  6. Run the application to verify that the button is displayed properly.

To Change the Culture for an Application

  1. Using the project from the previous example, add a .resx file for a culture other than the current one. Use the Resource Editor to add some text resources to the new .resx file.

  2. In the Application_Startup event handler, set the current culture to the culture of the .resx file you just added.

  3. In the form's load event, enter the following code.

    Form1.Text = My.Resource.SampleText
    

  4. Run the application to verify that the title of the form has SampleText in the correct culture.

Reading and Changing Application Settings

My.Settings is similar to My.Resources: it provides runtime access to strongly-typed settings added through the Settings Designer. The My.Settings object exposes each setting as a property; the property name is the same as the setting name, and the property type is the same as the setting type.

The setting's Scope determines if the property is read-only; the property for an Application-scope setting is read-only, while the property for a User-scope setting is read-write. You cannot change or save the values of application-scope settings at run time.

To Change an Application's Setting

  1. Create a new Windows application.

  2. Open the Settings editor by double-clicking the My Project node in the Solution Explorer and selecting the Settings tab.

  3. Add a setting to your project and make sure that its Scope is set to User.

  4. Add a button to the form.

  5. Add code to the button's Click event to change the setting when the button is clicked, and then call the My.Settings.Save method to persist the change. This code changes the value of the FullName setting.

    My.Settings.Fullname = newName
    

  6. Run the application and click the button.

  7. Verify that the setting has changed.

Handling Application Events

My includes a number of application events that can be handled to control the overall flow of your application. These events include:

  • Startup: fired when the applications starts and before the main form is shown.
  • Shutdown: fired when the application is shutting down.
  • UnhandledException: fired when an Exception is raised in your application and the Exception is not handled.
  • NetworkAvailabilityChanged: fired when the hosting computer is connected or disconnected from the network.
  • StartupNextInstance: if your application is a single instance application, this event will be fired when additional instances of the application are requested.

The application events can be handled in the MyEvents.vb file, available from the View Code button on the Application Designer.

To Handle Startup and Shutdown Events

  1. Create a new Windows application.

  2. Open the Application Designer, available by double-clicking the My Project node in the Solution Explorer.

  3. Click the View Code button in the Application Designer to open the MyEvents.vb file.

  4. Add a handler for the Startup event and insert the following code.

    MsgBox( "The application is starting" )
    

  5. Add a handler for the Shutdown event and insert the following code.

    MsgBox( "The application is shutting down" )
    

  6. Run the application.

Additional Tasks

  1. Add a handler for the UnhandledException event that writes a log message whenever an unhandled Exception is raised.

    Note   this handler will not be called when your application is run inside Visual Studio.

  2. Make the above application a single instance application and handle the StartupNextInstance event.

Getting Information About the User

My.User represents the currently logged-on user for the application. By default, My.User returns information related to the current Windows user.

To Access the Current Logged-on Windows User

  1. Create a new Windows application.
  2. In the form_load event handler, add a personalized welcome message to the form as follows.
    Me.Text = "Hello, " & My.User.Identity.Name

My.User harnesses the extensibility characteristics of the System.Security.Principal infrastructure, which allows developers to implement custom authentication and authorization mechanism. For example, if an application relies on a SQL database or legacy back-end to store user information and roles, the IPrincipal and IIDentity interfaces can be implemented to communicate with those stores. My.User allows developer-defined IPrincipal and IIdentity implementations to replace the default WindowsPrincipal and WindowsIdentity.

For more information on how to implement a custom IPrincipal and IIDentity, and role-based security, see Role Based Security

To Add Custom Authentication and Authorization to an Application

  1. Create a new Windows application.
  2. Double click the My Project node in the Solution Explorer. The Project Designer opens. Deselect Set My.User to Logged On Windows User.
  3. In the Form_Load event, set the current user with your own custom IPrincipal using the following code method.
    Dim customPrincipal As New <InsertCustomPrincipal>
    My.User = customPrincipal
    

Conclusion

My provides rapid access to a wealth of .NET Framework functionality, exposing it in a simple and intuitive, yet powerful, way. For more information on tasks involving My and its related objects, please see the product documentation.

© Microsoft Corporation. All rights reserved.