Get Account management - Display Name - Vb.net - vb.net

This little piece of code gets the system current logged in user's Display name
Imports System.DirectoryServices.AccountManagement
Dim userFullName As String = UserPrincipal.Current.DisplayName
Label1.Text = "Hi " & userFullName & ", Welcome !!"
The above code works fine when i connected the LAN to the computer. but when LAN is removed and WIFI is connected it doesn't work .. Can someone guide the workaround for this?

This method only works as long as the directory server can be contacted.
Otherwise you get a PrincipalServerDownException.
As a workaround you could cache the displayname while the server is reachable.
You can cache it for example inside My.Settings.
Create a user scoped setting named cachedDisplayname and use the following method:
Function GetUserDisplayName() As String
Dim userFullName As String
Try
'Reading the displayname from the directory
userFullName = UserPrincipal.Current.DisplayName
'Saving the displayname in My.Settings
My.Settings.cachedDisplayname = userFullName
My.Settings.Save()
Catch ex As PrincipalServerDownException
If String.IsNullOrWhiteSpace(My.Settings.cachedDisplayname) Then
'displayname has not been cached yet, use Username as compromise solution
userFullName = Environment.UserName
Else
'read the cached displayname from My.Settings
userFullName = My.Settings.cachedDisplayname
End If
End Try
Return userFullName
End Function
Setting the label-text:
Label1.Text = String.Format("{0}, Welcome !!", GetUserDisplayName())

Related

Finding user name of current logged in user using VB.NET

I'm trying to get the user name of the current user. When I log in as Johnny Smith and run my application without administrator privileges it will return me the correct user name, Johnny Smith. But the problem is that when I right click and choose "Run as Administrator", Windows will prompt me with a login screen for the administrator and after login my application returns user name admin, not the user which is logged in currently.
I have tried:
strUserLabel.Text = Environment.UserName
Also
Dim WSHNetwork = CreateObject("WScript.Network")
Dim strUser = ""
While strUser = ""
strUser = WSHNetwork.Username
End While
strUserLabel.Text = strUser
Both return me the administrator user name when prompted as administrator.
In the MSDN documentation, I discovered they changed the definition of property Environment.UserName.
Before .NET 3
Gets the user name of the person who started the current thread.
Starting from version 3
Gets the user name of the person who is currently logged on to the Windows operating system
I think the accepted answer above is a VERY resource intensive way to find a username. It has nested loops with hundreds of items. In my 8GP RAM PC this takes 2+ seconds!
How about:
Username: SystemInformation.Username, and
DomainName: Environment.UserDomainName
Tested in VS2017
I have figured it out. I used this function which will determine which process which the user is using. In my code I defined that look for username of the explorer.exe process.
Function GetUserName() As String
Dim selectQuery As Management.SelectQuery = New Management.SelectQuery("Win32_Process")
Dim searcher As Management.ManagementObjectSearcher = New Management.ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As Management.ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = "explorer.exe" Then
Return s(0)
End If
Next
End Function
Index of 0 will return username
Index of 1 will return domain name of user
SystemInformation.Username doesn't work for certain applications. In my case, code is being run as System but explorer.exe is being run as Daniel. SystemInformation.Username reports System.
if using Identity
Dim UserEmail As String = Context.User.Identity.Name.ToString

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

Trying to get AD Username using VB.net but its returning serverName$

I'm creating a App which people will log into using Remote Desktop Connection to our server but I need to get the AD username via VB.net and store it. I've tried loads of methods of getting the username such as:
Protected oNet = CreateObject("WScript.NetWork")
Protected user5 = oNet.UserName
Protected userName = oNet.ExpandEnvironmentStrings("%UserName%")
Protected userName1 = Environment.UserName
Protected objSysInfo = CreateObject("ADSystemInfo")
Protected objUser = GetObject("LDAP://" & objSysInfo.UserName)
Protected userName2 As String = objUser.CN
Plus a few other methods but all it seems to be returning is "Server-Name$". Am I missing something in IIS or have I just got the wrong end of the stick completely?
Any help would be much appreciated!
CreateObject("WScript.Network").UserName
This should return the username of the user in whose context your script/application is running.
CreateObject("WScript.Network").ExpandEnvironmentStrings("%UserName%")
This should fail, because the WshNetwork object doesn't have an ExpandEnvironmentStrings method. You need a WshShell object instead:
CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERNAME%")
Environment.UserName
This probably should return the username of the user in whose context your script/application is running in vb.net. It should fail in vbscript, because there you can only access the Environment collection through a WshShell object:
CreateObject("WScript.Shell").Environment("PROCESS")("USERNAME")
GetObject("LDAP://" & CreateObject("ADSystemInfo").UserName).CN
The user (account) name is stored in the sAMAccountName attribute, not in the cn attribute.

Windows Service not able to access mapped folders

I have a very simple VB.net Windows Service written using VS.net 2008. The program after doing several other functions writes a log in one of the network folders. The code is as shown below: If I change the path from "Y:\Activity_Log" to "C:\Activity_Log" it is working like a charm.
What is the problem if I use Y drive which is a valid one and I am able to access it from other VB.net desktop apps. Please help.
Dim strFile As String = "Y:\Activity_Log\" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim fs As FileStream = Nothing
Dim activityfolder As String = "Y:\Activity_Log"
Dim di As System.IO.DirectoryInfo
di = New System.IO.DirectoryInfo(activityfolder)
If (Not di.Exists) Then
di.Create()
End If
If (Not File.Exists(strFile)) Then
Try
Dim sw1 As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw1.WriteLine("******************************Activity Log for " & Now.Date & "*******************")
sw1.WriteLine("-----------------------------------------------------------------------------------------------------------------")
sw1.WriteLine(Remarks & " ---" & DateTime.Now)
sw1.Close()
Catch ex As Exception
End Try
Else
Dim sw As StreamWriter
sw = AppendText(strFile)
sw.WriteLine(Remarks & " ---" & DateTime.Now)
sw.Close()
End If
Start->Control Panel->Administrative Tools->Services
Find Your service in the list, right click on the name, Properties
Click the Log On tab
Change from Local System account to 'This Account'
Use a user that has access to that share, start with your username/password to convince yourself that it works ;)
Click Ok, then restart the service.
maybe you need to run the service under a user that has access to that drive?
maybe the generic service user doesn't have access.

How to save the input values?

Using VB.Net
Database Form
Server Name, Username, Password - textbox
SQL Authentication, windows Authentication - checkbox
I have Database Form, First Time i run my software, I have to give Server Name, Window or SQL Authentication mode, UserName and password. Next Time I run the software, given data's like Server name, username, password, window or sql authentication should appear in the form.
Before I used VB6, I used the ini file for getting the username, password and servername.
vb6 code.
Dim File As String, OFLen As Double, str As String
File = App.Path & "\SQLServer.ini"
OFLen = FileLen(File)
SName = ReadIni(File, "Server", "ServerName")
UName = ReadIni(File, "UserName", "UName")
PWord = ReadIni(File, "Password", "PWord")
Dim ConnectionString As String
Set DLTConn = New ADODB.Connection
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI; Persist Security Info=False;Initial Catalog=database1;Data Source=" & SName & ""
DLTConn.Open ConnectionString
There is any option is available in the vb.net for saving the data's or i have to use the same format(ini file) in vb.net
Need vb.net code Help.
These instructions assume VB2008 but I believe that 2010 is similar.
As #treaschf said, right click on your project in the Solution Explorer and select properties. If a window pops up with a title "Solution '...' Property Pages" then you clicked on the solution instead of the project. In the property window click on Settings. In the name column enter "Username", leave the type as String, the scope as User and the value as empty (unless you want to enter a default). Repeat this with each property that you want to store. These steps automatically create variables that you can access using My.Settings..
So in your code-behind you can do:
My.Settings.Username = "bob"
And:
Dim username as String = My.Settings.Username
I believe that settings will automatically be saved on exit but I recommend making an explicit call after updating just in case.
My.Settings.Save()
So that will pretty much do the same as you INI file used to do. But like #treaschf said, you should really encrypt the password when saving to disk. Below is a modified version of the routine found here. http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx . I removed the System.Security.SecureString because as nice as it is it also makes life more complicated. Change the value of Entropy to anything you want, call Encrypt(string) to encrypt your text and Decrypt(string) to decrypt it. This uses DPAPI so you don't have to worry about messing with the registry, permissions and everything else.
Private Shared entropy As Byte() = System.Text.Encoding.Unicode.GetBytes("Enter some text here for entropy")
Public Shared Function EncryptString(ByVal text As String) As String
Dim data = System.Security.Cryptography.ProtectedData.Protect(System.Text.Encoding.Unicode.GetBytes(text), _
entropy, _
System.Security.Cryptography.DataProtectionScope.CurrentUser)
Return System.Convert.ToBase64String(data)
End Function
Public Shared Function DecryptString(ByVal encryptedData As String) As String
Dim data As Byte() = System.Security.Cryptography.ProtectedData.Unprotect(System.Convert.FromBase64String(encryptedData), _
entropy, _
System.Security.Cryptography.DataProtectionScope.CurrentUser)
Return System.Text.Encoding.Unicode.GetString(data)
End Function
And then to put it all together:
My.Settings.Username = EncryptString("bob")
Dim username As String
If Not String.IsNullOrEmpty(My.Settings.Username) Then
Try
username = DecryptString(My.Settings.Username)
Catch ex As Exception
'There was a problem decrypting the username
End Try
End If
Trace.WriteLine(username)
If you right-click on your project in Solution Explorer, and chose Properties, on the properties page there will be a Settings tab, in which you define the settings of your application.
These settings will be stored in an XML file, near the executable of your application. (Or in case of user-settings, in the C:\Users\username... directory.
If you name your connection string setting as DbConnectionString, you will be able to access it from code like this:
My.Settings.DbConnectionString
However if you need to store user names and passwords, I would recommend you to store the settings in the Windows registry, and encrypt them with the System.Security.Cryptography.ProtectedData class. (Storing the password unencrypted is not recommended.)