Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 110 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
110
Dung lượng
5,47 MB
Nội dung
Figure 9-8 My The My keyword is a novel concept 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 that you need access to. Using the My keyword, you can quickly get access to a wide variety of items such as user details or specific settings of the requestor’s browser. Though not really considered a true namespace, the My object declarations that you make work the same as the .NET namespace structure you are used to working with. To give you an example, let’s first look at how you get at 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. Now let’s look at how you would accomplish this same task using the new My keyword: My.Computer.Info.MachineName.ToString() As you are looking at this example, you might be wondering what the point is if the example, which is using My, is lengthier than the first example that just works off of the Environment namespace. Just remember that it really isn’t about the length of what you type to get access to specific classes, but instead is about a logical way to find often accessed resources without the need to spend too much time hunting them down. 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 previously without a performance hit. Global System Web Wrox Text Integer String Book Text String System 298 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 298 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If you type the My keyword in your Windows Forms application, you will notice that IntelliSense provides you with six items to work with— Application, Computer, Forms, Resources, User, and WebServices. Though this new 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 for a Web application, then you will have three items off of the My keyword— Application, Computer, and User. Each of these is broken down 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. The following table details the properties and methods of the My.Application namespace. Property/Method Description ApplicationContext Returns the contextual information about the thread of the Windows Forms application. AssemblyInfo Provides quick access to the assembly of the Windows Forms. You can get at assembly information such as version number, name, title, copyright information, and more. ChangeCurrentCulture A method that allows you to change the culture of the current application thread. ChangeCurrentUICulture A method that allows you to change the culture that is being used by the Resource Manager. CurrentCulture Returns the current culture which is being used by the current thread. CurrentDirectory Returns the current directory for the application. CurrentUICulture Returns the current culture that is being used by the Resource Manager. Deployment Returns an instance of the ApplicationDeployment object, which allows for programmatic access to the application’s ClickOnce features. IsNetworkDeployed Returns a Boolean value which 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 This property allows you to write to your application’s event log listeners. MainForm Allows access to properties of the main form (initial form) for the application. Table continued on following page 299 Namespaces 12_575368 ch09.qxd 10/7/05 11:05 PM Page 299 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Property/Method Description OpenForms Returns a FormCollection object, which allows access to the properties of the forms which are currently open. SplashScreen Allows you to programmatically assign the splash screen for the application. While there is much that can be accomplished using the My.Application namespace, for an example of its use, let’s focus on the use of the AssemblyInfo property. This property provides access to the information that is 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: MessageBox.Show(“Company Name: “ & My.Application.AssemblyInfo.CompanyName & _ vbCrLf & _ “Description: “ & My.Application.AssemblyInfo.Description & vbCrLf & _ “Directory Path: “ & My.Application.AssemblyInfo.DirectoryPath & vbCrLf & _ “Copyright: “ & My.Application.AssemblyInfo.LegalCopyright & vbCrLf & _ “Trademark: “ & My.Application.AssemblyInfo.LegalTrademark & vbCrLf & _ “Name: “ & My.Application.AssemblyInfo.Name & vbCrLf & _ “Product Name: “ & My.Application.AssemblyInfo.ProductName & vbCrLf & _ “Title: “ & My.Application.AssemblyInfo.Title & vbCrLf & _ “Version: “ & My.Application.AssemblyInfo.Version.ToString()) From this example, you can see that we can get at quite a bit of information concerning the assembly of the application that is running. Running this code will produce a message box similar to the one shown in Figure 9-9. Figure 9-9 300 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 300 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Another interesting property to look at from the My.Application namespace is the Log property. This property allows 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: <?xml version=”1.0” encoding=”utf-8” ?> <configuration> <system.diagnostics> <sources> <source name=”Microsoft.VisualBasic.MyServices.Log.WindowsFormsSource” 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=”EvjenEventWriter”/> </sharedListeners> </system.diagnostics> </configuration> Once the configuration file is in place, you can then record entries to the Application Event Log as illustrated here in the following simple example: Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load My.Application.Log.WriteEntry(“Entered Form1_Load”, _ TraceEventType.Information, 1) End Sub 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 9-10. The previous example showed 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. It is important to 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 Administrator accounts. 301 Namespaces 12_575368 ch09.qxd 10/7/05 11:05 PM Page 301 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 9-10 In addition to writing to the Application Event Log, you can also just as easily write to a text file. Just as with writing to the Application Event Log, writing to a text file also means that you are going to need to make changes to the app.config file. <?xml version=”1.0” encoding=”utf-8” ?> <configuration> <system.diagnostics> <sources> <source name=”Microsoft.VisualBasic.MyServices.Log.WindowsFormsSource” 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=”EvjenEventWriter”/> <add name=”FileLog” type=”System.Diagnostics.FileLogTraceListener, Microsoft.VisualBasic, 302 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 302 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Version=8.0.1200.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” 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. Though this time, in addition to writing the Application Event Log, the information will also be written to a new text file. You will find the text file at C:\Documents and Settings\[ username ]\ Application Data\[ AssemblyCompany ]\[ AssemblyProduct ]\[ Version ] . For instance, in my example, the log file was found at C:\Documents and Settings\Administrator\Application Data\ Wrox\Log Writer\1.2.0.0\ . In the .log file found, you will see a line such as: Microsoft.VisualBasic.MyServices.Log.WindowsFormsSource Information 1 Entered Form1_Load Though split here on two lines (due to the width of the paper for this book), you will find this informa- tion in a single line within the .log file. By default it is separated by tabs, but you can also change the delimiter yourself by adding a delimiter attribute to the FileLog section in the app.config file. This is: <add name=”FileLog” type=”System.Diagnostics.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.1200.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” 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. The following table details the objects contained in this namespace. Property Description Audio This object allows you to work with audio files from your application. This includes starting, stopping, and looping audio files. Clipboard This object allows you to read and write to the clipboard. Clock This allows for access to the system clock to get at GMT and the local time of the computer that is running the application. You can also get at the tick count, which is the number of milliseconds that has elapsed since the computer was started. Table continued on following page 303 Namespaces 12_575368 ch09.qxd 10/7/05 11:05 PM Page 303 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Property Description FileSystem This object provides a large collection of properties and methods that allow for 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 access to knowledge of which keyboard keys are pressed by the end user. Also included is a single method, SendKeys, which allows you to send the pressed keys to the active form. Mouse This provides a handful of properties that allow for detection of the type of mouse installed, and provides such details as whether the left and right mouse buttons have been swapped, whether a mouse wheel exists, and details on 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 to enable you to interact with the network to which the computer where the application is running is connected. With this object, you can use the IsAvailable property to first check that the computer is connected to a network. If this is positive, the Network object allows you to upload or download files, and ping the network. Ports This object can provide notify one if there are available ports as well as allowing for access to the ports. Printers This object allows determination of which printers are available to the application as well as provides the ability to define default printers and print items to any of the printers available. Registry This object provides programmatic access to the registry and the registry settings. Using the Registry object, you can determine if keys exist, determine values, change values, and delete keys. Screen Provides the ability to work with one or more screens which may be attached to the computer. 304 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 304 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com There is a lot to the My.Computer namespace, so it is impossible to touch upon most of it. For an example of using this namespace, let’s take a look at the FileSystem property. The FileSystem property allows for you to easily and logically access drives, directories, and files on the computer. To illustrate the use of this property, first start off by creating a Windows Form with a DataGridView and a Button control. It should appear as shown in Figure 9-11. Figure 9-11 This little application will look in the user’s My Music folder and list all of the .wma files found therein. Once listed, the user of the application will be able to select one of the listed files, and after pressing the Play button, the file will be launched and played inside Microsoft’s Windows Media Player. The first step after getting the controls on the form in place is to make a reference to the Windows Media Player DLL. You will find this on the COM tab, and the location of the DLL is C:\WINDOWS\System32\ wmp.dll . This will give you an object called WMPLib in the References folder of your solution. You might be wondering why you would make a reference to a COM object in order to play a .wma file from your application instead of using the My.Computer.Audio namespace that is provided to you. The Audio property only allows for the playing of .wav files, because to play .wma, .mp3, and similar files, the user must have the proper codecs on his or her machine. These codecs are not part of the Windows OS, but are part of Windows Media Player. 305 Namespaces 12_575368 ch09.qxd 10/7/05 11:05 PM Page 305 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Now that the reference to the wmp.dll is in place, let’s put some code in the Form1_Load event. Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load For Each MusicFile As String _ In My.Computer.FileSystem.GetFiles _ (My.Computer.FileSystem.SpecialDirectories.MyMusic, True, “*.wma”) Dim MusicFileInfo As System.IO.FileInfo = _ My.Computer.FileSystem.GetFileInfo(MusicFile.ToString()) Me.DataGridView1.Rows.Add(MusicFileInfo.Directory.Parent.Name & _ “\” & MusicFileInfo.Directory.Name & “\” & MusicFileInfo.Name) Next End Sub In this example, the My.Computer.FileSystem.GetFiles method points to the My Music folder through the use of the SpecialDirectories property. This property allows for logical and easy access to folders such as Desktop, My Documents, My Pictures, Programs, and more. Though it is possible to use just this first parameter with the GetFiles method, this example makes further definitions. The second parameter defines the recurse value — which states whether the subfolders should be perused as well. By default, this is set to False, but it has been changed to True for this example. The last parameter defines the wildcard that should be used in searching for elements. In this case, the value of the wildcard is *.wma, which instructs the GetFile method to get only the files that are of type .wma. Once retrieved with the GetFile method, the retrieved file is then placed inside the DataGridView control, again using the My.Computer.FileSystem namespace to define the value of the item placed within the row. Once the Form1_Load event is in place, the last event to construct is the Button1_Click event. This is illustrated here: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim MediaPlayer As New WMPLib.WindowsMediaPlayer MediaPlayer.openPlayer(My.Computer.FileSystem.SpecialDirectories.MyMusic & _ “\” & DataGridView1.SelectedCells.Item(0).Value) End Sub From this example, you can see that it is pretty simple to play one of the provided .wma files. It is as simple as creating an instance of the WMPLib.WindowsMediaPlayer object and using the openPlayer method, which takes as a parameter the location of the file to play. In this case, you are again using the SpecialDirectories property. The nice thing about using this property is that it could be more difficult to find the user’s My Music folder due to the username changing the actual location of the files that the application is looking for, but using the My namespace allows it to figure out the exact location of the items. When built and run, the application provides a list of available music files and allows you to easily select one for playing in the Media Player. This is illustrated in Figure 9-12. 306 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 306 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 9-12 Though it would have been really cool if it were possible to play these types of files using the Audio property from the My.Computer namespace, it is still possible to use the My.Computer.Audio name- space for playing .wav files and system sounds. To play a system sound, you use the following construct: My.Computer.Audio.PlaySystemSound(SystemSounds.Beep) The system sounds in the SystemSounds enumeration include: Asterisk, Beep, Exclamation, Hand, and Question. My.Forms The My.Forms namespace is just a quick and logical way of getting at the properties and methods of the forms that are contained within your solution. For instance, to get at the first form in your solution (assuming that it’s named Form1), you use the following namespace construct: My.Form.Form1 To get at other forms, you simply change the namespace so that the name of the form that you are trying to access follows the Form keyword in the namespace construction. 307 Namespaces 12_575368 ch09.qxd 10/7/05 11:05 PM Page 307 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... a DataException instance Having many types of exceptions in VB. NET enables different types of conditions to be trapped with different exception handlers This is a major advance over VB6 The syntax to do that is discussed next Structured-Exception-Handling Keywords in VB. NET Structured exception handling depends on several new keywords in VB. NET They are: ❑ Try — Begin a section of code in which an... shown in Figure 1 0 -4 Figure 1 0 -4 As mentioned earlier, the TargetSite property gives you the name of the method that threw your exception This information comes in handy when troubleshooting and could be integrated into the error message so that the end user could report the method name back to you Figure 1 0-5 shows a message box displaying the TargetSite from the previous example Figure 1 0-5 325 Chapter... Handling in VB6 For compatibility, Visual Basic NET still supports the old-style syntax for error handling that was used in Visual Basic 6 and earlier versions That means you can still use the syntax presented in this review However, it is strongly recommended that you avoid using this old-style syntax in favor of the exception handling features that are native to NET The old-style syntax in VB6 was handed... Exception 3 24 Exception Handling and Debugging Then you display three message boxes: Messagebox.Show(objB.Message) Messagebox.Show(objB.InnerException.Message) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Messagebox.Show(objB.TargetSite.Name) The message box that is produced by your custom error, which is held in the objB variable, is shown in Figure 1 0-3 Figure 1 0-3 The InnerException... before for a team of developers to work on different parts of the same project 309 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Exception Handling and Debugging All professional- grade programs need to handle unexpected conditions In programming languages before Microsoft NET, this was often called error... http://www.simpopdf.com relevant information about the error However, where there is only one global Err object in VB6 , there are many types of exception objects in VB. NET For example, if a divide by zero is done in code, then an OverflowException is generated There are several dozen types of exception classes in VB. NET, and in addition to using the ones that are available in the NET Framework, you can inherit from... exception handling works in Visual Basic NET (VB. NET) There are many improvements over pre-.NET versions of Visual Basic This chapter will discuss the common language runtime (CLR) exception handler in detail and the programming methods that are most efficient in catching errors Specifically, it will discuss: ❑ A brief review of error handling in Visual Basic 6 (VB6 ) ❑ The general principles behind exception... matches that type of exception will receive control Merge and Split Unregistered Version - http://www.simpopdf.com A Catch statement is analogous to the line label used in a VB6 On Error statement, but the ability to route different types of exceptions to different Catch statements is a radical improvement over VB6 ❑ Finally — Contains code that runs when the Try block finishes normally, or if a Catch... a Finally in VB6 ❑ Throw — Generate an exception This is similar to Err.Raise in VB6 It’s usually done in a Catch block when the exception should be kicked back to a calling routine or in a routine that has itself detected an error such as a bad argument passed in The Try, Catch, and Finally Keywords Here is an example showing some typical simple structured exception handling code in VB. NET In this... follow the sequence better if you place a breakpoint at the top of the GetAverage function and step through the lines Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Here is a more complex example that traps the divide-by-zero exception explicitly This second version of the GetAverage function (notice that the name is GetAverage2) also includes a Finally block: Private Function . exceptions. 3 14 Chapter 10 13_575368 ch10.qxd 10/7/05 11:02 PM Page 3 14 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com How Exceptions Differ from the Err Object in VB6 Because. in VB. NET enables different types of conditions to be trapped with different exception handlers. This is a major advance over VB6 . The syntax to do that is discussed next. Structured-Exception-Handling. similar to the one shown in Figure 9-9 . Figure 9-9 300 Chapter 9 12_575368 ch09.qxd 10/7/05 11:05 PM Page 300 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Another interesting