Editting the registry in VB.NET - vb.net

I used the code necessary to change the DWord of a registry in VB.NET however I need to always Right click and run as administrator for it to work. In order to prevent this I passed the administrator user credentials before executing the command, however I get an error message.
The code I used for this purpose is,
Dim regVersion As RegistryKey
regVersion = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services\\USBSTOR", True)
Try
Dim intVersion As Integer = 4
intVersion = regVersion.GetValue("Start", 0)
intVersion = intVersion + 1
End If
Dim p As New ProcessInfo(regVersion.SetValue("Start", intVersion))
p.UseShellExecute = False
p.Domain = "domain"
p.UserName = "Yoosuf"
p.Password = New System.Security.SecureString()
Dim q As New System.Security.SecureString()
For Each c As Char In
q.Password.AppendChar(c)
Next
Process.Start(p)
regVersion.Close()
Catch es As Exception
End Try
However I receive an error message on the line
Dim p As New ProcessInfo()
Could anyone please let me know what is the mistake I have done

The error is most likely because this code:
Dim p As New ProcessInfo(regVersion.SetValue("Start", intVersion))
doesn't make any sense. The ProcessInfo constructor is expecting a string, which specifies the name of the file or application to be started. You've passed it the result of the RegistryKey.SetValue method, which does not return a value.
Considering the real problem that you want to solve is,
I need to always Right click and run as administrator for it to work
then the real solution is to add a manifest to your application that indicates it should be launched with administrative privileges. This would free you from having to right-click and explicitly choose "Run as administrator" each time. Instead, the application's process would be automatically elevated (if possible), or you would be prompted for permission by UAC.
To do this in Visual Studio for a VB.NET application, you need to modify the default manifest that is embedded into the application. Here are the steps:
Right-click on your project in the Solution Explorer, and select "Properties".
Open the "Application" tab.
Click "View Windows Settings".
This opens the default manifest. Change the <requestedExecutionLevel> element to requireAdministrator.
It should look like this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Related

VBNet changing Active Directory passwords of expired or one time password accounts

I need to change the Passwords of an Active Directory account in windows 10 in VB.NET.
The program, I wrote, runs as local administrator,
My working code with a valid user account is (Domain_xps and UserName_xps are Strings and pwdPtr System.Runtime.InteropServices.Marshal.SecureStringToBSTR of a SecureString):
dEntry = New DirectoryServices.DirectoryEntry("LDAP://" & Domain_xps, UserName_xps
, System.Runtime.InteropServices.Marshal.PtrToStringBSTR(pwdPtr)
, System.DirectoryServices.AuthenticationTypes.Secure
+ System.DirectoryServices.AuthenticationTypes.Sealing
+ System.DirectoryServices.AuthenticationTypes.ServerBind) ',pwd)
nativeObject = dEntry.NativeObject
Dim searcher_Fullname_xpo As System.DirectoryServices.DirectorySearcher
= New System.DirectoryServices.DirectorySearcher(dEntry)
With searcher_Fullname_xpo
.Filter = "(&(objectClass=User) (sAMAccountName=" & UserName_xps & "))"
End With
result_xpo = searcher_Fullname_xpo.FindOne
Dim user As DirectoryServices.DirectoryEntry 'open directory
user = result_xpo.GetDirectoryEntry() 'get directory results
user.Username = UserName_xps
user.Password = PWD_xps
user.Path = result_xpo.GetDirectoryEntry().Path
user.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure
+ System.DirectoryServices.AuthenticationTypes.Sealing
+ System.DirectoryServices.AuthenticationTypes.ServerBind
user.Options.PasswordPort = 389
user.Options.PasswordEncoding = 1
user.Invoke("ChangePassword", New Object() {PWD_xps, PWDNeu_xps})
user.CommitChanges() 'commit changes
user.Close() 'close directory
But if a account has expired through holidays or if a new user with a one time password is generated and tries to change his password, i get an error.
The user or password are wrong.
while debugging i noticed, that following lines produce the same error.
nativeObject = dEntry.NativeObject
Dim searcher_Fullname_xpo As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(dEntry)
With searcher_Fullname_xpo
.Filter = "(&(objectClass=User) (sAMAccountName=" & UserName_xps & "))"
End With
result_xpo = searcher_Fullname_xpo.FindOne
And also
user.Options.PasswordPort = 389
user.Options.PasswordEncoding = 1
user.Invoke("ChangePassword", New Object() {PWD_xps, PWDNeu_xps})
each of these produce the error and doesn't change the password correctly, after encapsulating every line in a try catch expression.
Active Directory shows a change, but the user account is not valid any more.
I tried basically the same methods, in hope that i could set the options.
Dim ADS_OPTION_PASSWORD_PORTNUMBER As Long = 6
Dim ADS_OPTION_PASSWORD_METHOD As Long = 7
Dim ADS_PASSWORD_ENCODE_REQUIRE_SSL As Integer = 0
Dim ADS_PASSWORD_ENCODE_CLEAR As Integer = 1
Try
user.Invoke("SetOption", New Object() {ADS_OPTION_PASSWORD_PORTNUMBER, 389})
Catch ex3 As Exception
End Try
Try
user.Invoke("SetOption", New Object() {ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR})
Catch ex3 As Exception
End Try
And i tried also
user.Invoke("SetPassword", New Object() {PWDNeu_xps})
the error message stays the same
To set the password seems the right way, but as i can't set the password port or enable the password method, it produces the same error.
i also found this old thread How to change password in active directory when password expired
but that is not longer possible under windows 10.
How can i change the password, of an expired account with the needed options in VB Net or can i configure the account, so that it is possible to achieve it.
So an update on this situation. 28.10.2021
I also tried as workaround a powershell command as described in Microsoft or here for that matter.
And the same thing happens, the password change isn't possible,
Set-ADAccountPassword : The server has rejected the client credentials.
With a valid user the comand works as does it in DotNet
Write a program in a 32 bit version of C or up to C++11 on a 32 bit version of Microsoft Windows up to XP pro sp2 (and not later version) which does what you want to do. Compile it with Code::Blocks up to version 17.12 and not a later version. Do not allow any version of Visual C++ or Visual Basic or Visual Studio on that computer before or during this process.
Load and run that program, on your Windows 10 computer, as the highest administrator level that Windows 10 will "allow". If you cannot get it to run compiled as GUI, then try to get it to run compiled as CLI. Remember, This is Extremely important: Compile the program as a stand-alone single executable that uses NO external dlls.
Change the password outside of any Windows 10 commands. Edit the file that they are in with your program, and do not tell Windows 10 anything is happening.

Unable to set write permission on file

I want to create a file and give a user write permission.
IO.File.Create(Path & "\test.json")
Dim fs As Security.AccessControl.FileSecurity = IO.File.GetAccessControl(Path & "\test.json")
Dim far As Security.AccessControl.FileSystemAccessRule = New Security.AccessControl.FileSystemAccessRule("DOMAIN\USER", Security.AccessControl.FileSystemRights.WriteData, Security.AccessControl.AccessControlType.Allow)
fs.AddAccessRule(far)
When I check the Security tab for this file, I see no changes. VS2015 output window does not show any exceptions. VS2015 is running as Administrator.
I used this for reference: https://msdn.microsoft.com/en-us/library/d49cww7f(v=vs.110).aspx
All you have changed in your code is the in-memory file security. In order to apply these changes to the file, you must call SetAccessControl.
For example:
File.SetAccessControl(Path & "\test.json", fs)

Getting selected files filepath without OpenFileDialog

I was wondering if there is anyway to get the file path of a selected file. I have registered a hotkey in reference to this.
E.g. RegisterHotKey(Me.Handle, 100, MOD_CONTROL Or MOD_SHIFT, Keys.D2)
Which will do certain actions on pressing ctrl, shift and 2. What i want to do is to get the path of a selected file WITHOUT opening OpenFileDialog
e.g. i select mydoc.doc located on my desktop, press ctrl shift and 2, and it will msgbox out the location of the file.
(meaning i click the file mydoc.doc on my desktop, press my hotkey and get the file location. Is there anyway to do this? (Just like how you would click a file in a folder to copy and paste it to another location, i want to click the file press my hotkey and msgbox out its location))
Is there anyway to do this or any direction anyone can point me in?Because i can't find any API which does this...
Thanks!
EDIT:
After reading all the updates and the several links here and there, I started to construct my own function for this, I'm just at the part to determine how many selected icons there are, but i keep getting back 0 icons is there something wrong with what I'm doing?
Public Function getDesktopFiles() As String
Dim vhandle As IntPtr = FindWindow("Progman", "Program Manager")
vhandle = FindWindowEx(vhandle, IntPtr.Zero, "SHELLDLL_DefView", vbNull)
vhandle = FindWindowEx(vhandle, IntPtr.Zero, "SysListView32", "FolderView")
Dim vItemcount As IntPtr
vItemcount = SendMessage(vhandle, LVM_GETSELECTEDCOUNT, 0, 0)
Return vItemcount
End Function
This question has a link to a Raymond Chen blog post which will give you the API calls you require, you will need to convert it to VB but it is based on COM so should be easy. The other answer to that question gives the C# version of Raymond's code...
Edited to add specifics:
1. Include project references to Microsoft Internet Controls (to get the SHDocVw namespace) and Microsoft Shell Controls and Automation (to get the Shell32 namespace)
2. Use SHDocVw.ShellWindows to get an enumeration of open browser windows.
3. Try to cast each item as a ShellBrowserWindow, and then try to cast the Document property as a Shell32.IShellFolderViewDual2 object.
4. The FocusedItem property gives the selected item.
VB.NET code:
Dim windows As New SHDocVw.ShellWindows
For Each window As Object In windows
Dim browser As SHDocVw.ShellBrowserWindow = window
Dim folder As Shell32.IShellFolderViewDual2 = browser.Document
Console.WriteLine(folder.FocusedItem.Path)
Next

Access to path is denied when trying to import from the client's desktop with SSIS

I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.

Opening a file using impersonation

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)
My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.