Needs to get default program association on remote computers - vb.net

I am using the below code to get some information on remote computers. Basically, I need to get the OS version (which is working well) and the default program for .pdf files and the default browser. I can get the OS version but the code fails to get the default program association. The Remote Registry is enabled and started but even though I am getting an "access is denied" error message. Any clue guys? Hope you could help me. Thanks
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Const HKEY_LOCAL_MACHINE As String = "80000002"
Const HKEY_current_user1 As String = "80000001"
'Dim remoteRegistryController As New System.ServiceProcess.ServiceController("RemoteRegistry", computerNameTB.Text)
'remoteRegistryController.Start()
Dim osName, pdf, browser As String
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = "hd_juann"
options.Password = "Diosteamo42="
Dim myScope As New ManagementScope("\\" & computerNameTB.Text & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Try
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_LOCAL_MACHINE, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "Software\Microsoft\Windows NT\currentVersion"
inParams("sValueName") = "ProductName"
'Dim osName As String
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
'MessageBox.Show(outParams("sValue").ToString())
osName = outParams("sValue").ToString()
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If
'get pdf
Dim inParamsPDF As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsPDF("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsPDF("sSubKeyName") = "Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.pdf\UserChoice"
inParamsPDF("sValueName") = "ProgId"
'Dim pdf As String
Dim outParamsPDF As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsPDF, Nothing)
If (outParamsPDF("ReturnValue").ToString() = "0") Then
pdf = outParamsPDF("sValue").ToString()
Else
pdf = "No value Set"
End If
'MessageBox.Show(pdf)
'remoteRegistryController.Stop()
'get browser
Dim inParamsBrowser As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsBrowser("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsBrowser("sSubKeyName") = "SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations\https\UserChoice"
inParamsBrowser("sValueName") = "ProgId"
'Dim browser As String
Dim outParamsBrowser As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsBrowser, Nothing)
If (outParamsBrowser("ReturnValue").ToString() = "0") Then
browser = outParamsBrowser("sValue").ToString()
Else
browser = "No value Set"
End If
MsgBox(osName & " is installed on computer " & computerNameTB.Text & vbCrLf & "PDF Default App: " & pdf & vbCrLf & "Default Browser: " & browser,, "ComputerInfo W10 Upgrade Project")
Catch err As Exception
If osName <> "" Then
MsgBox(osName & " is installed on computer: " & computerNameTB.Text & ". No default program association information could be accessed " & err.Message,, "ComputerInfo W10 Upgrade Project")
Else
MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End If
'MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End Try
End Sub
eoor

Related

UWP epPlus - choose directory to save

I am making an application in vb using UWP and epPlus along with it to save the current database to an excel file. I would create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. There isn't a "Savefiledialog" in UWP... Ideas?
UPDATE
I tried to use FileSavePicker: if I save it in the principal directory (C:\, Desktop, Documents ...) epPlus doesn't work, but if I save it in another directory (D:\, USB...) it workes... How can I save it in the principal directory?
I post my code here:
Private Async Sub ButtonXls_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
OutputTextBlock.Text = ""
Dim savePicker As FileSavePicker = New FileSavePicker()
savePicker.SuggestedStartLocation = PickerLocationId.Desktop
savePicker.FileTypeChoices.Add("Microsoft Excel", New List(Of String)() From {
".xlsx"
})
savePicker.SuggestedFileName = "Riepilogo_Test"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync()
If file IsNot Nothing Then
CachedFileManager.DeferUpdates(file)
Dim ExcelPkg As ExcelPackage = New ExcelPackage()
Dim wsSheet1 As ExcelWorksheet = ExcelPkg.Workbook.Worksheets.Add("Sheet1")
Using Rng As ExcelRange = wsSheet1.Cells(2, 2, 2, 2)
Rng.Value = "Text file on Excel here"
Rng.Style.Font.Size = 16
Rng.Style.Font.Bold = True
Rng.Style.Font.Italic = True
End Using
wsSheet1.Protection.IsProtected = False
wsSheet1.Protection.AllowSelectLockedCells = False
Dim filePath As FileInfo = New FileInfo(file.Path)
ExcelPkg.SaveAs(filePath)
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
If status = FileUpdateStatus.Complete Then
OutputTextBlock.Text = "File " & file.Name & " was saved."
ElseIf status = FileUpdateStatus.CompleteAndRenamed Then
OutputTextBlock.Text = "File " & file.Name & " was renamed and saved."
Else
OutputTextBlock.Text = "File " & file.Name & " couldn't be saved."
End If
Else
OutputTextBlock.Text = "Operation cancelled."
End If
End Sub

Downloading files code gets unexpected 404 error

My code downloads files in loop but after the last file downloads it keeps downloading files that aren't there. Website shows redirect and 404 error.
I'm new with visual basic so I'm asking for help here.
My.Computer.Network.DownloadFile(strFullUrlDownload, strFullSavePath, False, 1000)
404 error
redirect
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strMainUrl As String = "http://jixxer.com/123/"
Dim dt As DateTime = DateTime.Now
Dim dtDate As String = dt.ToString("yyyy-MM-dd")
Dim strSlash As String = "/"
Dim strPdf As String = "pdf"
Dim strDot As String = "."
Dim strPage As String = "page"
Dim strPageNbr As String = 1
Dim intCounter As Integer = 1
Dim strPageCounter As String = String.Format("{0:000}", intCounter)
Dim strSavePath As String = "D:\dls\title1\"
Dim strFullSavePath As String = strSavePath & strPageCounter & strDot & strPdf
Dim strFullUrlDownload As String = strMainUrl & dtDate & strSlash & strPdf & strSlash & strPage & strPageNbr & strDot & strPdf
Do Until strPageCounter = 200
' Downloads the resource with the specified URI to a local file.
My.Computer.Network.DownloadFile(strFullUrlDownload, strFullSavePath, False, 1000)
intCounter = intCounter + 1
strPageNbr = strPageNbr + 1
strPageCounter = String.Format("{0:000}", intCounter)
strFullSavePath = strSavePath & strPageCounter & strDot & strPdf
strFullUrlDownload = strMainUrl & dtDate & strSlash & strPdf & strSlash & strPage & strPageNbr & strDot & strPdf
Loop
End Sub
End Class
Try
'TRY to download the file using https first...
My.Computer.Network.DownloadFile(New Uri("https://" & ServerAddress & WebLogoPath & Convert.ToString(RowArray(0)) & ".png"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\" & AppDataFolder & PCLogoPath & Convert.ToString(RowArray(0)) & ".png", "", "", False, 500, True)
Catch ex_https As Exception
'Unable to locate file or write file
'If the operation timed out...
If (ex_https.Message = "The operation has timed out") Then
'Re-TRY to download the file using http instead, as a time out error may indicate that HTTPS is not supported.
Try
My.Computer.Network.DownloadFile(New Uri("http://" & ServerAddress & WebLogoPath & Convert.ToString(RowArray(0)) & ".png"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\" & AppDataFolder & PCLogoPath & Convert.ToString(RowArray(0)) & ".png", "", "", False, 500, True)
Catch ex_http As Exception
'Most likely, the file doesn't exist on the server. Either way, we cannot obtain the file so we need to perform the same action,
'which is handled outside of this Try block.
End Try
Else
'This is most likely a 404 error. Either way, we cannot obtain the file (and the connection is not timing out) - so
'we need to perform the same action, which is handled outside of this Try block.
End If
End Try
I just put the counter at 200 to test and make sure it works. But I know I need a way to quit on error but not sure how to code it yet. Appreciate any help.
If you don't know how many documents are stored in that remote directory, you have to handle the exception when a page is not found.
It's always possible to receive WebExceptions when a resource is requested from a site, so you should handle this case anyway.
I suggest to use the WebClient class directly instead of Network.DownloadFile(), which may be handy if you want to show a predefined UI of the progress (when it's possible), but using WebClient directly, lets you perform the download asynchrounously if you need it to, using the async/await pattern and the WebClient.DownloadFileTaskAsync() method.
Another suggestion: use a method to download those files, so you can call it from anywhere in your code. You can use a class or a module to store your methods, so you don't clutter your UI and you can also easily reuse these classes or modules in different projects, just including in a project the file that contains them.
Your code could be modified as follow (synchronous version):
You need to pass to the DownloadPdfPages method the remote base address: http://jixxer.com/123, the Path where the files are store (filesPath).
The third and fourth parameters are optional:
- If you don't specify a resourceName, Date.Now.ToString("yyyy-MM-dd") is assumed,
- If you don't specify a startPage, it will default to 1, converted in page1.pdf (the example here asks to start from page 3).
Note: I'm using String Interpolation here: $"page{startPage + pageCount}.pdf".
If your VB.Net version doesn't support it, use String.Format() instead.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfPages = DownloadPdfPages("http://jixxer.com/123", "D:\dls\title1", "", 3)
If numberOfPages > 0 Then
MessageBox.Show($"Download completed. Number of pages: {numberOfPages}")
Else
MessageBox.Show("Download failed")
End If
End Sub
Private Function DownloadPdfPages(baseAddress As String, filesPath As String, Optional resourceName As String = "", Optional startPage As Integer = 1) As Integer
If String.IsNullOrEmpty(resourceName) Then resourceName = Date.Now.ToString("yyyy-MM-dd")
Dim resourceAddr = Path.Combine(baseAddress, resourceName, "pdf")
Dim pageCount = 0
Dim client = New WebClient()
Try
Do
Dim documentName = $"page{startPage + pageCount}.pdf"
Dim resourceUri = New Uri(Path.Combine(resourceAddr, documentName), UriKind.Absolute)
Dim fileName = Path.Combine(filesPath, documentName)
client.DownloadFile(resourceUri, fileName)
pageCount += 1
Loop
Catch ex As WebException
If ex.Response IsNot Nothing Then
Dim statusCode = DirectCast(ex.Response, HttpWebResponse).StatusCode
If statusCode = HttpStatusCode.NotFound Then
Return pageCount
End If
ElseIf ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Message.Contains("404") Then
Return pageCount
Else
' Log and/or ...
Throw
End If
Return 0
Finally
client.Dispose()
End Try
End Function
Asynchronous version, using the WebClient.DownloadFileTaskAsync() method.
Just a few changes ae necessary, note the Async keyword added to both the Button.Click handler and the DownloadPdfPagesAsync() method.
The Await keyword is then used to wait for a method to complete, without blocking the UI:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfPages = Await DownloadPdfPagesAsync("http://jixxer.com/123", "D:\dls\title1", "", 3)
If numberOfPages > 0 Then
MessageBox.Show($"Download completed. Number of pages: {numberOfPages}")
Else
MessageBox.Show("Download failed")
End If
End Sub
Private Async Function DownloadPdfPagesAsync(baseAddress As String, filesPath As String, Optional resourceName As String = "", Optional startPage As Integer = 1) As Task(Of Integer)
If String.IsNullOrEmpty(resourceName) Then resourceName = Date.Now.ToString("yyyy-MM-dd")
Dim resourceAddr = Path.Combine(baseAddress, resourceName, "pdf")
Dim pageCount = 0
Dim client = New WebClient()
Try
Do
Dim documentName = $"page{startPage + pageCount}.pdf"
Dim resourceUri = New Uri(Path.Combine(resourceAddr, documentName), UriKind.Absolute)
Dim fileName = Path.Combine(filesPath, documentName)
Await client.DownloadFileTaskAsync(resourceUri, fileName)
pageCount += 1
Loop
Catch ex As WebException
If ex.Response IsNot Nothing Then
Dim statusCode = DirectCast(ex.Response, HttpWebResponse).StatusCode
If statusCode = HttpStatusCode.NotFound Then
Return pageCount
End If
ElseIf ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Message.Contains("404") Then
Return pageCount
Else
' Log and/or ...
Throw
End If
Return 0
Finally
client.Dispose()
End Try
End Function

How to Calculate estimated time remaining in downloading Using Xceed.Ftp.FtpClient() in VB.net?

I am downloading FTP files using Xceed.Ftp.FtpClient() how can i calculated the estimated remaining Time?
Dim HostName As String = (New Uri(RemoteFilePath).Host).ToString()
Dim RemoteFolderName As String = System.IO.Path.GetFileName((New Uri(RemoteFilePath).LocalPath).ToString())
Dim RemoteFileName As String = System.IO.Path.GetFileName((New Uri(RemoteFilePath).LocalPath).ToString())
Dim LocalFileName As String = System.IO.Path.GetFileName((New Uri(LocalFilePath).LocalPath).ToString())
Dim Ftp As New Xceed.Ftp.FtpClient()
Dim AuthMethod As AuthenticationMethod = AuthenticationMethod.Tls
Dim VeriFlag As VerificationFlags = VerificationFlags.None
Dim Cert As Certificate = Nothing
Ftp.Connect(HostName, 990, AuthMethod, VeriFlag, Cert)
'Console.WriteLine("Connected")
Ftp.Login(username, pass)
Dim s As String = Ftp.GetCurrentFolder()
'Console.WriteLine("LogedIn")
Ftp.ChangeCurrentFolder("WindowsPatches/" & RemoteFolderName)
'Console.WriteLine("Remote Folder Name:" & RemoteFolderName)
'Ftp.ChangeCurrentFolder(RemoteFolderName)
Dim files = Ftp.GetFolderContents()
If files IsNot Nothing AndAlso files.Count >= 0 Then
For index = 0 To files.Count - 1
If files.Item(index).Type = FtpItemType.File Then
RemoteFileName = files.Item(index).Name
LocalFileName = RemoteFileName
If Not Directory.Exists(RemoteFolderName) Then
Directory.CreateDirectory(RemoteFolderName)
End If
LocalFileName = RemoteFolderName & "\" & LocalFileName
If Not String.IsNullOrEmpty(LocalFilePath) AndAlso System.IO.File.Exists(LocalFilePath) Then
System.IO.File.Delete(LocalFilePath)
End If
'Console.WriteLine("Downloading started...")
Ftp.ReceiveFile(RemoteFileName, LocalFileName)
'Console.WriteLine("Downloading Complete")
'Console.WriteLine("Working Path" & Directory.GetCurrentDirectory())
Dim psi As New ProcessStartInfo()
Directory.SetCurrentDirectory(LocalFilePath & RemoteFolderName)
'Console.WriteLine("Local Directory Name: " & LocalFilePath & RemoteFolderName)
psi.CreateNoWindow = True
psi.FileName = RemoteFileName
psi.UseShellExecute = True
Dim myProcess As Process = Process.Start(psi)
Console.WriteLine("Update process started...")
'Exit For
End If
Next
'LocalFileName = RemoteFileName
End If
I am using this code, any suggestion please?

Connect to MongoDB server with Driver 2.0 best practice

I have VB.net code that connects to a MongoDB. When the database is up and running my code works fine, but when the database is not running I don't get any errors back.
How do I check that the Server is up and running so I can connect to it and do my work? Basically IF the Server is up do work ELSE return a message to user that server is not available.
I look at the documentation about the MongoClient Class but I can't seem to find anything I can use.
MongoClient Class (http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_MongoClient.htm)
Below is my code that works to connect to the MongoDB:
Public Function DbConnection(ByRef ConnString As String, vDbName As String, vColName As String) As MongoClient
'default port
'ConnString = "mongodb://localhost:27017"
'example DB and Collection
'vDbName = "blog"
'vColName = "users"
'Root Object
Dim vClient As MongoClient
vClient = New MongoClient(ConnString)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Return vClient
End Function
Below is additional code where I use InsertOneAsync without creating an error:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtName.Text = "" Then
MsgBox("Enter a Name for the Database.")
Else
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
'Root Object
Dim vClient As MongoClient
vClient = DbConnection(ConnString, vDbName, vColName)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Dim vAddUser As BsonDocument
vAddUser = New BsonDocument
vAddUser.Add("_Id", txtID.Text)
vAddUser.Add("Name ", txtName.Text)
vAddUser.Add("Email", txtEmail.Text)
vAddUser.Add("City", txtCity.Text)
rtfDataDisplay.Text = "BsonDocument = " & vAddUser.ToString & ", #" & vAddUser.Count
Await vCol.InsertOneAsync(vAddUser)
End If
End Sub
Below is the solution I came up with. I am only posting the Try...Catch since I have already posted entire procedures above.
Try
Dim watch As Stopwatch = New Stopwatch
watch.Start()
Dim insertResult As Task = vCol.InsertOneAsync(vAddUser)
Await insertResult
watch.Stop()
MsgBox("Faulted =" & insertResult.IsFaulted.ToString & ", Status = " & insertResult.Status.ToString & ", Watch = " & watch.Elapsed.ToString)
Catch ex As Exception
If ex.HResult.ToString = "-2146233083" Then
MsgBox("unable to insert data due to a timeout exception")
Else
MsgBox("Unable to insert data = " & ", HResult = " & ex.HResult.ToString & "!" & ex.ToString)
End If
End Try
Since the asynch only returns Task, it doesn't wait until the operation is complete. If you wait after the task and then you will capture the exception and process it accordingly, Here is the sample
Change this
Await vCol.InsertOneAsync(vAddUser)
Var insertTask = vCol.InsertOneAsync(vAddUser); insertTask.Wait();
and then remove the async keyword from the button_click method signature.

0x80004002 exception with wia and vb.net

Hope someone can help with the above error.
I have the following code that worked fine with windows xp and a Kodak scanmate 1120
Private Sub BtnScan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnScan.Click
Dim img As WIA.ImageFile = Nothing
Dim wiaDialog As WIA.CommonDialog = New WIA.CommonDialog
Dim wiaScanner As WIA.Device
Dim root As String = "c:\myimages"
Dim IFileName As String = TxtInvoiceNo.Text
Dim WiaCommonDialog As New WIA.CommonDialog
If TxtInvoiceNo.Text = "" Then
'FrmPicDisplay.Show()
MsgBox("Please enter a valid Invoice No." & vbNewLine _
& "Then press scan button to continue.")
TxtInvoiceNo.Select()
ElseIf My.Computer.FileSystem.FileExists(root & IFileName & ".bmp") Then
MsgBox("This filename already exists," & vbNewLine _
& "Please enter a different filename")
TxtInvoiceNo.Text = ""
Else
Ino = TxtInvoiceNo.Text
wiaScanner = wiaDialog.ShowSelectDevice
With wiaScanner.Items(1)
.Properties("6146").Value = 4 '4 is Black-white,gray is 2, color 1 (Color Intent)
.Properties("6147").Value = 200 'dots per inch/horizontal
.Properties("6148").Value = 200 'dots per inch/vertical
.Transfer(wiaFormatTIFF) '("{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}") 'BMP format - This prompts the scan
End With
img = wiaScanner
Dim Item As WIA.Item = TryCast(wiaScanner.Items(1), WIA.Item)
Dim imageBytes As [Byte]() = DirectCast(img.FileData.BinaryData, Byte())
Dim ms As New MemoryStream(imageBytes)
Dim image_1 As Image = Image.FromStream(ms)
img.SaveFile("c:\myimages" & TxtInvoiceNo.Text & ".bmp")
I had to change the pc to windows seven and now the program doesn't work and gives me the above error at the line
img = wiaScanner
From what I have found by searching it sounds like a com exception but I don't really understand where to start looking so any help would be very much appreciated.
Thanks
Gareth