parallel.foreach is hanging my application - vb.net

I have a List(of MyCustomObject). This List is the DataSource for TreeView.
Now, all of collected objects must be updated on periodicaly Rising Timer1_Timer event. To update I'm using Parallel.ForEach. This works fine in test app, but final application hangs after adding code for calculations, and random number of relults may absent. Please help to fix it.
Imports System.Threading.Tasks
Imports Telerik.WinControls.UI
Imports System.ComponentModel
Imports System.Threading
Imports Accessibility
Public Class Form1
Dim WithEvents bw As New BackgroundWorker
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
Upadte(rt.Nodes.Cast(Of RadTreeNode)())
End Sub
Private Shared Sub Upadte(Of T)(source As IEnumerable(Of T))
Parallel.ForEach(source, New ParallelOptions With {.TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext, .MaxDegreeOfParallelism = 5}, AddressOf zUpdate)
End Sub
' Following fragment is a simple example. Real code is more difficult. It includes Network requests, WQL queries e.t.c.
' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Private Shared Sub zUpdate(Of T)(node As T)
Dim item = TryCast(node, RadTreeNode)
If item Is Nothing Then
Return
End If
Dim n_node As New RadTreeNode("_" & item.Name)
n_node.Nodes.Add("Hardware")
Dim tf As Form = Control.FromHandle(Form1.Handle)
tf.BeginInvoke(New Action(Function() InlineAssignHelper(item, n_node)))
End Sub
' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Private Shared Function InlineAssignHelper(ByRef target As RadTreeNode, ByVal value As RadTreeNode) As RadTreeNode
target.Nodes.Add(value.Clone)
Return target
End Function
End Class
Greate idea! I'll check it. By the way, there's no any secret in full code. It's just much more than 1st example. Here is the copy of complete sub zUpdate without some typical queries, which working fine in STA:
Private Shared Sub zUpdate(Of T)(anode As T)
Dim searcher As New ManagementObjectSearcher
Dim tt_node As RadTreeNode = TryCast(anode, RadTreeNode)
If tt_node Is Nothing Then
Return
End If
Dim t_node As String = tt_node.Name
Dim n_node As New RadTreeNode With {.Name = "_" & t_node, .Text = "_" & t_node}
Dim opt As New ConnectionOptions
opt.Authentication = AuthenticationLevel.PacketPrivacy
opt.EnablePrivileges = True
opt.Impersonation = ImpersonationLevel.Impersonate
opt.Username = CredentialCache.DefaultNetworkCredentials.UserName
opt.Password = CredentialCache.DefaultNetworkCredentials.Password
opt.Authority = "ntlmdomain:" & CredentialCache.DefaultNetworkCredentials.Domain
Dim scope As New ManagementScope("\\" & t_node & "\ROOT\CIMV2", opt)
Dim query As New ObjectQuery
If My.Computer.Network.Ping(t_node, 10) = False Then
Return
GoTo 1
End If
scope.Connect()
If Not scope.IsConnected Then
Return
GoTo 1
End If
'Summary
query.QueryString = "SELECT * FROM Win32_ComputerSystem"
searcher.Scope = scope
searcher.Query = query
n_node.Nodes.Add("Summary")
For Each queryobj As ManagementObject In searcher.Get
With n_node.Nodes("Summary")
.Nodes.Add("Name", "Name:" & queryobj("Name"), 6)
.Nodes.Add("Domain", "Domain:" & queryobj("Domain"), 6)
.Nodes.Add("Manufacturer", "Manufacturer:" & queryobj("Manufacturer"), 6)
.Nodes.Add("Model", "Model:" & queryobj("Model"), 6)
.Nodes.Add("NumberOfLogicalProcessors", "NumberOfLogicalProcessors:" & queryobj("NumberOfLogicalProcessors").ToString, 6)
.Nodes.Add("NumberOfProcessors", "NumberOfProcessors:" & queryobj("NumberOfProcessors").ToString, 6)
.Nodes.Add("TotalPhysicalMemory", "TotalPhysicalMemory:" & queryobj("TotalPhysicalMemory").ToString, 6)
.Nodes.Add("UserName", "UserName:" & queryobj("UserName"), 6)
.Nodes.Add("Workgroup", "Workgroup:" & queryobj("Workgroup"), 6)
End With
Next
'LogicalDisk
query.QueryString = "SELECT * FROM Win32_LogicalDisk"
searcher.Query = query
n_node.Nodes.Add("Hardware")
With n_node.Nodes("Hardware")
.Nodes.Add("LogicalDisks")
With .Nodes("LogicalDisks")
For Each queryobj As ManagementObject In searcher.Get
.Nodes.Add("Name", "Name" & ": " & queryobj("Name"), 6)
With .Nodes("Name")
.Nodes.Add("Description", "Description: " & queryobj("Description"), 6)
.Nodes.Add("DriveType", "DriveType: " & queryobj("DriveType"), 6)
.Nodes.Add("Size", "Size: " & queryobj("Size").ToString, 6)
.Nodes.Add("FreeSpace", "FreeSpace: " & queryobj("FreeSpace"), 6)
.Nodes.Add("VolumeName", "VolumeName: " & queryobj("VolumeName"), 6)
.Nodes.Add("VolumeSerialNumber", "VolumeSerialNumber: " & queryobj("VolumeSerialNumber"), 6)
End With
Next
End With
'network adapters
query.QueryString = "SELECT * FROM Win32_NetworkAdapterConfiguration"
searcher.Query = query
.Nodes.Add("NetworkAdapters")
With .Nodes("NetworkAdapters")
For Each queryobj As ManagementObject In searcher.Get
.Nodes.Add(CStr(queryobj("Description")))
With .Nodes(CStr(queryobj("Description")))
.Nodes.Add("DHCPServer", "DHCPServer: " & queryobj("DHCPServer"), 6)
.Nodes.Add("DNSDomain", "DNSDomain: " & queryobj("DNSDomain"), 6)
.Nodes.Add("DNSHostName", "DNSHostName: " & queryobj("DNSHostName"), 6)
.Nodes.Add("MACAddress", "MACAddress: " & queryobj("MACAddress"), 6)
.Nodes.Add("SettingID", "SettingID: " & queryobj("SettingID"), 6)
End With
Next
End With
End With
'software
query.QueryString = "SELECT * FROM Win32_Product"
searcher.Query = query
n_node.Nodes.Add("Software")
With n_node.Nodes("Software")
For Each queryobj As ManagementObject In searcher.Get
.Nodes.Add(queryobj("Name"))
With .Nodes(queryobj("Name"))
.Nodes.Add("InstallDate", "InstallDate: " & queryobj("InstallDate"), 6)
.Nodes.Add("IdentifyingNumber", "IdentifyingNumber: " & queryobj("IdentifyingNumber"), 6)
End With
Next
End With
Dim tf As Form = Control.FromHandle(Form2.Handle)
tf.BeginInvoke(New Action(Function() InlineAssignHelper(tt_node, n_node)))
1:
If Not searcher Is Nothing Then
searcher.Dispose()
scope = Nothing
End If
End Sub
Private Shared Function InlineAssignHelper(ByRef target As RadTreeNode, ByVal value1 As RadTreeNode) As RadTreeNode
Dim t_str As String = Now.Date.ToString & Now.TimeOfDay.ToString
target.Nodes.Add(t_str)
target.Nodes(t_str).Nodes.Add(value1.Clone)
Return target
End Function

This works fine in test app, but final application hangs after adding
code for calculations, and random number of results may absent.
I suspect this means that your problem may lay in the code that you are not showing us.
The most likely candidate is that the code in your real zupdate method is accessing some sort of shared resource that is deadlocking.

Related

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.

For-loop doesn't complete all iterations

I have problem with this - I try to send broadcast SMS using AT Commands in my system. After that the SMS content will be stored in my database. My store content SMS function works well. I can store all my SMS content that I send, but the send function just sends message to my first data on my datagridview.
Please help me to deal with this - I posted my code below
Private Sub ButtonKirim_Click(sender As Object, e As EventArgs) Handles ButtonKirim.Click
Dim noPel As String
Dim isiPesan As String = ""
Dim tgl As Date = Now.Date
Dim strReplace(2) As String
Dim strIsi(2) As String
Dim tagBulan As String = "<bulan>"
Dim tagtagihan As String = "<tagihan>"
Dim tagLokasi As String = "<lokasi>"
Dim pesanKirim As String = ""
My.Settings.SettingPesan = RichTextBoxPesan.Text
My.Settings.Save()
'Label4.Text = isiPesan
For pelanggan As Integer = 0 To DataGridViewKirimPesan.RowCount - 1
'mengirim pesan/send message
noPel = DataGridViewKirimPesan.Rows(pelanggan).Cells(3).Value()
strReplace(0) = tagBulan
strReplace(1) = tagtagihan
strReplace(2) = tagLokasi
strIsi(0) = DataGridViewKirimPesan.Rows(pelanggan).Cells(4).Value
strIsi(1) = DataGridViewKirimPesan.Rows(pelanggan).Cells(5).Value
strIsi(2) = DataGridViewKirimPesan.Rows(pelanggan).Cells(6).Value
isiPesan = RichTextBoxPesan.Text
For i As Integer = LBound(strReplace) To UBound(strReplace)
isiPesan = isiPesan.Replace(strReplace(i), strIsi(i))
Next
SendMessage(noPel, isiPesan)
''menyimpan pesan keluar ke sms_terkirim/this query store my content SMS to table
Dim sqlSmsKeluar As String = "INSERT INTO sms_terkirim (`tgl_sms`,`id_pelanggan`, `isi_sms`) VALUES ( NOW()," & DataGridViewKirimPesan.Rows(pelanggan).Cells(0).Value & " , '" & isiPesan & "');"
cudMethod(sqlSmsKeluar)
MsgBox(sqlSmsKeluar)
'ProgressBarKirimPesan.Increment(1)
Next
'MsgBox("Pesan Sukses Terkirim")
' Catch ex As Exception
' MsgBox("Pesan Gagal Terkirim" + ex.Message)
'End Try
' End If
End Sub
and this code is AT Command to send message
Public Sub SendMessage(ByVal NomorPelanggan As String, ByVal IsiPesan As String)
If SerialModem.IsOpen() Then
With SerialModem
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGS=" & Chr(34) & NomorPelanggan & Chr(34) & vbCrLf)
Threading.Thread.Sleep(100)
.Write(IsiPesan & vbCrLf & Chr(26))
Threading.Thread.Sleep(100)
End With
Else
MsgBox("Modem Belum Tersambung")
End If
End Sub

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.

SELECT Query WHERE multiple values from checkboxlist are used

I was wondering if it was possible to filter down data from a table using multiple values from a checkboxlist? (or any other way) I have a checkboxlist and a gridview and when you check on of the boxes it does show the right data in the gridview but the problem arises when I try to check multiple values. It seems to search for the first checked value and then ignores the rest. You'd think it'd be simple! Perhaps it is. Here is my attempt below.
CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim strSQL As New System.Text.StringBuilder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
FillGridView()
End If
End Sub
Private Sub FillGridView()
Dim strMyConn As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
Using MyConn As New SqlClient.SqlConnection(strMyConn)
MyConn.Open()
Dim cmd As New SqlClient.SqlCommand(strSQL.ToString, MyConn)
cmd.Connection = MyConn
cmd.CommandType = CommandType.Text
Try
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
If Me.GridView1.Visible = False Then Me.GridView1.Visible = True
Catch ex As Exception
Me.GridView1.Visible = False
End Try
End Using
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
If c <> 0 Then
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
End If
End Sub
End Class
Refactor this section to create a WHERE IN statement so it checks to see if the value is found among any item checked
Before
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
After
Dim params As StringBuilder = New StringBuilder()
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
params.Append("'")
params.Append(CheckBoxList1.Items(i).Text)
If i < Me.CheckBoxList1.Items.Count Then
params.Append("',") // don't append a comma if it's the last item
End If
End If
Next
strSQL.Append("SELECT Project.* FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID WHERE Keyword.Keyword in (")
strSQL.Append(params.ToString()) // append comma delimited values that make up where in statement
strSQL.Append("')") // close where in statement
FillGridView()

Visual basic and modules

Im writing a application in visual basic to tell the user about their pc.
All this is in a module
Imports Microsoft.VisualBasic.Devices
Imports System.Management
Imports System.Net
Imports System.IO
Imports System.Windows.Forms
Imports System.Deployment.Application
Module ComputerSpecModule
Public Enum infotypes
ProcesserName
VideocardName
VideocardMem
End Enum
Public Function getinfo(ByVal infotype As infotypes) As String
Dim info As New ComputerInfo : Dim value, vganame, vgamem, proc As String
Dim searcher As New Management.ManagementObjectSearcher( _
"root\CIMV2", "Select * FROM Win32_VideoController")
Dim searcher1 As New Management.ManagementObjectSearcher( _
"Select * FROM Win32_Processor")
If infotype = infotypes.ProcesserName Then
For Each queryObject As ManagementObject In searcher1.Get
proc = queryObject.GetPropertyValue("Name").ToString
Next
value = proc
ElseIf infotype = infotypes.VideocardName Then
For Each queryObject As ManagementObject In searcher.Get
vganame = queryObject.GetPropertyValue("Name").ToString
Next
value = vganame
ElseIf infotype = infotypes.VideocardMem Then
For Each queryObject As ManagementObject In searcher.Get
vgamem = queryObject.GetPropertyValue("AdapterRAM").ToString
Next
value = Math.Round((((CDbl(Convert.ToDouble(Val(vgamem))) / 1024)) / 1024), 2) & " MB"
End If
Return value
End Function
Public oAddr As System.Net.IPAddress 'gets the ipv4 add
Public sAddr As String
Public EmailStarterMessage As String = "This message was sent by SpecMee. SpecMee is a light weight application designed to allow the users to find out the specifications of their machines. Please download this application free at http://www.wilson18.com/projects/SpecMee/" + _
Environment.NewLine + _
"" + _
Environment.NewLine + _
"" + _
Environment.NewLine + _
""
'PC SPEC CONTENT
Public ComputerName As String = (My.Computer.Name.ToString)
Public myOS As String = (My.Computer.Info.OSFullName)
Public Processor As String = (getinfo(infotypes.ProcesserName))
Public HDD As String = (Format((My.Computer.FileSystem.Drives.Item(0).TotalSize.ToString / 1024) / 1024 / 1024, "###,###,##0 GB"))
Public RAM As String = (Format((My.Computer.Info.TotalPhysicalMemory / 1024) / 1024 / 1024, "###,###,##0 GB"))
Public VideoCard As String = (getinfo(infotypes.VideocardName))
Public VideoCardMemory As String = (getinfo(infotypes.VideocardMem))
Public Function Resolution() As String
Dim intx As Integer = Screen.PrimaryScreen.Bounds.Width
Dim inty As Integer = Screen.PrimaryScreen.Bounds.Height
Return intx & " x " & inty
End Function
Public Function InternalIPAddress()
With System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
oAddr = New System.Net.IPAddress(.AddressList(0).Address)
InternalIPAddress = oAddr.ToString
End With
End Function
Public Function ExternalIPAddress() As String
Dim uri_val As New Uri("http://www.wilson18.com/projects/SpecMee/curip.php")
Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim myip As String = reader.ReadToEnd()
response.Close()
Return myip
End Function
Public EmailContent As String = ("Computer Name: " & ComputerName & Environment.NewLine & "Operating System: " & myOS & Environment.NewLine & "Processor: " & Processor & Environment.NewLine & "Hard Drive Size : " & HDD & Environment.NewLine & "RAM: " & RAM & Environment.NewLine & "Graphics Card: " & VideoCard & Environment.NewLine & "Graphics Onboard Memory: " & VideoCardMemory & Environment.NewLine & "Resolution: " & Resolution() & Environment.NewLine & "Internal IP Address: " & InternalIPAddress() & Environment.NewLine & "External IP Address: " & ExternalIPAddress() & Environment.NewLine)
End Module
The problem I am having is that if one of the things in the module fails such as if the users graphics card does not have any onboard memory then it will fail.This is causing everything else to fail aswell...
I am very new to visual basic so ifyou could please excuse me if I have made any stupidly obvious errors and any suggestions are welcome
Thanks in advance.
Place the parts that can fail in a Try-Catch-statement
Public VideoCardMemory As String = getinfo(infotypes.VideocardMem)
Public Function getinfo(ByVal infotype As infotypes) As String
Try
...
value = ...
...
Catch
value = "Cannot be accessed!"
End Try
Return value
End Function