VB NET Read Remote Registry - vb.net

I'm trying to get the architecture and the operating system of many remote pcs.
In order to do that i'm querying Win32_OperatingSystem and parsing the "Caption" for the O.S. and for the architecture im reading OSArchitecture .
In Windows XP this value does not exists, so i thought that reading the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE
would have done the trick like this code:
Try
Dim co As New ConnectionOptions
co.Impersonation = ImpersonationLevel.Impersonate
co.Authentication = AuthenticationLevel.PacketPrivacy
co.EnablePrivileges = True
co.Username = username
co.Password = password
Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
scope.Connect()
Dim environmentKey, asd2 As Microsoft.Win32.RegistryKey
Dim asd As String
environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine.Text)
asd2 = environmentKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
asd = asd2.GetValue("PROCESSOR_ARCHITECTURE")
Debug.Print("asd: " + asd)
environmentKey.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
My problem is: if im trying this code I get an System.Security.SecurityException: "Accessing remote registry not permitted"
I am, and i know the administrator username and password.
In fact if I run a simple cmdkey /add:targetname /user:username /pass:password
It works.
So why do I have to run a cmdkey /add even if i have alredy specified the username and password in the ConnectionOptions ??
P.S. Sorry for my bad English

This may very well be because remote registry access is not enabled on the target PC.
Even if you know the administrator credentials, remote access to the registry will not work if the feature isn't enabled on the target PC.
To enable it, see the following Microsoft Knowledge Base Article, which covers a variety of Windows Operating Systems: https://support.microsoft.com/en-us/kb/314837

All right, i got it:
Const HKEY_current_user As String = "80000002"
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = ".\administrator"
options.Password = "my_password"
Dim myScope As New ManagementScope("\\" & RemotePCHostname & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_current_user,System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
inParams("sValueName") = "PROCESSOR_ARCHITECTURE"
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
MessageBox.Show(outParams("sValue").ToString())
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If

Related

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

Notes error: Could not open the ID file in lotus notes

Please somebody help me. I use Lotus Notes to send email with using vb.net but I got this error when I try to run. I already add references about interop.lotus.dll and interop.Domino.dll but it's still the same error. Please advice..
Line 115: If dsEmail.Tables(0).Rows.Count > 0 Then
Line 116: **s.Initialize("abcde!")** 'ERROR in THIS LINE
Protected Sub btnSend_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.ServerClick
Dim s As New Domino.NotesSession
Dim db As Domino.NotesDatabase
Dim doc As Domino.NotesDocument
Dim mimeEntity As Domino.NotesMIMEEntity
Dim mimeChild As Domino.NotesMIMEEntity
Dim header As Domino.NotesMIMEHeader
Dim stream As Domino.NotesStream
Dim sendTo As String
Dim connectionString As String = "Data Source=[hide];User ID=[hide];initial Catalog=[hide];Password=[hide]"
Dim objConn As New SqlConnection(connectionString)
objConn.Open()
Dim dsEmail = New DataSet
Dim CommTaskA As SqlCommand
Dim AdapTaskA As SqlDataAdapter
CommTaskA = New SqlCommand("select EMAILBLASTCCID, rtrim(ltrim(EMAILADDR)) EMAILADDR, SUBJECTEMAIL, EMAILTEMPLATE from [hide] where [MESSAGE_TIME] is NULL", objConn)
CommTaskA.CommandTimeout = 180
AdapTaskA = New SqlDataAdapter
AdapTaskA.SelectCommand = CommTaskA
AdapTaskA.Fill(dsEmail)
AdapTaskA.Dispose()
CommTaskA.Dispose()
objConn.Close()
If dsEmail.Tables(0).Rows.Count > 0 Then
s.Initialize("abcde!")
db = s.GetDatabase("[hide]", "[hide].nsf", False)
subjectEmail = dsEmail.Tables(0).Rows(0)(2).ToString
For x As Integer = 0 To dsEmail.Tables(0).Rows.Count - 1
doc = db.CreateDocument()
sendTo = dsEmail.Tables(0).Rows(x)(1).ToString
doc.ReplaceItemValue("SendTo", dsEmail.Tables(0).Rows(x)(1))
doc.ReplaceItemValue("Subject", dsEmail.Tables(0).Rows(x)(2))
mimeEntity = doc.CreateMIMEEntity
mimeChild = mimeEntity.CreateChildEntity
header = mimeEntity.GetNthHeader("Content-Type")
header.SetHeaderVal("multipart/related")
stream = s.CreateStream
stream.WriteText("<img src='" & dsEmail.Tables(0).Rows(x)(3) & "'>")
mimeChild.SetContentFromText(stream, "text/html", Domino.MIME_ENCODING.ENC_NONE)
stream.Close()
doc.Send(False)
objConn.Open()
CommTaskA = New SqlCommand("update [ZITA].[DEV].[EMAILBLASTCC_test] set [MESSAGE_TIME] ='" & DateTime.Now.ToString & "' where rtrim(ltrim(EMAILADDR)) = '" & sendTo & "'", objConn)
CommTaskA.CommandTimeout = 180
CommTaskA.ExecuteNonQuery()
CommTaskA.Dispose()
objConn.Close()
Next
End If
End Sub
Thank you for all your respond.. I found the answer
the problem because the user account Lotus Notes and my IIS Manager are different.
You must make your Lotus Notes IBM and Application Pool Identity in IIS Manager run with the same account.
It works for me. Thank You
Make sure the Windows environment variable PATH points to C:\Users\adventina.nababan\AppData\Local\IBM\Notes\Data\ too.
For further instructions on how to do this, please take a look at the question "Adding directory to PATH Environment Variable in Windows".

check connection sharing network folder using username and password

In my application check network folder connection using following code
Dim myIP As IPHostEntry = Dns.GetHostEntry(txtNetworkDrive.Text.Trim.Split("\", options:=StringSplitOptions.RemoveEmptyEntries)(0))
Dim IPAddress As String = myIP.AddressList.GetValue(0).ToString
Dim xStr As New System.Security.SecureString
For Each c As Char In txtNetworkPassword.Text.Trim
xStr.AppendChar(c)
Next
Dim psi As New ProcessStartInfo()
psi.UserName = txtNetworkusername.text
psi.Password = xStr
psi.Domain = IPAddress
psi.FileName = txtNetworkDrive.Text
psi.UseShellExecute = False
Process.Start(psi)
The Input like
Network drive = "\\Sys4\shareddocs"
Network password= "sys4"
Network Username="user"
IPaddress="198.168.0.24"
But all time it show login failure bad username and password. what am doing wrong?
How get the solutions?

Change IP Address in VB.Net

I am writing a Windows Forms App in VB.Net that will (among other things) change the IP Address, Default Gateway, Subnet Mask, and set the IP Address to Static on an image of Winfows 7 only. Sysprep is not being used. I have searched Google and only come up with 2 options. I don't believe the first solution will work for me because I do not necessarily know the name of the connection. It uses netsh to change IP settings. I was going to give a link to this example but I can't post more than 2 links...
The second solution is shown at this link (the VB.Net version) and the original code is here (the C# version). This solution uses WMI which I really don't know that much about.
When I debug the code and look at everything the code seems to be executing properly but the IP Address is still set to DHCP and all of the other setting are still the same. So, basically, what gives? Why does this code seem to not work?
Here is my code. I only made a few changes:
'Changed the 3 IPs below
Dim IPAddress As String = "192.168.1.105"
Dim SubnetMask As String = "255.255.252.0"
Dim Gateway As String = "192.168.1.100"
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {Gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = New String() {IPAddress}
objNewIP("SubnetMask") = New String() {SubnetMask}
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
'Changed this line so I could see if it was executing all of the way
MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!")
Catch ex As Exception
MessageBox.Show("Unable to Set IP : " & ex.Message)
End Try
Next objMO
I can answer my own question. I thought of it in the shower (how cliche right?). Because this is Windows 7, all I needed to was right-click and run the program as an administrator.

start batch file from within vb.net as admin

In my application, I need to run a batch file as admin for it to function.
I'm using this so far but I cant remember how to use the runas feature which allows it to run with admin rights.
process.start("filelocation.bat")
Any help would be apreciated.
Try
Dim procInfo As New ProcessStartInfo()
procInfo.UseShellExecute = True
procInfo.FileName = (FileLocation)
procInfo.WorkingDirectory = ""
procInfo.Verb = "runas"
Process.Start(procInfo)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
You could try with this code:
Dim proc as ProcessStartInfo = new ProcessStartInfo()
proc.FileName = "runas"
proc.Arguments = "/env /user:Administrator filelocation.bat"
proc.WorkingDirectory = "your_working_dir"
Process.Start(proc)
This code will ask the Administrator password and the start the execution of your batch file
EDIT:
This is an alternative without the cmd window
Dim proc as ProcessStartInfo = new ProcessStartInfo()
proc.FileName = "filelocation.bat"
proc.WorkingDirectory = "your_working_dir" // <- Obbligatory
proc.UseShellExecute = False
proc.Domain = userDomain // Only in AD environments?
proc.UserName = userName
proc.Password = securePassword
Process.Start(proc)
It's a little more complicated because you need to get the input values (userName, Password, domain) before using this code and the password is a SecureString that you need to build in a dedicated way
Dim securePassword as New Security.SecureString()
For Each c As Char In userPassword
securePassword.AppendChar(c)
Next c