Ping the network quickly - vb.net

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

Related

Find and highlight the max value in from multiple column in VB.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error
maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

vb.net threading sub slower than call sub

I know this Question was already posted, but it was never really answered, or I did not understand the answer :)
My Problem is that when I call this Sub within the Thread, it takes about 4 sec to execute the code, but if I make a simple Call Sub (Like commented in Code) it takes about 450 ms.
I have a simple program with 2 Subs:
To report Progress on Main Form
To do some "For" Looping
Imports System.Data.SqlClient
Public Class Form1
Public Delegate Sub ProzentDelegate(ByVal Prozent As Double)
Dim G_I_Temp As Integer = 0
Dim G_S_Prüfziffer As String
Dim G_S_Präfix As String
Dim G_I_Zähler As Integer
Dim G_I_Stellen As Integer
Dim G_D_Step As Integer = 1
Dim G_I_Position As Integer
Dim DT_G_Prüftabelle As DataTable
Dim DR_G_Prüftabelle As DataRow
Dim thisLock As New Object
Dim conn As String = "Data Source=SR-SQLWVS;Initial Catalog=Barcode;Integrated Security=True"
Dim sourceconn As New SqlConnection(conn)
Dim adap As SqlDataAdapter
Dim cmd As SqlCommand = New SqlCommand("SELECT TOP(10) * FROM dbo.Prüf_Tabelle", sourceconn)
Dim Thrd_preview As Threading.Thread
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sourceconn.Open()
cmd.Connection = sourceconn
End Sub
Public Sub ReportProgress(ByVal Prozent As Double)
ProgressBar1.Value = Prozent
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If RB_Thread.Checked Then
If Thrd_preview IsNot Nothing Then Thrd_preview = Nothing
Thrd_preview = New Threading.Thread(AddressOf DoSomeWork)
Thrd_preview.IsBackground = True
Thrd_preview.Start()
Else
DoSomeWork()
End If
End Sub
Private Sub DoSomeWork()
Dim ds As New DataSet
DT_G_Prüftabelle = ds.Tables.Add("Prüf_Tabelle")
Dim L_I_Counter, L_I_Counter2 As Integer
Dim L_I_Ende As Integer
Dim L_I_Step As Integer
Dim L_I_Nutzen As Integer = 1
L_I_Step = 1
L_I_Ende = Val(TB_Auftrag_neu_Anzahl.Text)
G_I_Stellen = 8
G_S_Prüfziffer = "1"
G_S_Präfix = "00"
If TB_Info_Increment.Text = "" Then TB_Info_Increment.Text = 1
adap = New SqlDataAdapter("SELECT TOP(10) * FROM dbo.Prüf_Tabelle", sourceconn)
adap.FillSchema(DT_G_Prüftabelle, SchemaType.Mapped)
DT_G_Prüftabelle.Rows.Clear()
Dim pre As Date = Now
For L_I_Counter = 1 To (L_I_Ende * L_I_Step) Step L_I_Step
For L_I_Counter2 = 1 To L_I_Nutzen
DR_G_Prüftabelle = DT_G_Prüftabelle.NewRow
DR_G_Prüftabelle.Item("Auftrag_Lfd_nr") = TB_KeyLot.Text
DR_G_Prüftabelle.Item("Position") = G_I_Position
G_I_Position += G_D_Step
DR_G_Prüftabelle.Item("Barcode_soll") = F_Berechnung((Trim(Str(Val(TB_Auftrag_neu_Von.Text) + L_I_Counter - 1))).PadLeft(G_I_Stellen, "0"))
DT_G_Prüftabelle.Rows.Add(DR_G_Prüftabelle)
If ProgressBar1.InvokeRequired Then
ProgressBar1.BeginInvoke(New ProzentDelegate(AddressOf ReportProgress), (L_I_Counter * 100) / (L_I_Ende * L_I_Step))
Else
ReportProgress((L_I_Counter * 100) / (L_I_Ende * L_I_Step))
End If
Next
Next
MsgBox(Now.Subtract(pre).TotalMilliseconds.ToString & " ms.")
End Sub
Function F_Berechnung(ByVal L_Nummer As String) As String
Dim L_B_Gerade As Boolean = False
Dim L_I_Prüfziffer As Integer
Dim L_I_Stellen As Integer
Me.G_I_Temp = 0
Select Case G_S_Prüfziffer
Case "0"
F_Berechnung = L_Nummer
Case "1"
F_Berechnung = G_S_Präfix & Trim(L_Nummer)
Case "2"
F_Berechnung = G_S_Präfix & Trim(L_Nummer)
Case "3"
F_Berechnung = L_Nummer
'
Case "5" '-----Mod 10 gewichtung 31...-----
L_Nummer = G_S_Präfix & Trim(L_Nummer)
L_I_Stellen = Len(L_Nummer)
For Me.G_I_Zähler = L_I_Stellen To 1 Step -1
Me.G_I_Temp += Val(Mid(L_Nummer, Me.G_I_Zähler, 1)) * IIf(L_B_Gerade, 1, 3)
L_B_Gerade = Not L_B_Gerade
Next
L_I_Prüfziffer = IIf(10 - Me.G_I_Temp Mod 10 = 10, 0, 10 - Me.G_I_Temp Mod 10)
F_Berechnung = Trim(L_Nummer) & Trim(Str(L_I_Prüfziffer))
'
Case "6" '-----Mod 10 gewichtung 13...-----
L_Nummer = G_S_Präfix & Trim(L_Nummer)
L_I_Stellen = Len(L_Nummer)
For Me.G_I_Zähler = L_I_Stellen To 1 Step -1
Me.G_I_Temp += Val(Mid(L_Nummer, Me.G_I_Zähler, 1)) * IIf(L_B_Gerade, 3, 1)
L_B_Gerade = Not L_B_Gerade
Next
L_I_Prüfziffer = IIf(10 - Me.G_I_Temp Mod 10 = 10, 0, 10 - Me.G_I_Temp Mod 10)
F_Berechnung = Trim(L_Nummer) & Trim(Str(L_I_Prüfziffer))
'
Case Else
F_Berechnung = L_Nummer
End Select
End Function
I have tried to take out Progress Reporting but the Result is the same.
I hope you have some suggestions or solutions for me. I would be very thankful.
Give these changes a try
Change this
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(New ProzentDelegate(AddressOf ReportProgress), Progr)
Else
ReportProgress(Progr)
End If
to
ReportProgress(Progr)
And change method ReportProgress to
Public Sub ReportProgress(ByVal Prozent As Double)
Me.BeginInvoke(Sub()
ProgressBar1.Value = Prozent
End Sub)
End Sub
See if that makes a difference. The check for InvokeRequired is not needed, the answer is always yes.
Just wanted to report that I found a solution.
The main problem was this line of code in:
DR_G_Prüftabelle.Item("Auftrag_Lfd_nr") = TB_KeyLot.Text
So if I start this Sub from another Thread rather than from a Main Thread, for every single loop it has to go to main thread and to take Paramater from TextBox and to go back in Thread to Loop further.
I took that out, declared a variable at the begining and assigned this TextBox value to it and it works like charm.
Also I took a suggestion from dbasnett to Invoke Reporting every time without If-Else and also the suggestion from Steven Doggart to Report every 100 Loops.
You guys helped a lot. Thanks for that!!

How to get VID and PID in 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

Creating a DataGridView Programatically and add clickable cells

Evening
I am struggling to achieve what I have set out todo! In a nutshell I am working with the Google Drive API to create an app in VB.net that allows you to view / download files etc.
Basically I am planning on using a couple of different api's for the different cloud provider s I have. The stage I have got to is that I have my collection of files and there various properties in a list. On load I am checking to see if a google account has been added to my program and if so creating a new tabpage on a tabcontrol, I then create the datagridview and add it to the collection on the new tab page. This works fine and displays all my data as is.
What I am trying to achieve is adding a clickable link to my download column instead of displaying the url. I have been trying to manipulate the code found here C# DataGridViewLinkCell Display after converting it to vb.net. This is basically what I have ended up with:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim dgvlc As New DataGridViewLinkColumn()
dgvlc.ActiveLinkColor = Color.Blue
dgvlc.HeaderText = "Download"
GoogleDriveDGV.Columns.Add(dgvlc)
GoogleDriveDGV.RowHeadersVisible = False
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download File"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
I have two problems that I cant figure out:
1) GoogleDriveDGV is not declared here : For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
2) If I comment out the GoogleDriveDGV_CellContentClick sub and just try to populate the datagridview I get System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.DataGridViewLinkColumn' to type 'customcolumn' here DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Can anyone let me know if what I am trying to achieve is possible and any hints?
Update!!!
I now have this:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
'Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
' For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
' If url.Key = e.RowIndex Then
' Process.Start(url.Value)
' Exit For
' End If
' Next
'End Sub
Which is almost there, I now have the datagridview filled with the items and a download link, just cant work out how to solve issue 1 above :-(
Would you believe it I worked it out :-)
Basically I needed to add a handler.
Full code:
Private Sub CloudManager_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
AddHandler GoogleDriveDGV.CellContentClick, AddressOf GoogleDriveDGV_CellContentClick
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(sender.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
End Class

VB.NET IP disconnector: what is the correct usage of SetTcpEntry to disconnect

I am trying to create an IP disconnector. This is part from a template that I took that creates a TCPtable. I was trying to add a disconnecting function. However, it does not disconnect.
Dim liste() = {"76.9.24.130" ... ... ...}
Dim pdwSize As Integer
Dim iRetVal As Integer
Dim i As Integer
Dim TcpTableRow As MIB_TCPROW
Dim pStructPointer As IntPtr = IntPtr.Zero
Dim iNumberOfStructures As Integer
ListView1.Items.Clear()
iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)
pStructPointer = Marshal.AllocHGlobal(pdwSize)
iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)
iNumberOfStructures = Math.Ceiling((pdwSize - 4) / Marshal.SizeOf(GetType(MIB_TCPROW)))
For i = 0 To iNumberOfStructures - 1
Dim pStructPointerTemp As IntPtr = New IntPtr(pStructPointer.ToInt32() + 4 + (i * Marshal.SizeOf(GetType(MIB_TCPROW))))
TcpTableRow = New MIB_TCPROW()
With TcpTableRow
.dwLocalAddr = 0
.dwState = 0
.dwLocalPort = 0
.dwRemoteAddr = 0
.dwRemotePort = 0
End With
'Marshal.PtrToStructure(pStructPointerTemp, TcpTableRow)
TcpTableRow = CType(Marshal.PtrToStructure(pStructPointerTemp, GetType(MIB_TCPROW)), MIB_TCPROW)
' Process each MIB_TCPROW here
'If Not ((Check1.CheckState = System.Windows.Forms.CheckState.Checked) And (GetIpFromLong(TcpTableRow.dwLocalAddr) = "0.0.0.0" Or GetIpFromLong(TcpTableRow.dwLocalAddr) = "127.0.0.1")) Then
If Not GetIpFromLong(TcpTableRow.dwRemoteAddr) = "127.0.0.1" And Not GetIpFromLong(TcpTableRow.dwRemoteAddr) = "0.0.0.0" Then
'Add the data to the ListView control
With TcpTableRow
Dim itemAdd As ListViewItem
itemAdd = ListView1.Items.Add(GetIpFromLong(.dwLocalAddr))
itemAdd.SubItems.Add(CStr(GetTcpPortNumber(.dwLocalPort)))
itemAdd.SubItems.Add(GetIpFromLong(.dwRemoteAddr))
itemAdd.SubItems.Add(CStr(GetTcpPortNumber(.dwRemotePort)))
itemAdd.SubItems.Add(GetState(.dwState))
End With
'-------------- Kill Connection--------------
If Array.IndexOf(liste, GetIpFromLong(TcpTableRow.dwRemoteAddr)) >= 0 Then
TcpTableRow.dwState = 12
SetTcpEntry(TcpTableRow)
End If
End If
Next
I could not solve it but found an alternative solution using CurrPorts
Shell(Application.StartupPath & "\cports /close * * " & GetIpFromLong(TcpTableRow.dwRemoteAddr) & " " & GetTcpPortNumber(TcpTableRow.dwRemotePort))
I am not sure if this is the same situation or not but I was using:
session = New Socket(,,,) as my means of connecting via TCP PORT23 and my issue was that I too could not get the connection to close for some reason. I did try the CurrPorts workaround above but I found that did not meet my expectations. Instead I am using TCPClient.
Dim TCPConnection as TCPClient 'Init TCPConnect
Private Sub Connect(Byval inIP)
Dim PiP = IPAddress.Parse(inIP)
Dim iplocal As New System.Net.IPEndPoint(PiP, 23)
Try
TCPsession = New TcpClient
TCPsession.Client.Connect(ipLocal)
Catch
'On Error Do Nothing
End Try
End Sub
Private Sub Disconnect()
TCPsession.Client.Close()
End Sub
This code solved my issue but I am not sure if thats what you where even talking about.