Santry Technology Solutions, Content Management, DotNetNuke, SharePoint Consulting
Register | Login
Friday, July 03, 2009

Sections
  
About Us
  
Partners
Downloads
  
 WWWCoder.com Resource Directory

Working with the System Registry
1/15/2004 7:24:50 PM

In this article we will cover working with the system registry, both reading and writing values. In this example, we will cover creating a license registration for your application.

In some application scenarios there may be instances where you need to obtain or modify information in the Windows registry. For example, say you have a service or another application that your Web application needs to interact with. You may need to obtain system information for your server, or write some information as part of your application distribution. In this article we will show how easy it is to modify the registry within an ASP.Net application.

In this specific example, we're going to write and read values in the registry for a registration system for our Web application. For example, you can create a Web form that accepts a license key, this key then gets submitted via a Web service to your license server, upon success the appropriate value or key is then entered into the registry allowing the Web application to run fully licensed and enabled.

Take note, you should always create a backup of your registry whenever modifying it.

Let's introduce you to the Microsoft.Win32 namespace, this namespace provides access to events generated by the system, and the ability to manipulate the system registry. In this tutorial we're working the registry aspects of the namespace.

First we'll import our namespace and create our class:

Imports Microsoft.Win32
Public Class Register
#Region "Declarations"
    Private thisRegKeyLength As Integer = 8
    Private thisRegNumber As String
    Private thisDaysLeft As Integer
#End Region

Reading Values

In this first method we are going to read a value that was written to the registry when the application first ran. The initial run date was entered. We will read this value to determine if the application has been ran.

#Region "Methods"
    Private Function GetDaysUsed() As Integer
        Try
            Dim runDate As Date
            runDate = CType(GetRegValue(RegistryHive.LocalMachine, _
               "SOFTWARE\MyCompany\MySoftware\", "InitDate"), Date)
            Return DateDiff(DateInterval.Day, runDate, Now)
        Catch ex As Exception
            Return 0
        End Try
    End Function
This function could be accomplished a number of ways. You could hard code your registration key within the code and then compile, or create a Web service that takes the name in, checks it against the Web service and returns a valid key. Once a valid key is returned it can then be written to the registry for future checking instead of calling the Web service.
    Public Sub GenerateRegistrationKey(ByVal inName As String)
        'call your web service or some other function to obtain key.
    End Sub
The following method is going to check the current key against the licensee name to see if it is correct. If not, you can then do a double check against your Web service to confirm whether or not the user is valid or prompt for a correct key.

Public Function CheckForValidRegistrationKey(ByVal inRegCode As String, _ ByVal inName As String) As Boolean
        GenerateRegistrationKey(inName)         Dim temp As String         Dim length As Integer
        Dim regCode As String = thisRegNumber         length = thisRegKeyLength         temp = Left$(regCode, length)         If inRegCode = temp Then             Return True         Else             Return False         End If     End Function
This next function will check the registry to see if a flag is set called "IsRun" within the registry, if it doesn't find the value it will write to the value to the registry using the WriteToRegistry method. This method is called twice once to set the flag, and another to set the initialization date for the application.
    Public Function CheckIfRunBefore() As Boolean
        'first check to see if there is an install date. if not create one.
        If RegValue(RegistryHive.LocalMachine, "SOFTWARE\MyCompany\MySoftware\", "IsRun") = "" Then
            WriteToRegistry(RegistryHive.LocalMachine, "SOFTWARE\MyCompany\MySoftware\", "IsRun", "Y")
            WriteToRegistry(RegistryHive.LocalMachine, "SOFTWARE\MyCompany\MySoftware\", _
                     "InitDate", CType(Date.Today, String))
            Return False
        Else
            Return True         End If
    End Function
This next method is what allows our application to read values from the registry on the Web server.

Public Function GetRegValue(ByVal thisHive As RegistryHive, _ ByVal thisKey As String, ByVal thisValueName As String) As String
        Dim objParent As RegistryKey
        Dim objSubkey As RegistryKey
        Dim sAns As String
        Select Case thisHive
            Case RegistryHive.ClassesRoot                 objParent = Registry.ClassesRoot             Case RegistryHive.CurrentConfig                 objParent = Registry.CurrentConfig             Case RegistryHive.CurrentUser                 objParent = Registry.CurrentUser             Case RegistryHive.DynData                 objParent = Registry.DynData
            Case RegistryHive.LocalMachine                 objParent = Registry.LocalMachine
            Case RegistryHive.PerformanceData                 objParent = Registry.PerformanceData             Case RegistryHive.Users                 objParent = Registry.Users
        End Select
        Try
            objSubkey = objParent.OpenSubKey(thisKey)             'Check to see if the object is in the registry.             If Not objSubkey Is Nothing Then                 sAns = (objSubkey.GetValue(thisValueName))             End If         Catch ex As Exception                   
        End Try
        Return sAns
    End Function

Writing Values

This method is going to write to the registry, previously we entered in some values such as the registration information, flag when the program was first ran, and a date for the application startup.

Public Function WriteToRegistry(ByVal thisParentKeyHive As RegistryHive, _
  ByVal thisSubKeyName As String, ByVal thisValueName As String, ByVal thisValue As Object) As Boolean
        Dim objSubKey As RegistryKey         Dim sException As String         Dim objParentKey As RegistryKey         Dim bAns As Boolean         Try             Select Case thisParentKeyHive                 Case RegistryHive.ClassesRoot                     objParentKey = Registry.ClassesRoot                 Case RegistryHive.CurrentConfig                     objParentKey = Registry.CurrentConfig                 Case RegistryHive.CurrentUser                     objParentKey = Registry.CurrentUser                 Case RegistryHive.DynData                     objParentKey = Registry.DynData
                Case RegistryHive.LocalMachine                     objParentKey = Registry.LocalMachine                 Case RegistryHive.PerformanceData                     objParentKey = Registry.PerformanceData                 Case RegistryHive.Users
                    objParentKey = Registry.Users             End Select             'Open the registry key.             objSubKey = objParentKey.OpenSubKey(thisSubKeyName, True)
            'We'll create it.
            If objSubKey Is Nothing Then                 objSubKey = objParentKey.CreateSubKey(thisSubKeyName)
            End If             objSubKey.SetValue(ValueName, thisValue)
            bAns = True         Catch ex As Exception             bAns = False
        End Try
        Return True
    End Function    #End Region
End Class

 

This code is only provided as an example of how to write to the registry using VB.Net. Keep in mind other issues may arise where a registration system for your application will not work. The process will need to have permissions to access the registry in order to read and write to it. In addition, if your application is load balanced then each machine will have most likely end up with different values in the registry.

There are plenty of other options for storing data that are preferred over this method like in a database, or inside the web.config, but if you need to read existing values or even hide values using the registry may be an option.


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 1/23/2008 3:13:25 AM by Anonymous
Comments: how can i access remote registry?
No ratings available.
Left on 4/11/2007 5:45:02 AM by Anonymous
Comments: very gud
Left on 3/21/2007 3:24:15 PM by Anonymous
Comments: The article would be more useful if it gave some hint about the permissions that must be set on the Registry key that you intend to update.
Left on 3/1/2007 10:03:24 PM by Anonymous
Comments:
No ratings available.
Left on 3/28/2006 8:42:12 AM by Anonymous
Comments: not clear at all
Left on 2/6/2004 3:46:40 PM by Anonymous
Comments: One major point here. Storing values within the registry is THE MOST SECURE method of securing data. You can store encypted data in the registry for items such as database connection information, account information, then lock that data down via ACLs. This prevents file browsing code on the Web server from ever seeing the data. Don't discount this article as something you'll never use, rather it is something you should seriously investigate for securing your applications. Kudos to the author.
Left on 2/1/2004 4:28:48 AM by Anonymous
Comments: Comments from the following blog: Ashutosh Nilkanth's .NET Blog, located at: http://weblogs.asp.net/ashben/archive/0001/01/01/62698.aspx
No ratings available.
Left on 1/25/2004 10:04:49 PM by Anonymous
Comments: any info on encrypting key value ?
Left on 1/25/2004 11:52:05 AM by Anonymous
Comments: I thin if you read the article the author mentions the fact that this method is not to be used, but yes there are cases where you need to access the registry. We wrote a Web application that integrates with an application that did not provide a web-based management piece. In effect we created our own web management interface by being able to modify registry values via an ASP.Net page.
No ratings available.
Left on 1/25/2004 10:19:53 AM by Anonymous
Comments: And this has to do with ASP.NET because...?

ASP.NET applications, by default, are restricted from using resources such as the system registry. That is why, in most cases, XML files are used to store application settings.

Sure this is demonstrated with ASP.NET but it does not show a best practice at all... nevermind, that on the live sites, the ASP.NET user does not have these rights.
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970