How to get VID and PID in VB.NET - vb.net

I need to create a program that detect if a certain USB device is plugged. So lets say that we have a device that have VID (Vendor ID) = 9839 and PID (Product ID) = 5453.
I need a code that when i plug the device, the program get automatically the VID and the PID of the device, and write them in two texboxes.
After that is simple, I use:
If textbox1.Text = "9839" And textbox2.Text = "5453" then
MsgBox("You plugged the device!")
Else
MsgBox("Device is not plugged")
End If
But i need the code for getting VID and PID of the inserted device into textboxes.
So if someone could help me, let me know :)
I tried a solution using USBCLASSLibrary Demo
wich is a free dll but my pc is a x64 one and the dll is x32 so i get a error in C# (Bad Image Format) or something else.
I tried using a code found on CodeProject
private void USBPort_USBDeviceAttached(object sender,
USBClass.USBDeviceEventArgs e)
{
if (!MyUSBDeviceConnected)
{
if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID,
ref USBDeviceProperties, false))
{
//My Device is connected
MyUSBDeviceConnected = true;
}
}
}
private void USBPort_USBDeviceRemoved(object sender,
USBClass.USBDeviceEventArgs e)
{
if (!USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID,
ref USBDeviceProperties, false))
{
//My Device is removed
MyUSBDeviceConnected = false;``
}
}

Have you tried HIDs?
Debug.WriteLine(" HIDD_ATTRIBUTES structure filled without error.")
Debug.WriteLine(" Structure size: " & MyHid.DeviceAttributes.Size)
Debug.WriteLine(" Vendor ID: " & Hex(MyHid.DeviceAttributes.VendorID))
Debug.WriteLine(" Product ID: " & Hex(MyHid.DeviceAttributes.ProductID))
Debug.WriteLine(" Version Number: " & Hex(MyHid.DeviceAttributes.VersionNumber))
And then, try :
Try
myVendorID = Int32.Parse(txtVendorID.Text, NumberStyles.AllowHexSpecifier)
myProductID = Int32.Parse(txtProductID.Text, NumberStyles.AllowHexSpecifier)
Catch ex As Exception
End Try

create combo box named cmbHdd and place the code on your form. this will populate the combo with usb devices and also get ALL required info from Win32_DiskDrive aswell as Win32_USBHub for the PID and Vendor ID
Hope this helps..
malvastyle team
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim mosDisks As New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive")
For Each moDisk As ManagementObject In mosDisks.[Get]()
cmbHdd.Items.Add(moDisk("Model").ToString())
Next
End Sub
Private Sub cmbHdd_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbHdd.SelectedIndexChanged
Try
Dim GetQuery As String = ("SELECT * FROM Win32_DiskDrive WHERE Model = '" & cmbHdd.SelectedItem & "'")
Dim mosDisks As New ManagementObjectSearcher(GetQuery)
For Each moDisk As ManagementObject In mosDisks.[Get]()
lblType.Text = moDisk("MediaType").ToString().Trim
lblModel.Text = moDisk("Model").ToString().Trim
lblSerial.Text = moDisk("SerialNumber").ToString().Trim
lblInterface.Text = moDisk("InterfaceType").ToString().Trim
lblCapacity.Text = moDisk("Size").ToString() & " bytes (" & Math.Round((((CDbl(Convert.ToDouble(moDisk("Size"))) / 1024) / 1024) / 1024), 2) & " GB)".Trim
lblPartitions.Text = moDisk("Partitions").ToString().Trim
lblSignature.Text = moDisk("Signature").ToString().Trim
lblFirmware.Text = moDisk("FirmwareRevision").ToString().Trim
lblSylinders.Text = moDisk("TotalCylinders").ToString().Trim
lblSectors.Text = moDisk("TotalSectors").ToString().Trim
lblHeads.Text = moDisk("TotalHeads").ToString().Trim
lblTracks.Text = moDisk("TotalTracks").ToString().Trim
lblBytesPerSector.Text = moDisk("BytesPerSector").ToString().Trim
lblSectorsPerTrack.Text = moDisk("SectorsPerTrack").ToString().Trim
lblTrackPerCylinder.Text = moDisk("TracksPerCylinder").ToString().Trim
' lblProductID.Text = moDisk("PNPDeviceID").ToString().Trim
lblVendorID.Text = moDisk("PNPDeviceID").ToString().Trim
Next
Dim USBClass As New System.Management.ManagementClass("Win32_USBHub")
Dim USBCollection As System.Management.ManagementObjectCollection = USBClass.GetInstances()
Dim _USB As System.Management.ManagementObject
Dim _tempID As String = ""
For Each _USB In USBCollection
Dim splitString As String() = (_USB("DeviceID")).Split(New [Char]() {"/"c, "\"c, CChar(vbTab)})
_tempID = splitString(1)
If (lblVendorID.Text).Contains(splitString(2)) Then
lblSerial.Text = splitString(2)
Exit For
End If
_tempID = ""
Next
If _tempID <> "" Then
Dim splitID As String() = _tempID.Split(New [Char]() {"&"c, CChar(vbTab)})
Dim splitVendor As String() = splitID(0).Split(New [Char]() {"_"c, CChar(vbTab)})
Dim splitProduct As String() = splitID(1).Split(New [Char]() {"_"c, CChar(vbTab)})
lblVendorID.Text = splitVendor(1)
lblProductID.Text = splitProduct(1)
End If
Catch ex As Exception
End Try
End Sub

Related

Ping the network quickly

good day!
Tell me how you can quickly ping the entire network?
There is the following code that scans the network.
Public Sub Scan(ByVal subnet As String)
Dim myPing As Ping
Dim reply As PingReply
Dim addr As IPAddress
Dim host As IPHostEntry
Dim active_addr As Integer = 0
ProgressBar1.Maximum = 254
ProgressBar1.Value = 0
ListView1.Items.Clear()
For i As Integer = 1 To 254
Dim subnetn As String = "." & i.ToString()
myPing = New Ping()
reply = myPing.Send(subnet & subnetn, 900)
Label3.ForeColor = Color.Green
Label3.Text = "Scan: " & subnet & subnetn
If reply.Status = IPStatus.Success Then
Try
addr = IPAddress.Parse(subnet & subnetn)
host = Dns.GetHostEntry(addr)
If My.Computer.Network.Ping(host.HostName, 10) Then
ListView1.Items.Add(New ListViewItem(New String() {subnet & subnetn, host.HostName, "True"}))
Else
ListView1.Items.Add(New ListViewItem(New String() {subnet & subnetn, host.HostName, "False"}))
End If
Catch
ListView1.Items.Add(New ListViewItem(New String() {subnet & subnetn, " ", "False"}))
End Try
active_addr += 1
End If
ProgressBar1.Value += 1
Label5.Text = Math.Round((ProgressBar1.Value * 100) / 254, 0, MidpointRounding.AwayFromZero) & " %"
')
ListView1.Items((ListView1.Items.Count - 1)).EnsureVisible()
ListView1.Items((ListView1.Items.Count - 1)).Selected = True
Next i
ListView1.Items(0).Focused = True
ListView1.Items(0).Selected = True
End Sub
But it takes a very long time to scan the network. Tell me, is it possible to do it faster?
And can I add the device's MAC address when scanning the network?
================================================================
Found a solution that quickly scans the network (a given range of ip addresses).
Tell me. how to add to this code to display the hostname and the MAC address? and add a ProgressBar to show the scan percentage.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Ping("192.168.1.28", "175")
End Sub
Private Async Function Ping(startIP As String, endIP As String) As Task
Dim start As IPAddress = IPAddress.Parse(startIP)
Dim bytes = start.GetAddressBytes()
Dim leastSigByte = start.GetAddressBytes().Last
Dim range = endIP - leastSigByte
Dim pingReplyTasks = Enumerable.Range(leastSigByte, range).Select(Function(x)
Dim p = New Ping()
Dim bb = start.GetAddressBytes()
bb(3) = CByte(x)
Dim destIp = New IPAddress(bb)
Dim pingResultTask = p.SendPingAsync(destIp)
Return New With {
Key pingResultTask,
Key .addr = destIp
}
End Function).ToList()
Await Task.WhenAll(pingReplyTasks.Select(Function(x) x.pingResultTask))
For Each pr In pingReplyTasks
Dim tsk = pr.pingResultTask
Dim pingResult = tsk.Result
Dim ip = pr.addr
'
DataGridView1.Rows.Add(ip, pingResult.RoundtripTime, pingResult.Status)
Next pr
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.

Convert jscript to vb.net

We use Kaspersky Security Center to manage AV on all our domain computers. I was looking for an external way to move computers to different groups and change the comments we give them in the Kaspersky Security Center. Kaspersky gave me some links to check out but I have no idea where to start on this. I was looking to code this in a VB.Net Windows Form Application.
My question is how do i convert or make the below jscript work in a VB.net Windows form. I'm going to have a sql table loaded with the Kaspersky Host ID, Comment and GroupID. once a day i want to iterate down through that sql table and only update the computers that need changes made wither to their comment or group. (the sql part i already have written)
Here is what im Aiming for:
Dim reader3 As SqlDataReader
Dim strconnection3 As String
strconnection3 = data_source_all 'defined globally
Dim SqlConnection3 As New SqlConnection(strconnection3)
Dim cmd3 As New SqlCommand
cmd3.CommandText = "SELECT kaspersky_hostid, kaspersky_comment, pc_info_comment, kaspersky_groupid FROM pc_info where (pc_status = 'active')"
cmd3.CommandType = CommandType.Text
cmd3.Connection = SqlConnection3
SqlConnection3.Open()
reader3 = cmd3.ExecuteReader()
If reader3.HasRows Then
While reader3.Read()
If reader3(1).ToString = reader3(2).ToString Then
Else
Update_Host_Comment(reader3(0).ToString,reader3(2).ToString)
End If
End While
SqlConnection3.Close()
SqlConnection3.Dispose()
cmd3.Dispose()
Else
End If
Public Sub Update_Host_Comment(ByVal hostid As String, ByVal comment As String)
'Converted JScript
'var oHosts = new ActiveXObject("klakaut.KlAkHosts");
'oHosts.AdmServer = AcquireAdServerProxy();
'var strHostName = hostid; //name of the host to change attributes
'//Fill container with attributes to change
'var oProps = new ActiveXObject("klakaut.KlAkParams");
'oProps.Item("KLHST_WKS_COMMENT") = comment; //Change Comment
'oHosts.UpdateHost(strHostName, oProps);
End Sub
Link1: https://support.kaspersky.com/9291
Link2: https://support.kaspersky.com/2810
below is the JScript i want to run with vb.net:
function AcquireAdServerProxy()
{
var oSrvConnectionProps = new ActiveXObject("klakaut.KlAkParams");
oSrvConnectionProps.Add("Address", "localhost:13291");
oSrvConnectionProps.Add("UseSSL", true);
var oAdmServer = new ActiveXObject("klakaut.KlAkProxy");
oAdmServer.Connect(oSrvConnectionProps);
return oAdmServer;
};
function Update_Host_Comment(hostid,comment)
{
var oHosts = new ActiveXObject("klakaut.KlAkHosts");
oHosts.AdmServer = AcquireAdServerProxy();
var strHostName = hostid; //name of the host to change attributes
//Fill container with attributes to change
var oProps = new ActiveXObject("klakaut.KlAkParams");
oProps.Item("KLHST_WKS_COMMENT") = comment; //Change Comment
oHosts.UpdateHost(strHostName, oProps);
};
function Update_Host_Group(hostid,groupid)
{
var oHosts = new ActiveXObject("klakaut.KlAkHosts");
oHosts.AdmServer = AcquireAdServerProxy();
var strHostName = hostid; //name of the host to change attributes
//Fill container with attributes to change
var oProps = new ActiveXObject("klakaut.KlAkParams");
oProps.Item("KLHST_WKS_GROUPID") = groupid; //Change group
oHosts.UpdateHost(strHostName, oProps);
};
//Calling Functions
Update_Host_Comment("SomeHostID","Some Comment Text");
Update_Host_Group("SomeHostID","Some GroupID");
06/04/18 Edit: Here is the code i tried:
Public Function AcquireAdServerProxy()
Try
Dim oSrvConnectionProps = CreateObject("klakaut.KlAkParams")
oSrvConnectionProps.Add("Address", "localhost:13291")
oSrvConnectionProps.Add("UseSSL", True)
Dim oAdmServer = CreateObject("klakaut.KlAkProxy")
oAdmServer.Connect(oSrvConnectionProps)
Return oAdmServer
Catch ex As Exception
MsgBox(ex.ToString)
Return False
End Try
End Function
Public Function Update_Host_Comment(ByVal hostid As String, ByVal comment As String) As Boolean
Try
Dim ohosts = CreateObject("klakaut.KlAkHosts")
ohosts.AdmServer = AcquireAdServerProxy()
Dim strHostName = hostid
'Fill container with attributes to change
Dim oProps = CreateObject("klakaut.KlAkParams")
oProps.Item("KLHST_WKS_COMMENT") = comment
ohosts.UpdateHost(strHostName, oProps)
Return True
Catch ex As Exception
MsgBox(ex.ToString)
Return False
End Try
End Function
Public Function Update_Host_Group(ByVal hostid As String, ByVal groupid As Integer) As Boolean
Try
Dim ohosts = CreateObject("klakaut.KlAkHosts")
ohosts.AdmServer = AcquireAdServerProxy()
Dim strHostName = hostid
'Fill container with attributes to change
Dim oProps = CreateObject("klakaut.KlAkParams")
oProps.Item("KLHST_WKS_GROUPID") = groupid
ohosts.UpdateHost(strHostName, oProps)
Return True
Catch ex As Exception
MsgBox(ex.ToString)
Return False
End Try
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label4.Text = "Processing ..."
Label4.Update()
Try
If TextBox1.Text <> Nothing Then
If TextBox2.Text <> Nothing Then
If Update_Host_Comment(TextBox1.Text, TextBox2.Text.ToUpper) Then
Label4.Text = "Comment Updated"
Label4.Update()
Else
Label4.Text = "Comment Update Error"
Label4.Update()
End If
Else
End If
If TextBox3.Text <> Nothing And IsNumeric(TextBox3.Text) Then
If Update_Host_Group(TextBox1.Text, TextBox3.Text) Then
Label4.Text = Label4.Text & " / Group Updated"
Label4.Update()
Else
Label4.Text = Label4.Text & " / Group Update Error"
Label4.Update()
End If
Else
End If
End If
Catch ex As Exception
Label4.Text = "Error"
Label4.Update()
End Try
End Sub
End Class
This is the error i get when i run it:
System.Runtime.InteropServices.COMException (0xE0FF04FD): Transport level error while connecting to http://localhost:13291: failed to resolve address at Microsoft.VisualBasic.CompilerServices.LateBinding.InternalLateCall(Object o, Type objType, String name, Object[] args, String[] paramnames, Boolean[] CopyBack, Boolean IgnoreReturn) at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack, Boolean IgnoreReturn) at kaspersky_api.Form1.AcquireAdServerProxy()

Wait until media element has naturalDuration information

I need to make a loop to look at a lot of mp3 files and getting their naturalDuration property using a mediaElement. The problem is that mediaElement need some time to load every single file and .source property works like async process (I think) because I have to click two times on below code if I want to obtain naturalDuration property. First click I have just 00:00:00 value, second clik give me real value.
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
mediaElement.Source = New Uri("\\Mac\Home\Desktop\NOVEDADES01\AbrahamMateo-OldSchool.mp3")
textBlock.Text = mediaElement.NaturalDuration.ToString
End Sub
If I try to wait after .Source instruction, the application keeps on loop.
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
mediaElement.Source = New Uri("\\Mac\Home\Desktop\NOVEDADES01\AbrahamMateo-OldSchool.mp3")
Do
Loop Until mediaElement.NaturalDuration.TimeSpan.TotalSeconds > 0
textBlock.Text = mediaElement.NaturalDuration.ToString
End Sub
I also have try set .source through an async process and wait for mediaOpenend event, but it look like mediaElemento can not end until the first click was ending
How could I get real value of naturalDuration inside one single process or function just after set .source property and without playing the file?
Thanks a lot!!
Ok, late and may be not so elegant but this was my solution for getting duration of a mp3 file. I used MusicProperties Class.
Public Function infoMP3(elfichero As String) As String
Dim salida As String = ""
Dim miTask = Task.Run(Async Function() As Task(Of String)
Dim musicFile As StorageFile = Await StorageFile.GetFileFromPathAsync(elfichero)
Dim FileProperties As StorageItemContentProperties = musicFile.Properties
Dim musicFileProperties As MusicProperties = Await FileProperties.GetMusicPropertiesAsync()
Dim tiempo = musicFileProperties.Duration
Dim horas As String
If tiempo.Hours < 10 Then
horas = "0" & tiempo.Hours.ToString
Else
horas = tiempo.Hours.ToString
End If
Dim minutos As String
If tiempo.Minutes < 10 Then
minutos = "0" & tiempo.Minutes.ToString
Else
minutos = tiempo.Minutes.ToString
End If
Dim segundos As String
If tiempo.Seconds < 10 Then
segundos = "0" & tiempo.Seconds.ToString
Else
segundos = tiempo.Seconds.ToString
End If
Dim autor = musicFileProperties.Artist
Dim titulo = musicFileProperties.Title
Dim presalida As String = "[" & horas & ":" & minutos & ":" & segundos & "];[" & titulo & "];[" & autor & "] " & elfichero
Return presalida
End Function)
miTask.Wait()
salida = miTask.Result
Return salida
End Function
To get access to the files later on Windows 10, you have to save permission for the files and/or folders. Do this when you select them.
...
Dim listToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(rutaS)
...
where rutaS is an SotorageFolder object.

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