Using the Registry and Event Log


Want to store your settings in the registry? Or are you looking for a ready-to-run function for writing to the Event log? Then sit back and begin reading: this is the section for you!

How to Read and Write the Registry

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Registry folder.

The registry is a great place to store your application settings. It s used by almost every Windows application, and you can view its entire contents by selecting Start Run and launching regedit.exe.

To manipulate the registry in your code, you need to use objects inside the Microsoft.Win32 namespace. To simplify this process, the following functions encapsulate all the required code for you, allowing you to read from or write to the registry in just a line of code.

The first function is called ReadFromRegistry . It accepts a location and name of the key to retrieve, returning a string value:

 Public Function ReadFromRegistry(ByVal Location As String, _     ByVal Name As String) As String      ' Returns a value from the registry      Dim MyKey As Microsoft.Win32.RegistryKey      MyKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Location)      ReadFromRegistry = CType(MyKey.GetValue(Name), String)      MyKey.Close()  End Function 

The second block of code is a method called WriteToRegistry . It accepts a location, key name, and the actual string to store with the key:

 Public Sub WriteToRegistry(ByVal Location As String, _      ByVal Name As String, ByVal Data As String)      ' Writes a value to the registry      Dim MyKey As Microsoft.Win32.RegistryKey      MyKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(Location)      MyKey.SetValue(Name, Data)      MyKey.Close()  End Sub 

You could use the preceding functions as follows :

 WriteToRegistry("Software\White Cliff\MyApp", "Username", "John")  MessageBox.Show(ReadFromRegistry("Software\White Cliff\MyApp", _     "Username")) 

Note that my sample functions save and retrieve data specific to the current user in the CurrentUser (HKEY_CURRENT_USER) portion of the registry. If you wish to store global data, accessible by whomever is logged in, simply change this to use the LocalMachine class.

You can also store other types of data in the registry. For more information, look up Registry class, about Registry class in the help index, or check out the Microsoft MSDN feature at http://msdn.microsoft.com/library/en-us/dv_vstechart/html/vbtchaccessingregistrywithvisualbasicnet.asp.

Putting Messages in the Event Log

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”Event Log folder.

The event log is a haven for system administrators. All the great programs use it to record details of how everything went: the batch update completed successfully, the midnight virus update failed, peak usage on Monday occurred at 13:37 P.M.

Now, you too can plug into and place your entry in the log. Here s my own little function to show you how:

 Public Function WriteToEventLog(ByVal Entry As String, _     Optional ByVal AppName As String = "VB.NET Application", _     Optional ByVal EventType As _     EventLogEntryType = EventLogEntryType.Information, _     Optional ByVal LogName As String = "Application") As Boolean      ' Writes an entry to the Event Log      Dim objEventLog As New EventLog()      Try          ' Register app as an Event Source          If Not objEventLog.SourceExists(AppName) Then              objEventLog.CreateEventSource(AppName, LogName)          End If          objEventLog.Source = AppName          ' Send entry          objEventLog.WriteEntry(Entry, EventType)          Return True      Catch Ex As Exception          Return False      End Try  End Function 

To use, simply call the WriteToEventLog function, passing in an empty string. You can also optionally specify the application name, event type, and the log to use (that is, Application ). If you specify a nonexistent log, one will be created for you. The function returns a Boolean dependent on its success.

To finish us off, here are examples of WriteToEventLog in use (see Figure 7-13 to see what this does in the event log):

click to expand
Figure 7-13: Our complex event log sample shown in the Event Viewer
 ' Simple event log addition  WriteToEventLog("Application has failed to find STARTUP.INI")  ' Slightly more complex sample  WriteToEventLog("Unable to parse request LOGON", _      "Authenticator", EventLogEntryType.Error, "Special Log") 
TOP TIP  

If you take time to explore the EventLog class, you ll find many interesting properties to take your work with the event log even further. Most importantly, you ll find .Clear and .Delete methods at your disposal, allowing you to perform actions even the Event Viewer doesn t support.




The Ultimate VB .NET and ASP.NET Code Book
The Ultimate VB .NET and ASP.NET Code Book
ISBN: 1590591062
EAN: 2147483647
Year: 2003
Pages: 76
Authors: Karl Moore

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net