save and load value from registry in vb.net - vb.net

I have an application where the user select configuration, I need to write to function one to save the configuration when the application is closed and other load the configuration when the application is loaded, i need to use registry would you able to help me by giving me 2 small example how to save and to load from the registry.
thank you
Jp

The "My" Class in VB contains almost everything you need.
To read data:
My.Computer.Registry.LocalMachine.GetValue("mykey")
To write data:
My.Computer.Registry.LocalMachine.SetValue("mykey", "myvalue")
Hope it helps.

Look into the Registry Class. The KEYS exposed by this class are
CurrentUser - Stores information about user preferences.
LocalMachine - Stores configuration information for the local machine.
ClassesRoot - Stores information about types (and classes) and their properties.
Users - Stores information about the default user configuration.
PerformanceData - Stores performance information for software components.
CurrentConfig - Stores non-user-specific hardware information.
It's important to understand the the use of these keys so information can be saved for user specific instances or machine.
I wasn't sure what version of .NET Framework you are using.
Sample data from MS
Imports Microsoft.VisualBasic
Imports System
Imports System.Security.Permissions
Imports Microsoft.Win32
Public Class RegKey
Shared Sub Main()
' Create a subkey named Test9999 under HKEY_CURRENT_USER.
Dim test9999 As RegistryKey = _
Registry.CurrentUser.CreateSubKey("Test9999")
' Create two subkeys under HKEY_CURRENT_USER\Test9999.
test9999.CreateSubKey("TestName").Close()
Dim testSettings As RegistryKey = _
test9999.CreateSubKey("TestSettings")
' Create data for the TestSettings subkey.
testSettings.SetValue("Language", "French")
testSettings.SetValue("Level", "Intermediate")
testSettings.SetValue("ID", 123)
testSettings.Close()
' Print the information from the Test9999 subkey.
Console.WriteLine("There are {0} subkeys under Test9999.", _
test9999.SubKeyCount.ToString())
For Each subKeyName As String In test9999.GetSubKeyNames()
Dim tempKey As RegistryKey = _
test9999.OpenSubKey(subKeyName)
Console.WriteLine(vbCrLf & "There are {0} values for " & _
"{1}.", tempKey.ValueCount.ToString(), tempKey.Name)
For Each valueName As String In tempKey.GetValueNames()
Console.WriteLine("{0,-8}: {1}", valueName, _
tempKey.GetValue(valueName).ToString())
Next
Next
' Delete the ID value.
testSettings = test9999.OpenSubKey("TestSettings", True)
testSettings.DeleteValue("id")
' Verify the deletion.
Console.WriteLine(CType(testSettings.GetValue( _
"id", "ID not found."), String))
testSettings.Close()
' Delete or close the new subkey.
Console.Write(vbCrLf & "Delete newly created " & _
"registry key? (Y/N) ")
If Char.ToUpper(Convert.ToChar(Console.Read())) = "Y"C Then
Registry.CurrentUser.DeleteSubKeyTree("Test9999")
Console.WriteLine(vbCrLf & "Registry key {0} deleted.", _
test9999.Name)
Else
Console.WriteLine(vbCrLf & "Registry key {0} closed.", _
test9999.ToString())
test9999.Close()
End If
End Sub
End Class

Related

Find username from email address in active directory vb.net

Sorry, i checked the link "Find username from Active Directory using email id" but that's for C# i can't figure that out how to do in Vb.net.
In my gridview when i select the row to get the email id and pass it to AD to find the user name but so far i can't figure that out what command will give that details in VB.net
Protected Sub grdValidate_RowUpdating(sender As Object, e As EventArgs)
Dim strEmail As String = grdValidate.SelectedRow.Cells(2).Text
Dim ctx As New PrincipalContext(ContextType.Domain)
' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, strEmail)
End Sub
i saw this property "UserPrincipal.EmailAddress" but VS is not even recognize the command. Obviously i imported
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
I am trying to find a command to pass the email and match the email id in AD and get the user information.
Thanks in Advance
You need to add .NET references to System.DirectoryServices and System.DirectoryServices.AccountManagement and then...
Using context As New System.DirectoryServices.AccountManagement.PrincipalContext(DirectoryServices.AccountManagement.ContextType.Domain, strDomainName)
Dim yourUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, strEmailAddress)
If yourUser IsNot Nothing Then
strFirstName = yourUser.GivenName
strLastName = yourUser.Surname
End If
End Using
MsgBox(strFirstName & " " & strLastName)
I've used fully qualified names for clarity, but you can tidy things up with Imports System.DirectoryServices.AccountManagement at the beginning of the module

My.User.CurrentPrincipal not working in Class Library

I am trying to get the current username in a Windows environment that uses Windows Authentication. The code exists in a class library that is built and referenced within a separate Visual Studio application:
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function
I get an error when it's located in the class library. My.User.CurrentPrincipal comes back with {System.Security.Principal.GenericPrincipal} and My.User.Name is blank. When I put the exact same code into a brand new windows forms application it works - My.User.CurrentPrincipal comes back with {System.Security.Principal.WindowsPrincipal} and My.User.Name is the user's login name.
Microsoft documentation suggests that the My.User object will work in class libraries. Does anyone know why I'm getting different values when it's put into a class library and added as a .dll reference to a parent application?
The parent application is a class library that is an add-in for Microsoft PowerPoint. The code in the parent application that calls the above code (called UsageDataCollection.dll) is:
Public Class rbnOvaPowerPoint
Private DataCollector As UsageDataCollection.DataCollector
Private Sub butShare_Click(sender As Object, e As RibbonControlEventArgs) Handles butShare.Click
OtherTasks.CreateMailItem()
End Sub
End Class
And then in a separate module:
Module OtherTasks
Private DataCollector As New UsageDataCollection.DataCollector
Sub CreateMailItem()
Dim OutlookApp As Outlook._Application = CreateObject("Outlook.Application")
Dim mail As Outlook.MailItem = Nothing
Dim mailRecipients As Outlook.Recipients = Nothing
Dim mailRecipient As Outlook.Recipient = Nothing
DataCollector.UsageStatistics("CreateMailItem")
Try
mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)
mail.Subject = "OvaPowerPoint"
mail.Body = "Check out OvaPowerPoint, a custom-built Arup add-in for PowerPoint!" & Strings.Chr(13) & Strings.Chr(13) & "About the Add-In:" & Strings.Chr(13) & "http://wiki.oasys.intranet.arup.com/X-Wiki/index.php/OvaPowerPoint" & Strings.Chr(13) & Strings.Chr(13) & "Installation File:" & Strings.Chr(13) & "\\n-ynas12\Software\Custom%20Applications\Plug-Ins\Microsoft%20PowerPoint\OvaPowerPoint\setup.exe"
mail.Display(True)
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message,
"An exception is occured in the code of add-in.")
Finally
If Not IsNothing(mailRecipient) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mailRecipient)
If Not IsNothing(mailRecipients) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mailRecipients)
If Not IsNothing(mail) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mail)
End Try
End Sub
End Module
And the UsageStatistics subroutine in UsageDataCollection.dll looks like:
Imports System.IO
Imports System.Text
Public Class DataCollector
Public Sub UsageStatistics(myAction As String)
Dim myAssemblyName As String = System.Reflection.Assembly.GetCallingAssembly.GetName.Name
Dim myFilePath As String = "\\n-ywpress01\uploads\UsageData\" & myAssemblyName & ".csv"
Using LogFile As New StreamWriter(myFilePath, True)
LogFile.WriteLine("[" & DateTime.Now.ToUniversalTime.ToString("yyyy/MM/dd HH':'mm':'ss") & "]" & Chr(44) & GetUserName() & Chr(44) & GetUserLocation() & Chr(44) & myAction)
LogFile.Close()
End Using
End Sub
End Class
Thanks
Zak
In the MS docs, it says
For Windows applications, only projects built on the Windows Application template initialize the My.User object by default. In all other Windows project types, you must initialize the My.User object by calling the My.User.InitializeWithWindowsUser Method explicitly or by assigning a value to CurrentPrincipal.
The fix in your code is:
Function GetUserName() As String
My.User.InitializeWithWindowsUser() 'pulls the network credentials into .NET
If TypeOf My.User.CurrentPrincipal Is
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function

Registry: Search for known String Value and return the name of the SubKey it resides in

I have an automation app I am developing for an isolated environment. One of its features will be to automate clearing a Windows user profile from the registry path HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\
The trouble I am having is in how to determine I am removing the correct subkey, as each subkey under this path is cryptic. I can identify the correct subkey visually in regedit by opening each subkey and inspecting for the String Value I am looking for (ProfileImagePath = C:\Users\USERANME).
Example: Subkey = S1-5-21-420551719-245851362-9522986-177556
Contains String Value = ProfileImagePath = C:\Users\n9000988
I already have a function that seeks and finds all available usernames, then a user control to select which username to work with.
So in this example, n9000988 is defined and selected.
So now I just need the ability to define what subkey the stringvalue resides in. Once I have that, I can then call to remove the subkey as that is the end goal of this sub.
What I've tried so far:
For Each subKeyName As String In My.Computer.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList").GetSubKeyNames()
For Each profPath As String In My.Computer.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & subKeyName).GetValue("ProfileImagePath")
MsgBox(profPath)
Next
Next
But this returns a MsgBox for each and every character in ProfileImagePath for all subkeys that contain the string ProfileImagePath.
I almost feel like my logic in this sub is trying to go too far forward before it can determine how to get the name of the subkey.
This one is making my brain hurt. Any help would be appreciated.
UPDATE:
That was perfect and so clean!!!
End result -
Public Class Dialog3
Private Function Username_To_SID(ByVal Username As String) As String
Return New Security.Principal.NTAccount(Username).Translate(GetType(Security.Principal.SecurityIdentifier)).Value
End Function
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
' Kill SearchIndexer to release locked files
Try
Process.GetProcessesByName("SearchIndexer")(0).Kill()
Catch ex As Exception
End Try
Dim userID As String = Dialog1.ListBox1.SelectedItem
Dim userPath As String = "C:\users\" & userID
' Rename user folder
Try
My.Computer.FileSystem.RenameDirectory(userPath, userID & ".BAK")
Catch ex As Exception
MsgBox("Failed to rename user folders path")
End Try
Try
My.Computer.Registry.LocalMachine.DeleteSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & (Username_To_SID(Dialog1.ListBox1.SelectedItem)))
Catch ex As Exception
MsgBox("Failed to remove registry entry in ProfileList")
End Try
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Dialog1.Close()
Me.Close()
End Sub
I want to suggest you to stop using/searching/parsing registry techniques while you are programming in .NET, you can do it all using pure .NET code.
If I understanded good what you want is to know the equivalent SID of an Username, then you could use this:
' [ Username To SID ]
'
' // By Elektro H#cker
'
' Usage Examples:
' MsgBox(Username_To_SID("Administrator")) ' Result like: S-1-5-21-250596608-219436059-1115792336-500
''' <summary>
''' Returns the SecurityIdentifier of an existing Username.
''' </summary>
''' <param name="Username">Indicates the username to retrieve the SID.</param>
Private Function Username_To_SID(ByVal Username As String) As String
Return New Security.Principal.NTAccount(Username).
Translate(GetType(Security.Principal.SecurityIdentifier)).Value
End Function

Concurrency Issues with multiple linked aacdb files

I've started to run into some concurrency issues with my databases. I have roughly ten different aacdb files in a shared location on our office network. One of these databases is kind of the 'master' database. It is split into backend and front end. The backend of this databases holds common tables such as users/passwords, employees, departments, etc etc.
Yesterday, I made two databases purely for input. They each have a single form bound to a table in 'data entry' mode, with record locks set to 'edited record.' They also link to some of the same tables shared by other databases. This is where I started to run into (likely?) concurrency issues for the first time.
People have been reporting odd behavior (forms not opening, etc) in the 'master' database. This was tested a bit and only happens when users are also in the linked data-entry only databases.
There are still less than ten current users across all of the databases at a given time.
Would drop down selections hold a lock on a table, preventing certain forms from opening?
AFAIK, dropdowns are just queried when the form is loaded.
Any ideas?
I had fits with this issue, trying to have several users share the same front end from a network share. Things would just...not work. Then when I went back it was impossible to dupilcate the failures. I decided to have the application installed on the local machines, but this had version control issues, especially since I had several different front ends running at the same time for different projects. There were updaters out there but they either cost money or I couldnt see the code and didnt trust them. I came up with this as a solution and have been using it since Access 2003.
This is a seperate ACCESS database, you have to lock it down just like you would any front end.
This launcher works for the four access front ends that I am running right now. There are two table that you have to setup on the network.
TABLE NAME: RunTimeTracking
FIELD: RTTID : AutoNumber
FIELD: RTTComputerName : Text
FIELD: RTTLoginTime : Date/Time
TABLE NAME: VersionControlTable
FIELD: VCTID : AutoNumber
FIELD: VCTVersion : Number
FIELD: VCTSourceLoc : Text
FIELD: VCTDest : Text
FIELD: VCTDateVer : Date/Time
The RunTimeTracking table works to prevent the user from starting the actual application without using the launcher. When the launcher runs it inserts a entry into the table with the computer name. When the application runs it looks for that entry, if it doesnt see it. It warns and dumps.
In the version control table put the location of the most up to date app, the location on the local machine where you want the applicaiton to be stored.
If you have more than one program that you are controlling, then increment VCTVersion entry and reference it in your code in the launcher.
strSQL = "SELECT * FROM VersionControlTable WHERE VCTVersion = 200"
When the launcher runs it checks the CREATED datestamp on the local file to the one on the network, if they are different, it copies. If not, it runs.
Private Sub Form_Load()
DoCmd.ShowToolbar "Ribbon", acToolbarNo
DoCmd.ShowToolbar "Status Bar", acToolbarNo
DoCmd.Maximize
Form.TimerInterval = 2000
End Sub
Private Sub Form_Timer()
runDataCheck
End Sub
Private Sub runDataCheck()
' This is the launcher program. This program is designed to check for
' Version information and upload and download the new version automaticaly.
' Place entry into the Run Time Tracking Table. This will be used by the Main Application to verify that
' The application was launched by the Launcher and not run straight from the desktop
'First, retrieve the name of the computer from the Environment.
Dim strCompName As String
strCompName = Environ("computername")
' Now, delete all entries on the tracking table that have this computer name associated with it.
' Later we will try to add a trigger that archives the logins.
Dim strSQL As String
strSQL = "DELETE FROM RunTimeTracking WHERE RTTComputerName = '" & strCompName & "'"
adoSQLexec (strSQL)
' Now, add and entry into the table
strSQL = "INSERT INTO RunTimeTracking (RTTComputerName,RTTLoginTime) VALUES ('" & strCompName & "','" & Now() & "')"
adoSQLexec (strSQL)
' First, retrieve the parameters from the Version Control File and put them into variables that we can use.
Dim strSource As String
Dim strDest As String
Dim dateVer As Date
Dim rs As New ADODB.Recordset
'LBLSplashLabel.Caption = "Checking Version Information...."
strSQL = "SELECT * FROM VersionControlTable WHERE VCTVersion = 200"
With rs
rs.Open strSQL, CurrentProject.Connection
End With
strSource = rs.Fields("VCTSourceLoc").Value
strDest = rs.Fields("VCTDest").Value
dateVer = rs.Fields("VCTDateVer").Value
Set rs = Nothing
' Next. See if the folders on both the local drive and the source drive exists.
Dim binLocal As Boolean
Dim binNet As Boolean
Dim binDirectoryLocal As Boolean
'Debug.Print strSource
' First check to see if the network file exists.
binNet = FileExists(strSource)
If binNet = False Then
MsgBox ("The network source files are missing. Please contact Maintenance!")
Application.Quit (acQuitSaveNone)
End If
' Get the timestamp from the network version since it exists.
Dim fileNet As File
Dim fileLocal As File
Dim fileNetObject As New FileSystemObject
Set fileNet = fileNetObject.GetFile(strSource)
Debug.Print strSource
Debug.Print "Created Date : " & fileNet.DateCreated
Dim strDirName As String
Dim intFind As Integer
' Check to see if the Local file Exists.
binLocal = FileExists(strDest)
If binLocal = False Then
'There is no local file. Check to see if the directory exists
' Get the directory name
intFind = (InStrRev(strDest, "\", , vbTextCompare))
strDirName = (Left(strDest, intFind - 1))
Debug.Print "Directory Name: " & strDirName
binDirectoryLocal = FolderExists(strDirName)
If binDirectoryLocal = False Then
'There is no local directory. Create one
MkDir (strDirName)
' LBLSplashLabel.Caption = "Copying Files...."
'Copy the source file to the directory.
FileCopy strSource, strDest
'Since we have no copied the latest version over, no need to continue. Open the main app
OpenMaintApp (strDest)
Else
' No need to create the directory, simply copy the file.
'Copy the source file to the directory.
' LBLSplashLabel.Caption = "Copying Files...."
FileCopy strSource, strDest
'Since we have no copied the latest version over, no need to continue. Open the main app
OpenMaintApp (strDest)
End If
End If
'Now we know that the file is in the directory, now we need to check its version.
'Get the last modified date from the file.
Set fileLocal = fileNetObject.GetFile(strDest)
Debug.Print "Last Modified Date : " & fileLocal.DateCreated
'Do the version check
If fileLocal.DateCreated <> fileNet.DateCreated Then
' LBLSplashLabel.Caption = "Copying Files...."
'Copy the source file to the directory.
FileCopy strSource, strDest
'Since we have no copied the latest version over, no need to continue. Open the main app
OpenMaintApp (strDest)
Else
OpenMaintApp (strDest)
End If
OpenMaintApp (strDest)
End Sub
Private Sub OpenMaintApp(strAppName As String)
Dim accapp As Access.Application
Set accapp = New Access.Application
accapp.OpenCurrentDatabase (strAppName)
accapp.Visible = True
DoCmd.Quit acQuitSaveNone
End Sub

Trouble writing to App.Config file

Having issues reading/writing to App.config.
The code I have below I took from the MSDN article on (AppSettingsSection Class)
http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.100%29.aspx
I am successfully able to read the App.config file and get/use the values and it responds correctly if I change the App.config file to get the new values.
However, in this (from MS page) I add a new entry and change a value on one of my initial entries. It appears to change it, does not error in saving it, but does not write it to the file so the next time I run, I am back to my initial values in App.config.
Can someone show me my erroneous ways?
TIA!
Imports System
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Text
Imports System.IO
' IMPORTANT: To compile this example, you must add to the project
' a reference to the System.Configuration assembly.
'
Module Module1
Sub Main()
Dim KeypairHolder As String = Nothing
' Get Configuration File as config object
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' Create a unique key/value pair to add to the appSettings section.
Dim keyName As String = "DateTimeStamp Number " & config.AppSettings.Settings.Count + 1
Dim value As String = String.Concat(Date.Now.ToLongDateString(), " ", Date.Now.ToLongTimeString())
' Create appSettings as object
Dim appSettings As System.Configuration.AppSettingsSection = config.AppSettings
' add the new key and value
appSettings.Settings.Add(keyName, value)
' save and refresh the values
config.Save(ConfigurationSaveMode.Modified)
' Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings")
' Get keys
Dim kAll() As String = appSettings.Settings.AllKeys()
' Build string to display
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
'Display
MsgBox(KeypairHolder)
' Change a value
appSettings.Settings("CustomKey").Value = "Changed Value"
' Resave and get and display
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
kAll = appSettings.Settings.AllKeys()
KeypairHolder = Nothing
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
MsgBox(KeypairHolder)
End Sub
End Module
' appSettings Section of my App.Config file
' <appSettings>
' <add key="UsernamePassword" value="BobsUsername:BobsPassword"/>
' <add key="CustomKey" value="ConfigApp Value"/>
' </appSettings>
Right click on the app.config file in your solution explorer window and select the Properties option. Ensure that the Copy to Output Directory property is NOT set to Copy always.