Obtain the list of open ports, windows firewall - arrays

I am trying to develop a code that manages the firewall ports using vb.net. The first part is to list all ports enabled. so I am trying this code:
Function portsList()
Dim ports As INetFwOpenPorts
Dim port As INetFwOpenPort
Dim myPorts() As INetFwOpenPorts
Dim NetFwMgrType As Type = Type.GetTypeFromProgID("HNetCfg.FwMgr", False)
Dim mgr As INetFwMgr = DirectCast(Activator.CreateInstance(NetFwMgrType), INetFwMgr)
ports = DirectCast(mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts, INetFwOpenPorts)
Dim enumerate As System.Collections.IEnumerator = ports.GetEnumerator()
Dim i As Integer
While enumerate.MoveNext()
port = DirectCast(enumerate.Current, INetFwOpenPort)
myPorts(i) = port
i += 1
End While
Dim portAsString() As String
For j As Integer = 0 To i
portAsString(j) = myPorts(j).ToString
Next
Return portAsString
End Function
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim ports() As String = portsList()
Dim n As String = ports.Length
Dim newString As String = ""
For h As Integer = 0 To n
newString = ports(h) & vbNewLine
Next
RichTextBox1.Text = newString
End Sub
What I want to do is list all the ports in Richtextbox1 after clicking Button4. The error that I am getting is:
NullReferenceException was unHandled. Object reference not set to an instance of an object.
I am new to Vb, how can I get over this?

Try this:
For port As Integer = 1 to maxPorts
Dim host As String = "192.168.1.7"
Dim hostadd As Net.IPAddress = Net.Dns.GetHostEntry(host).AddressList(0)
Dim EPhost As New Net.IPEndPoint(hostadd, port)
Dim s As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
Try
s.Connect(EPhost)
Catch
End Try
If s.Connected Then
'Port opened
Else
'Port closed
End If
Next
Here you have the complete project.

Related

VB.NET add or subtract an integer value to a SQL Server value into a label when selecting a combobox item

Following my previous question answered by #Andrew Morton, I have one more :)
Here is my whole code (not very long for now) :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateCB()
End Sub
Private Sub ComboBoxC1L1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxC1L1.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = val - 2
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = val + 2
End If
If cb.SelectedIndex >= 0 Then
Dim val2 = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
End If
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBoxQC1L1.Text = "ordinaire"
End Sub
Private Sub TextBoxC1L1_TextChanged(sender As Object, e As EventArgs) Handles TextBoxC1L1.TextChanged
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As exception
End Try
End Sub
End Class
Here is the program interface
Here is the SQL table look
Here is the program interface when the Button has been clicked
Red Arrow ComboBox text is a DropDownStyle box with 3 possible text choices:
ordinaire,
élite,
médiocre
What I want to do: when changing the red arrow combobox text, the cout_unité label should change too with a "cout_unité -2" in case of "médiocre" ComboBox text, or "cout_unité +2" in case of "élite" ComboBox text or remain = to "cout_unité" if the selected text is "ordinaire".
And it should calculate this only once from the original "cout_unité" value in the table (in case of clicking 10 times on "ordinaire", it shouldn't subtract 10 * 2 to the "cout_unité" value, only 1 * 2)
I can do it in the ComboBoxC1L1 (see code) but I can't reproduce it with this red arrow combobox (probably because of the type of data into this combobox which are "strings", I don't know).
Many thanks :)
Since there is only a single Handles clause, the following line is unnecessary. The sender can only be the ComboBox in the Handles.
Dim cb = DirectCast(sender, ComboBox)
If you set the ValueMember of the combo in the PopulateCB method, you can save a long line of code making the code more readable.
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
To:
Dim val = CInt(ComboBoxC1L1.SelectedValue)
We need the CInt since SelectedValue is an Object.
Don't assign the DataSource until after the DisplayMember and ValueMember are set.
You are checking twice for ComboBoxC1L1.SelectedIndex >= 0.
Just include the unit type in the first If.
The user may not have to trigger the SelectedIndexChanged event if the correct value is already selected. Maybe a button click would be better.
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBoxC1L1.ValueMember = "cout_unité"
ComboBoxC1L1.DataSource = dt
End Sub
Private Sub btnCalculateValue_Click(sender As Object, e As EventArgs) Handles btnCalculateValue.Click
If ComboBoxC1L1.SelectedIndex >= 0 Then
Dim val = CInt(ComboBoxC1L1.SelectedValue)
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val.ToString
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = (val - 2).ToString
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = (val + 2).ToString
End If
Dim val2 = DirectCast(ComboBoxC1L1.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1.ToString
End Sub

Moving file contents into an array

Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)

Add Items to a ListView from a database

I am a Vb nooby and I have trouble to add specific Items to my Listview from a database.
I would like to compare the value of a combobox with a column value of a table.
To proof if they are equal like apple = apple
When they are equal the whole data set should be added to my ListView. (Only data sets which have the equal value like the selected item of the combobox)
Please Help !!
Thanks a lot and best regards
You can try below code..
Imports System.Data.SqlClient
Public Class Form1
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=id;Password=pass")
Dim strQ As String = String.Empty
strQ = "SELECT * FROM Northwind.dbo.Products"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
End Sub
End Class
You can try this link.
Thanks for your help.
In my solution, I just set a parameter into the sql statement.
Public Function getRahmenvertrag**(ByVal costumerID As Integer)** As List(Of Rahmenvertrag)
Dim sqlCom As New SqlServerCe.SqlCeCommand
sqlCom.CommandText = **"SELECT * FROM Rahmenvertrag LEFT OUTER JOIN Kunde ON Kunden_FID = Kunden_ID WHERE Kunden_ID = #Kunde "**
**sqlCom.Parameters.AddWithValue("Kunde", costumerID)**
Private Sub ComboBox1_Click(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ListView4.DataBindings.Clear()
ListView4.Items.Clear()
If IsNothing(ComboBox1.SelectedItem) = False Then
For Each Rahmenvertrag As Rahmenvertrag In controller.getRahmenvertrag(ComboBox1.SelectedItem.kunde_ID)
With ListView4.Items.Add(Rahmenvertrag.bezeichnung)
.SubItems.Add(Rahmenvertrag.inhalt)
End With
Next
End If
End Sub

ProcessWindowStyle.Hidden in string array

In my VB.net project, I am trying to call up multiple programs using an array to help clean up my code.
Currently, I have this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles StartServer.Click
Dim proc As New ProcessStartInfo()
Dim prochide As New ProcessStartInfo()
prochide.WindowStyle = ProcessWindowStyle.Hidden
If CheckBox1.CheckState = 1 Then
proc.WorkingDirectory = TextBox1.Text
proc.FileName = "xserver.exe"
Process.Start(proc)
proc.FileName = "yserver.exe"
Process.Start(proc)
proc.FileName = "zserver.exe"
Process.Start(proc)
Else
prochide.WorkingDirectory = TextBox1.Text
prochide.FileName = "xserver.exe"
Process.Start(prochide)
prochide.FileName = "yserver.exe"
Process.Start(prochide)
prochide.FileName = "zserver.exe"
Process.Start(prochide)
End If
End Sub
What this does is allows me to hide the windows so they show up in task manager but the windows don't actually show up.
However, I would prefer to switch with this code or something similar to clean it up:
Dim servers(0 To 2) As String
servers(0) = "xserver.exe"
servers(1) = "yserver.exe"
servers(2) = "zserver.exe"
Then I can simplify the code:
Dim directory As String = TextBox1.Text
For Each fileName As String In servers
Next
However, I cannot figure out how to hide the windows in an array, since the .WindowStyle = ProcessWindowStyle.Hidden does not seem to work with array strings. Is there another way I can do this?Changing the method is fine, I just want to try to clean up the code since it seems a bit bulky right now.
Okay so I've finally checked this out, and this works for me:
Public Class Form1
Dim servers() As String = New String() {"cmd.exe|1", "cmd.exe|1", "cmd.exe|1"}
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim directory As String = TextBox1.Text
Dim prochide As New ProcessStartInfo()
prochide.WorkingDirectory = directory
For Each fileName As String In servers
Dim FileOptions() As String = Split(fileName, "|")
prochide.FileName = FileOptions(0)
prochide.WindowStyle = CType(FileOptions(1), ProcessWindowStyle)
Process.Start(prochide)
Next
End Sub
End Class
When using New String() you cannot declare the array with a limit. So that was our problem. :)
So instead of Dim servers(3)... or Dim servers(0 To 2)... you have to use Dim servers()...

Store multiple TcpClient Connections - VB.NET

I'm building an application that can communicate and send commands to game servers. In the gaming world we call this “rcon” for remote console, but in reality it's just a telnet session. After successful authentication, a text command can be issued to the server and a text response is sent back to the client.
Often times server admins/owners run multiple game servers and every server has its own distinct ip address, port & password. I would like my application to loop through a list/array/datatable/dictionary (or whatever method is best ) of servers, connect and authenticate to each server, then somehow store that connection so commands can be sent to it in the future (Without having to connect & authenticate again)
Below is the code I have that works for a single server. I store the TcpClient(client) & NetworkStream(stm) as global objects which keeps the connection/session open to the server. What is the best method for me to do this with multiple servers since each server will have it's own TcpClient & NetworkStream?
Is there some way for me to store each TcpClient(client) & NetworkStream(stm) in an array, dictionary or something? I'm completely lost with how to approach this.
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Security.Cryptography
Imports System.IO
Public Class Form1
Public client As TcpClient
Public stm As NetworkStream
Sub SendCmd(cmd As String)
Dim data
If cmd.Trim = "" Then
data = Encoding.GetEncoding(1252).GetBytes(cmd)
Else
data = Encoding.GetEncoding(1252).GetBytes(cmd & vbCrLf)
End If
stm.Write(data, 0, data.Length)
Dim resp As Byte() = New Byte(512) {}
Dim memStream = New MemoryStream()
Thread.Sleep(500)
Dim bytes As Integer = 0
If stm.DataAvailable Then
Do
Thread.Sleep(10)
bytes = stm.Read(resp, 0, resp.Length)
memStream.Write(resp, 0, bytes)
Loop While stm.DataAvailable
Dim responsedata As String = Encoding.GetEncoding(1252).GetString(memStream.ToArray())
If responsedata.Contains("### Digest seed: ") Then
'The server is asking for authentication: Login to the server now
Authenticate(responsedata)
End If
OutputRTB.Text &= responsedata
End If
memStream.Close()
End Sub
Sub GetPlayerList()
If stm.CanRead Then
Dim data = Encoding.GetEncoding(1252).GetBytes("bf2cc pl" & vbCrLf)
Dim PlayerDT As New DataTable
PlayerDT.Columns.Add("PlayerSlot", GetType(Integer))
PlayerDT.Columns.Add("HeroName", GetType(String))
PlayerDT.Columns.Add("Score", GetType(String))
PlayerDT.Columns.Add("HeroID", GetType(String))
PlayerDT.Columns.Add("PlayerID", GetType(String))
PlayerDT.Columns.Add("Level", GetType(Integer))
PlayerDT.Columns.Add("Class", GetType(String))
PlayerDT.Columns.Add("Ping", GetType(Integer))
stm.Write(data, 0, data.Length)
Dim resp As Byte() = New Byte(512) {}
Dim memStream = New MemoryStream()
Thread.Sleep(500)
Dim bytes As Integer = 0
If stm.DataAvailable Then
Do
Thread.Sleep(10)
bytes = stm.Read(resp, 0, resp.Length)
memStream.Write(resp, 0, bytes)
Loop While stm.DataAvailable
Dim responsedata As String = Encoding.GetEncoding(1252).GetString(memStream.ToArray())
If responsedata.Contains("### Digest seed: ") Then
'Login to the server
Authenticate(responsedata)
End If
OutputRTB.Text = responsedata.Replace(vbTab, "^")
Dim Rows() As String = responsedata.Split(Environment.NewLine)
For i = 0 To Rows.Length - 1
Dim Cols() As String = Rows(i).Split(vbTab)
If Cols.Length > 40 Then
PlayerDT.Rows.Add(Cols(0).ToString(), Cols(1).ToString(), Cols(37).ToString(), Cols(10).ToString(), Cols(47).ToString(), Cols(39).ToString(), Cols(34).ToString(), Cols(3).ToString)
End If
Next
End If
DataGridView1.DataSource = PlayerDT
DataGridView1.Update()
memStream.Close()
End If
End Sub
Sub Authenticate(ByVal rdata As String)
Dim DigestKeyStart As Integer = rdata.LastIndexOf(":") + 2
Dim DigestKeyLen As Integer = 16
Dim PWResponse As String = rdata.Substring(DigestKeyStart, DigestKeyLen) & PassTXT.Text
PWResponse = "login " & GenerateHash(PWResponse)
SendCmd(PWResponse)
End Sub
Private Function GenerateHash(ByVal SourceText As String) As String
Dim objMD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim arrData() As Byte
Dim arrHash() As Byte
' first convert the string to bytes (using UTF8 encoding for unicode characters)
arrData = System.Text.Encoding.UTF8.GetBytes(SourceText)
' hash contents of this byte array
arrHash = objMD5.ComputeHash(arrData)
' thanks objects
objMD5 = Nothing
' return formatted hash
Return ByteArrayToString(arrHash)
End Function
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
Dim strOutput As New System.Text.StringBuilder(arrInput.Length)
For i As Integer = 0 To arrInput.Length - 1
strOutput.Append(arrInput(i).ToString("X2"))
Next
Return strOutput.ToString().ToLower
End Function
Private Sub Form1_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
stm.Close()
client.Close()
End Sub
Private Sub ConnectBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectBTN.Click
client = New TcpClient(ServerIPTXT.Text, PortTXT.Text)
stm = client.GetStream()
SendCmd(CommandTXT.Text)
End Sub
Private Sub SendCommandBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendCommandBTN.Click
SendCmd(CommandTXT.Text)
End Sub
Private Sub GetPlayerListBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetPlayerListBTN.Click
GetPlayerList()
End Sub
End Class
BTW This is my first post on stackoverflow, but I have learned so much from this site over the years =)

Resources