Create New RegistryKey

G

Guest

Thank you in advance for any and all assistance. Here is my problem. I have a
program that will create a registry key, however it is not and here is the
code and also the error that follows:

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports Microsoft.VisualBasic.Conversion
Imports System.Management
Imports Microsoft.Win32

Public Class License

Private szRegKey As String
Private szKeyValueName As String
Private szDateValueName As String

Public Property KeyValueName() As String
Get
Return szKeyValueName
End Get
Set(ByVal value As String)
szKeyValueName = value
End Set
End Property

Public Property DateValueName() As String
Get
Return szDateValueName
End Get
Set(ByVal value As String)
szDateValueName = value
End Set
End Property

Public Property RegKey() As String
Get
Return szRegKey
End Get
Set(ByVal value As String)
szRegKey = value
End Set
End Property

Public Function CheckValidity(ByVal szRegMainKey As String, ByVal
szKeyBaseString As String, ByVal nHours As Integer) As Boolean
Dim keyArray() As String
Dim rKey As RegistryKey = Nothing
Dim uB As Long
Dim szMasterKey As String
Dim i As Long
Dim szKeyEnc As String
Dim szKey As String
Dim szDate As String
Dim szDateEnc As String
Dim szDateD As Date

If szRegKey = "" Then Return False
If szKeyValueName = "" Then Return False
If szDateValueName = "" Then Return False

keyArray = szRegKey.Split("\")
uB = UBound(keyArray)
szMasterKey = ""
For i = 1 To uB
szMasterKey = szMasterKey & keyArray(i) & "\"
Next
szMasterKey = szMasterKey.Substring(0, szMasterKey.Length - 1)

Try
Select Case keyArray(0)
Case "HKEY_CLASSES_ROOT"
rKey = Registry.ClassesRoot.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_USER"
rKey = Registry.CurrentUser.OpenSubKey(szMasterKey, True)
Case "HKEY_LOCAL_MACHINE"
rKey = Registry.LocalMachine.OpenSubKey(szMasterKey, True)
Case "HKEY_USERS"
rKey = Registry.Users.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_CONFIG"
rKey = Registry.CurrentConfig.OpenSubKey(szMasterKey,
True)
End Select
Catch ex As Exception
Return False
End Try
szKeyEnc = rKey.GetValue(szKeyValueName).ToString()
szDateEnc = rKey.GetValue(szDateValueName).ToString()
rKey.Close()
If szKeyEnc = "" Then Return False
If szDateEnc = "" Then Return False

szKey = DecryptKey(szKeyEnc)
If szKey <> szKeyBaseString Then
Return False
End If

szDate = DecryptKey(szDateEnc)
If IsDate(szDate) = False Then Return False

szDateD = Convert.ToDateTime(szDate)
If DateDiff(DateInterval.Hour, szDateD, Now()) >= nHours Then
Return False
End If

Return True

End Function

Public Function SaveKeyToRegistry(ByVal szKeyValue As String) As Boolean

Dim keyArray() As String
Dim rKey As RegistryKey = Nothing
Dim uB As Long
Dim szMasterKey As String
Dim i As Long
Dim szDate As String
Dim szDateEnc As String

If szRegKey = "" Then Return False
If szKeyValueName = "" Then Return False
If szDateValueName = "" Then Return False

keyArray = szRegKey.Split("\")
uB = UBound(keyArray)
szMasterKey = ""
For i = 1 To uB
szMasterKey = szMasterKey & keyArray(i) & "\"
Next
szMasterKey = szMasterKey.Substring(0, szMasterKey.Length - 1)

Try
Select Case keyArray(0)
Case "HKEY_CLASSES_ROOT"
rKey = Registry.ClassesRoot.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_USER"
rKey = Registry.CurrentUser.OpenSubKey(szMasterKey, True)
Case "HKEY_LOCAL_MACHINE"
rKey = Registry.LocalMachine.OpenSubKey(szMasterKey, True)
Case "HKEY_USERS"
rKey = Registry.Users.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_CONFIG"
rKey = Registry.CurrentConfig.OpenSubKey(szMasterKey,
True)
End Select
Catch ex As Exception
Return False
End Try
szDate = Day(Now) & "/" & Month(Now) & "/" & Year(Now) & " " &
Hour(Now) & ":" & Minute(Now)
szDateEnc = GenerateKey(szDate)
Try
rKey.SetValue(szDateValueName, szDateEnc)
rKey.SetValue(szKeyValueName, szKeyValue)
rKey.Close()
Catch ex As Exception
rKey.Close()
Return False
End Try
Return True

End Function

Public Function GenerateKey(Optional ByVal szBaseString As String = "")
As String
Dim szOutput As String
Dim sHex As String
Dim sLen As Integer
Dim i As Integer
Dim nRet As String = ""

If szBaseString = "" Then szBaseString = GetBiosID()
szOutput = des.Encrypt(szBaseString)
sLen = szOutput.Length
For i = 0 To sLen - 1
sHex = Convert.ToString(Hex(Asc(szOutput.Substring(i, 1))))
If sHex.Length < 2 Then sHex = "0" & sHex
nRet = nRet & sHex
Next
If nRet.EndsWith("3D3D") Then nRet = nRet.Substring(0, nRet.Length -
4)
Return nRet
End Function

Public Function DecryptKey(ByVal szBaseString As String) As String

Dim nRet As String = ""
Dim sChar As String
Dim sLen As Integer
Dim i As Integer

sLen = szBaseString.Length
For i = 0 To sLen - 1 Step 2
sChar = Chr("&H" & szBaseString.Substring(i, 2))
nRet = nRet & sChar
Next
Return des.Decrypt(nRet)

End Function

Public Function GetBiosID() As String
Dim searcher As Object = New ManagementObjectSearcher("SELECT * FROM
Win32_BIOS")
Dim info As ManagementObject
Dim nRet As String = ""

For Each info In searcher.Get()
nRet += info("manufacturer").ToString() &
info("serialnumber").ToString()
Next
Return nRet

End Function

When I run this code in an application I get this:

System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="LicenseLib"
StackTrace:
at LicenseLib.License.SaveKeyToRegistry(String szKeyValue)
at Sample_Ins.frmMain.InstallRegisterNewKey(String szClientName,
Boolean isMachineLinked, Int64 nHours) in
E:\LicenseCode\Sample_Ins\Sample_Ins\frmMain.vb:line 95
at Sample_Ins.frmMain.btnSample_Click(Object sender, EventArgs e) in
E:\LicenseCode\Sample_Ins\Sample_Ins\frmMain.vb:line 50
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context)
at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,
ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at Sample_Ins.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

When I attempt to debug, I never even get a registry value created. HELP
PLEASE!
 
C

Cor Ligthert [MVP]

Hi,

Is it instead of showing us a complete program not better to show the part
where the creation of the registry key fails?

I think that you give us now to much data to let it be information.

Cor

eSolTec said:
Thank you in advance for any and all assistance. Here is my problem. I
have a
program that will create a registry key, however it is not and here is the
code and also the error that follows:

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports Microsoft.VisualBasic.Conversion
Imports System.Management
Imports Microsoft.Win32

Public Class License

Private szRegKey As String
Private szKeyValueName As String
Private szDateValueName As String

Public Property KeyValueName() As String
Get
Return szKeyValueName
End Get
Set(ByVal value As String)
szKeyValueName = value
End Set
End Property

Public Property DateValueName() As String
Get
Return szDateValueName
End Get
Set(ByVal value As String)
szDateValueName = value
End Set
End Property

Public Property RegKey() As String
Get
Return szRegKey
End Get
Set(ByVal value As String)
szRegKey = value
End Set
End Property

Public Function CheckValidity(ByVal szRegMainKey As String, ByVal
szKeyBaseString As String, ByVal nHours As Integer) As Boolean
Dim keyArray() As String
Dim rKey As RegistryKey = Nothing
Dim uB As Long
Dim szMasterKey As String
Dim i As Long
Dim szKeyEnc As String
Dim szKey As String
Dim szDate As String
Dim szDateEnc As String
Dim szDateD As Date

If szRegKey = "" Then Return False
If szKeyValueName = "" Then Return False
If szDateValueName = "" Then Return False

keyArray = szRegKey.Split("\")
uB = UBound(keyArray)
szMasterKey = ""
For i = 1 To uB
szMasterKey = szMasterKey & keyArray(i) & "\"
Next
szMasterKey = szMasterKey.Substring(0, szMasterKey.Length - 1)

Try
Select Case keyArray(0)
Case "HKEY_CLASSES_ROOT"
rKey = Registry.ClassesRoot.OpenSubKey(szMasterKey,
True)
Case "HKEY_CURRENT_USER"
rKey = Registry.CurrentUser.OpenSubKey(szMasterKey,
True)
Case "HKEY_LOCAL_MACHINE"
rKey = Registry.LocalMachine.OpenSubKey(szMasterKey,
True)
Case "HKEY_USERS"
rKey = Registry.Users.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_CONFIG"
rKey = Registry.CurrentConfig.OpenSubKey(szMasterKey,
True)
End Select
Catch ex As Exception
Return False
End Try
szKeyEnc = rKey.GetValue(szKeyValueName).ToString()
szDateEnc = rKey.GetValue(szDateValueName).ToString()
rKey.Close()
If szKeyEnc = "" Then Return False
If szDateEnc = "" Then Return False

szKey = DecryptKey(szKeyEnc)
If szKey <> szKeyBaseString Then
Return False
End If

szDate = DecryptKey(szDateEnc)
If IsDate(szDate) = False Then Return False

szDateD = Convert.ToDateTime(szDate)
If DateDiff(DateInterval.Hour, szDateD, Now()) >= nHours Then
Return False
End If

Return True

End Function

Public Function SaveKeyToRegistry(ByVal szKeyValue As String) As
Boolean

Dim keyArray() As String
Dim rKey As RegistryKey = Nothing
Dim uB As Long
Dim szMasterKey As String
Dim i As Long
Dim szDate As String
Dim szDateEnc As String

If szRegKey = "" Then Return False
If szKeyValueName = "" Then Return False
If szDateValueName = "" Then Return False

keyArray = szRegKey.Split("\")
uB = UBound(keyArray)
szMasterKey = ""
For i = 1 To uB
szMasterKey = szMasterKey & keyArray(i) & "\"
Next
szMasterKey = szMasterKey.Substring(0, szMasterKey.Length - 1)

Try
Select Case keyArray(0)
Case "HKEY_CLASSES_ROOT"
rKey = Registry.ClassesRoot.OpenSubKey(szMasterKey,
True)
Case "HKEY_CURRENT_USER"
rKey = Registry.CurrentUser.OpenSubKey(szMasterKey,
True)
Case "HKEY_LOCAL_MACHINE"
rKey = Registry.LocalMachine.OpenSubKey(szMasterKey,
True)
Case "HKEY_USERS"
rKey = Registry.Users.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_CONFIG"
rKey = Registry.CurrentConfig.OpenSubKey(szMasterKey,
True)
End Select
Catch ex As Exception
Return False
End Try
szDate = Day(Now) & "/" & Month(Now) & "/" & Year(Now) & " " &
Hour(Now) & ":" & Minute(Now)
szDateEnc = GenerateKey(szDate)
Try
rKey.SetValue(szDateValueName, szDateEnc)
rKey.SetValue(szKeyValueName, szKeyValue)
rKey.Close()
Catch ex As Exception
rKey.Close()
Return False
End Try
Return True

End Function

Public Function GenerateKey(Optional ByVal szBaseString As String = "")
As String
Dim szOutput As String
Dim sHex As String
Dim sLen As Integer
Dim i As Integer
Dim nRet As String = ""

If szBaseString = "" Then szBaseString = GetBiosID()
szOutput = des.Encrypt(szBaseString)
sLen = szOutput.Length
For i = 0 To sLen - 1
sHex = Convert.ToString(Hex(Asc(szOutput.Substring(i, 1))))
If sHex.Length < 2 Then sHex = "0" & sHex
nRet = nRet & sHex
Next
If nRet.EndsWith("3D3D") Then nRet = nRet.Substring(0,
nRet.Length -
4)
Return nRet
End Function

Public Function DecryptKey(ByVal szBaseString As String) As String

Dim nRet As String = ""
Dim sChar As String
Dim sLen As Integer
Dim i As Integer

sLen = szBaseString.Length
For i = 0 To sLen - 1 Step 2
sChar = Chr("&H" & szBaseString.Substring(i, 2))
nRet = nRet & sChar
Next
Return des.Decrypt(nRet)

End Function

Public Function GetBiosID() As String
Dim searcher As Object = New ManagementObjectSearcher("SELECT *
FROM
Win32_BIOS")
Dim info As ManagementObject
Dim nRet As String = ""

For Each info In searcher.Get()
nRet += info("manufacturer").ToString() &
info("serialnumber").ToString()
Next
Return nRet

End Function

When I run this code in an application I get this:

System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="LicenseLib"
StackTrace:
at LicenseLib.License.SaveKeyToRegistry(String szKeyValue)
at Sample_Ins.frmMain.InstallRegisterNewKey(String szClientName,
Boolean isMachineLinked, Int64 nHours) in
E:\LicenseCode\Sample_Ins\Sample_Ins\frmMain.vb:line 95
at Sample_Ins.frmMain.btnSample_Click(Object sender, EventArgs e) in
E:\LicenseCode\Sample_Ins\Sample_Ins\frmMain.vb:line 50
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context)
at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason,
ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine)
at Sample_Ins.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

When I attempt to debug, I never even get a registry value created. HELP
PLEASE!
 
W

Walter Wang [MSFT]

Hi Michael,

The exception is a common one, for example, following code will throw
System.NullReferenceException:

Dim s as String
s.ToLower()

it's because s is not initialized yet.

Without actual working code, there's many possibilities that your code may
throw the exception. Therefore if you could provide a more complete code
listing, we can help you diagnose which statement is causing the exception.

During debugging, the debugger should help you locate the statement that is
causing this exception, how are you currently debugging the application?

Sincerely,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
G

Guest

I'm confused! I post the code block Project in my post and I'm asked to post
a more complete post in one response and in the previous response I'm told
posting the entire project is "TOO MUCH" code. Come on, please make up my
mind. I posted the entire project for the .dll and all of the exception that
is being thrown. I just want to get my project working and get on to the next
project.

The code that I posted is the code used to create or modify the registry.
Using RegMon from Systernals, I'm not seeing any attempt to even access the
registry with a create or modify. The program does however post the data to
the SQL Server database. I would also like the information stored on the
local machine, since that way it should reduce bandwidth to and from the
server.


_____________________________________________________________
Here is the code block where the registry creation fails:

'check if we succeed to register this new key for this client
'and this application on the our remote server
nRet = wsl.RegisterKey(szClientName, szBaseString, szEncKey,
szAppName, nHours)
If nRet = 0 Then ' success, new registration key as registered
on the remote server
'register the key locally___________________________________________________________________

lic.SaveKeyToRegistry(szEncKey)

** NullReferenceException was unhandled
Use the "new" keyword to create an object instance.
Check to dertermine if the object is null before calling the method.
Get general help for this exception

(szEncKey) is populated with the generated registry data

Upon viewing the Detail, the LicenseLib Project is the culprid and that is
what I posted in my original post.


Michael Bragg,
MS Authorized MAR
looking for used laptops for developmentally disabled.
 
W

Walter Wang [MSFT]

Hi Michael,

From the stack trace of the exception, the exception is thrown from the
function SaveKeyToRegistry. After going through the code of this function,
I do find some problem in the code:

Try
Select Case keyArray(0)
Case "HKEY_CLASSES_ROOT"
rKey = Registry.ClassesRoot.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_USER"
rKey = Registry.CurrentUser.OpenSubKey(szMasterKey, True)
Case "HKEY_LOCAL_MACHINE"
rKey = Registry.LocalMachine.OpenSubKey(szMasterKey, True)
Case "HKEY_USERS"
rKey = Registry.Users.OpenSubKey(szMasterKey, True)
Case "HKEY_CURRENT_CONFIG"
rKey = Registry.CurrentConfig.OpenSubKey(szMasterKey, True)
End Select
Catch ex As Exception
Return False
End Try

From the documentation of RegistryKey.OpenSubKey:

Rather than throwing an exception, a null reference (Nothing in Visual
Basic) is returned if the requested key does not exist.


This means a non-existing subkey will not raise exception, instead, a null
reference is returned. Therefore your Try-Catch block will not return False
as intended. You need to also check for the rKey value after the Try-Catch
block:

If rKey is Nothing Then Return False

Since I don't have a complete working project for your code, this is my
guess. If it's not the case, would you please take some time to create a
repro project and send it to me? Thanks.

By the way, you can easily add the LicenseLib project to your solution and
reference the project instead of compiled assembly, this way when the
exception is thrown, the debugger will locate the offending code.



Regards,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top