Connect to MongoDB server with Driver 2.0 best practice - vb.net

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.

Related

Needs to get default program association on remote computers

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

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 use serial port in a service application environment constantly listening for data

Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,
Application: BondTestService.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException at
System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean
ByRef) at
System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,
Boolean ByRef) at
Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,
System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at
System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at
System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at
System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?
I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?
Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.
Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration
Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10
#Region "Commport Traffic and Configuration Validations"
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
End If
Try
With serialPort
.PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
.BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
.Parity = Parity.None
End If
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
.StopBits = StopBits.One
End If
.DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
.Handshake = Handshake.None
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
.RtsEnable = True
Else
.RtsEnable = False
End If
End With
serialPort.Open()
'debug
'ErrorLog2("Listening to COM 19, SerialPort has been Opened")
Catch ex As Exception
ErrorLog2(Now.ToString & ex.tostring)
End Try
End Sub
Public Function Filelocator() As String
' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
'Dim reader As New System.IO.StreamReader(filePath)
Dim LineNumber = 4
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To LineNumber - 1
If file.ReadLine() Is Nothing Then
ErrorLog2("LineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
ErrorLog2("LineNumber")
End If
Return line
End Using
End Function
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Try
If GetBondInterfaceStatus = 1 Then
UPdateVariable()
Else
exit Sub
End If
Catch ex As Exception
Errorlog2(Ex.Tostring)
End Try
End Sub
#End Region
#Region "String Handling"
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
try
ErrorLog2(now.ToString & RawString.ToString)
InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
RawString.Clear()
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Public Function StringParser(RawString As String)As Double ()
Dim Moisture = RawString
Dim pattern As String = "[0-9],"
Dim regex As New Regex(pattern)
Dim Counter As Integer = 0
Dim dblValues(1) As Double
Dim values As String() = Moisture.Split(New Char() {" "c})
for i = 0 to values.Count - 1
if regex.IsMatch(values(i)) Then
dblValues(Counter) = CDbl(values(i).Substring(0,1))
Counter = Counter + 1
Elseif values(i) = "" Then
continue for
else
if Double.TryParse(values(i), dblValues(Counter)) Then
Counter = Counter + 1
End If
End If
Next
Return dblValues
End Function
#End Region
#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime)"
Try
conn.ExecuteNonQuery(InsertQuery)
IncrementTestPosition
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#RawString") = rawString
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime, #RawString)"
Try
conn.ExecuteNonQuery(InsertQuery)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub IncrementTestPosition()
Dim tempPosition As Integer = GetBondPosition()
Dim FrontOriginalMax = 5
Dim CenterOriginalMax = 15
Dim BackOriginalMax = 25
Dim FrontRetestOrWinderMax = 10
Dim CenterRetestOrWinderMax = 20
Dim BackRetestOrWinderMax = 30
If tempPosition = FrontOriginalMax Then
tempPosition = 11
else if tempPosition = CenterOriginalMax Then
tempPosition = 21
else if tempPosition = BackOriginalMax Then
tempPosition = 1
Else If tempPosition = FrontRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = CenterRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = BackRetestOrWinderMax then
tempPosition = 1
else
tempPosition = tempPosition + 1
End If
SetBondPosition(tempPosition.tostring)
End Sub
#End Region
#Region "Get PiValues"
Private Function GetRecordID() As Int64
Dim RecordID As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return RecordID
End Function
Private Function GetBondPosition() As Int64
Dim BondPos As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return BondPos
End Function
Private Sub SetBondPosition(pos As String)
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Function BondTestType() As String
Dim TestType As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return TestType
End Function
Private Function BondReelLoc() As String
Dim ReelLoc As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return ReelLoc
End Function
Private Function GetBondInterfaceStatus() As Integer
Dim Status As Integer = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return Status
End Function
#End Region
#Region "Debug"
Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
' For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
' Next
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
'For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
'Next
End Using
End If
End Sub
Private Sub ErrorLog2(dataArray as string)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
' Dim TestPos = StartingTestPos
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
End If
End Sub
#End Region
This is a screenshot of the errors:
Thanks in advance
Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.
According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.
Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.
This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.
The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.
Also check your power management settings on your USB port if USB-to-RS232 converter is used. Try to uncheck this option on USB device to which converter is connected.
SW bug in your code.
It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.
Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class
Shared Dim WithEvents serialPort as IO.Ports.SerialPort
and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.

Mongodb Driver 2.0 find() in VB.net not working

I am trying to practice with the C# Driver 2.0 for MongoDB. I don't know C# so I am writing the code in Visual Basic.
When I try to print out a list code won't compile. I know I have the For Each contents commented out but that's not the problem. I want to query the db for all documents in a collection and print them out to a text box.
Below is the code that isn't working. The last part is giving me trouble.
Private Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
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 query As BsonDocument
query = New BsonDocument("Names", txtListUsers.Text)
For Each item As BsonDocument In vCol.Find(query).ToListAsync()
'print a count
'print bson document
Next
End Sub
Any help is appreciated. I have been banging my head against the keyboard for hours.
BELOW IS THE CODE THAT WORKED FOR ME AFTER ALEX GAVE ME AN ANSWER:
Private Async Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
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 query As BsonDocument
query = New BsonDocument("Name", txtListUsers.Text)
Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()
Dim i As Integer = 0
For Each vItem As BsonDocument In myList
'count
i += 1
'print bson document
rtfDataDisplay.Text = rtfDataDisplay.Text & vbCrLf & "#" & i.ToString & " - " & vItem.ToString & vbCrLf
Next
End Sub
I had to add Async to the sub. I also had my key "Name" incorrect. After that things went smoothly. Woo Hoo!
Your problem is in this line:
For Each item As BsonDocument In vCol.Find(query).ToListAsync()
The call to the ToListAsync() method returns an awaitable Task(Of List(Of BsonDocument)), i.e. a promise that it will return a list that you can enumerate when it has completed fetching it. You need to Await it, to get to the list. As in:
Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()
For Each item As BsonDocument in myList
'print a count
'print bson document
Next
An alternative construct offered by the MongoDB driver, is to use its ForEachAsync method, and supply it with a lambda delegate argument.

Poll a directory looking for files with a certain extension

I'm writing a script to look in a directory, read the file name and use a part of the file name to run a SQL query to amend a DB, then copy the files to a new location and delete the original.
Once this is done it sends an email confirmation to a predefined email address.
I have the majority in place but am not able to Poll a Dir and process all files that may be there. Im new to this VB.net stuff and to get the other stuff working iv just named it at the beginning.
Any help would be greatly appreciated.
Dim fileName As String = "C:\temp\Input\VBTEST1.success"
Dim pathname As String = "C:\temp\Input\"
Dim result As String
Dim sourceDir As String = "C:\temp\Input\"
Dim processedDir As String = "C:\temp\Input\Processed\"
Dim fList As String() = Directory.GetFiles(sourceDir, "*.success")
Dim sqlCommand As SqlCommand
Public Sub Main()
result = Path.GetFileName(fileName)
Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result)
Dim betacell As String = result
betacell = (result.Remove(7, 8))
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
sqlCommand.ExecuteNonQuery()
updateTransaction.Commit()
connection.Close()
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
Call MoveFiles()
End Sub
I'm all chuffed now as iv also managed to make it look for all files with a .success extension. Now it processes all files and not the one named in the code.
Module Module1
Dim sourceDir As String = My.Settings.watchPath
Dim processedDir As String = My.Settings.processedPath
Private loggerName As String = "EmailReleases"
Public Sub log(ex As Exception)
Console.WriteLine("Error: " & ex.ToString)
End Sub
Public Sub log(ByVal s As String)
Console.WriteLine(DateTime.Now.ToString & " [" & loggerName & "] " & s)
End Sub
Public Sub Main()
Dim inputFiles As String() = Directory.GetFiles(sourceDir, "*.success")
log("Starting processing of .success files in '" & sourceDir & "' ... ")
If (inputFiles.Length > 0) Then
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
For Each fileName As String In inputFiles
Dim sqlCommand As SqlCommand
Dim fFile As New FileInfo(fileName)
log(" Processing " & fFile.Name)
Dim betacell As String = fFile.Name.Substring(0, fFile.Name.Length - 8)
'Update Status on Database with the use of the Betacell
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
Dim result = sqlCommand.ExecuteNonQuery()
'Email COnfirmation
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
If (result > 0) Then
'Move the file
fFile.MoveTo(processedDir & fFile.Name)
updateTransaction.Commit() ' make sure to commit only in case moving the file is OK
Else
log("ERROR - Betacell '" & betacell & "' not found in database!")
updateTransaction.Rollback()
End If
Rather than polling a folder (i.e. checking every n seconds whether it has new files) it's much more efficient to have the operating system notify you of changes in that folder. You can do this by creating a FileSystemWatcher. There is an example on MSDN.
However, if you did want to poll a folder, it's actually nice and easy - just wrap the following code in a Timer. Please note I normally code in C#, so apologies if the syntax is not 100%...
Imports System.IO
....
For Each file as String in Directory.GetFiles("C:\SomeFolder")
DoSomethingWithFile (file)
Next