I have this function which return all TCP connections for all proccess
Declare Auto Function GetExtendedTcpTable Lib "iphlpapi.dll" (ByVal pTCPTable As IntPtr, ByRef OutLen As Integer, ByVal Sort As Boolean, ByVal IpVersion As Integer, ByVal dwClass As Integer, ByVal Reserved As Integer) As Integer
Const TCP_TABLE_OWNER_PID_ALL As Integer = 5
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPTABLE_OWNER_PID
Public NumberOfEntries As Integer 'number of rows
Public Table As IntPtr 'array of tables
End Structure
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPROW_OWNER_PID
Public state As Integer 'state of the connection
Public localAddress As UInteger
Public LocalPort As Integer
Public RemoteAddress As UInteger
Public remotePort As Integer
Public PID As Integer 'Process ID
End Structure
Structure TcpConnection
Public State As TcpState
Public localAddress As String
Public LocalPort As Integer
Public RemoteAddress As String
Public remotePort As Integer
Public Proc As String
End Structure
Function GetAllTCPConnections() As MIB_TCPROW_OWNER_PID()
GetAllTCPConnections = Nothing
Dim cb As Integer
GetExtendedTcpTable(Nothing, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0)
Dim tcptable As IntPtr = Marshal.AllocHGlobal(cb)
If GetExtendedTcpTable(tcptable, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0) = 0 Then
Dim tab As MIB_TCPTABLE_OWNER_PID = Marshal.PtrToStructure(tcptable, GetType(MIB_TCPTABLE_OWNER_PID))
Dim Mibs(tab.NumberOfEntries - 1) As MIB_TCPROW_OWNER_PID
Dim row As IntPtr
For i As Integer = 0 To tab.NumberOfEntries - 1
row = New IntPtr(tcptable.ToInt32 + Marshal.SizeOf(tab.NumberOfEntries) + Marshal.SizeOf(GetType(MIB_TCPROW_OWNER_PID)) * i)
Mibs(i) = Marshal.PtrToStructure(row, GetType(MIB_TCPROW_OWNER_PID))
Next
GetAllTCPConnections = Mibs
End If
Marshal.FreeHGlobal(tcptable)
End Function
Function MIB_ROW_To_TCP(ByVal row As MIB_TCPROW_OWNER_PID) As TcpConnection
Dim tcp As New TcpConnection
tcp.State = DirectCast(row.state, TcpState) 'a State enum is better than an int
Dim ipad As New IPAddress(row.localAddress)
tcp.localAddress = ipad.ToString
tcp.LocalPort = row.LocalPort / 256 + (row.LocalPort Mod 256) * 256
ipad = New IPAddress(row.RemoteAddress)
tcp.RemoteAddress = ipad.ToString
tcp.remotePort = row.remotePort / 256 + (row.remotePort Mod 256) * 256
Dim p As Process = Process.GetProcessById(row.PID)
tcp.Proc = p.ProcessName
p.Dispose()
Return tcp
End Function
I wan't to store only the out going connections of certain processes in a text file so I used
Sub main()
For Each Row In GetAllTCPConnections()
Dim Tcp As TcpConnection = MIB_ROW_To_TCP(Row)
Dim RemoteAddress As String = Tcp.RemoteAddress.ToString
Dim process As String = Tcp.Proc
If (process = "chrome" Or process = "Viber" Or process = "ddns") And (RemoteAddress <> "127.0.0.1") And (RemoteAddress <> "0.0.0.0") Then
Dim myFile As String = "C:\TCP.txt"
Using sw As StreamWriter = New StreamWriter(myFile)
Dim line As String = Tcp.RemoteAddress & "|" & Tcp.localAddress & "|" & Tcp.LocalPort & "|" & Tcp.Proc
sw.WriteLine(line)
MsgBox(line)
End Using
End If
Next
End Sub
msgbox works fine showing every process and out going connections that established by it but when I open
TCP.txt
file I only find one line.
So how to write the entire results (Each process with its out going connections) to the text file?
You need to set the append to text file.
You need to change:
Using sw As StreamWriter = New StreamWriter(myFile)
To
Using sw As StreamWriter = New StreamWriter(myFile, True)
By setting the true you set the append to file to true
Related
I'm scanning some text in the screen using Windows.Media.Ocr under a timer control, firing the tick event every 200 ms.
I'm then displaying the output in a richtextbox that is unfortunately flickering..
I made a gif to show the issue ( the ocr is on purpose scanning just the values with M)
is there any way to stop this behavior? Thanks
The code I'm using inside of the timer is:
Dim softwareBmp As Windows.Graphics.Imaging.SoftwareBitmap
Using bmp As Bitmap = New Bitmap(PictureBox1.Width, PictureBox1.Height)
Using g As Graphics = Graphics.FromImage(bmp)
Dim pt As Point = Me.PointToScreen(New Point(PictureBox1.Left, PictureBox1.Top))
g.CopyFromScreen(pt.X, pt.Y, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy)
Using memStream = New Windows.Storage.Streams.InMemoryRandomAccessStream()
bmp.Save(memStream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp)
Dim decoder As Windows.Graphics.Imaging.BitmapDecoder = Await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memStream)
softwareBmp = Await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore)
End Using
End Using
End Using
Dim ocrEng = OcrEngine.TryCreateFromLanguage(New Windows.Globalization.Language("en-US"))
Dim languages As IReadOnlyList(Of Windows.Globalization.Language) = ocrEng.AvailableRecognizerLanguages
For Each language In languages
Console.WriteLine(language.LanguageTag)
Next
Dim r = ocrEng.RecognizerLanguage
Dim n = ocrEng.MaxImageDimension
Dim ocrResult = Await ocrEng.RecognizeAsync(softwareBmp)
RichTextBox1.Clear()
Dim wordList As List(Of cText) = New List(Of cText)()
Dim lines As IReadOnlyList(Of OcrLine) = ocrResult.Lines
For Each line In lines
For Each word In line.Words
Dim nY As Double = CLng(word.BoundingRect.Bottom / 10) * 10
wordList.Add(New cText() With {.Text = word.Text, .LocY = nY, .LocX = word.BoundingRect.Left})
Next
Next
wordList.Sort(New WordComparer())
Dim oldLocY As Double = 0
For Each item As cText In wordList
If (item.LocY > oldLocY And oldLocY <> 0) Then
RichTextBox1.Text += Environment.NewLine
End If
RichTextBox1.Text += (item.Text + " ")
oldLocY = item.LocY
Next
I solved using WM_SETREDRAW
<DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
End Function
Public Const WM_SETREDRAW As Integer = &HB
Before adding lines (before RichTextBox1.Clear())
If (RichTextBox1.IsHandleCreated) Then
SendMessage(RichTextBox1.Handle, WM_SETREDRAW, 0, IntPtr.Zero)
End If
After lines have been added :
If (RichTextBox1.IsHandleCreated) Then
SendMessage(RichTextBox1.Handle, WM_SETREDRAW, 1, IntPtr.Zero)
RichTextBox1.Invalidate()
End If
I'm trying get a displayversion for a specific program in uninstall registry path. I can get it from a direct path or get the whole uninstall listed, but I cannot get it to find a specific program based on displayname and returns displayversion. Thank you if you can help or provide instruction.
Public Function GetDisplayLink() As String
On Error Resume Next
Dim strRegPath As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{772811A3-D34B-4594-AF3E-A7C655013E62}\"
Dim regVersion64 As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, strWorkstation, Microsoft.Win32.RegistryView.Registry64).OpenSubKey(strRegPath)
Dim strDisplayLink As String = regVersion64.GetValue("DisplayVersion")
GetDisplayLink = "DisplayLink Driver|" & strDisplayLink & "<BR>"
regVersion64 = Nothing
End Function
I cannot get it to find a specific program based on displayname and
returns displayversion.
There are several ways (WMI, Shell, Msi, ...)
WMI is the simplest one but slow
A sample with Msi, test with "Microsoft Silverlight" on Windows 10 =>
Dim sProductName As String = "Microsoft Silverlight"
Dim nResult As UInteger = 0
Dim sProductCode As StringBuilder = New StringBuilder(256)
Dim nIndex As Integer = 0
Do While (True)
nResult = MsiEnumProducts(nIndex, sProductCode)
If (nResult <> 0) Then
Exit Do
End If
Dim nSize As Integer = 256
Dim sbProductName As StringBuilder = New StringBuilder(nSize)
nResult = MsiGetProductInfo(sProductCode.ToString(), "InstalledProductName", sbProductName, nSize)
If (sbProductName.ToString() = sProductName) Then
nSize = 256
Dim sbVersionString As StringBuilder = New StringBuilder(nSize)
nResult = MsiGetProductInfo(sProductCode.ToString(), "VersionString", sbVersionString, nSize)
Console.WriteLine("Product: {0}", sProductName)
Console.WriteLine(vbTab + "Code: {0}", sProductCode.ToString())
Console.WriteLine(vbTab + "Version: {0}", sbVersionString.ToString())
Exit Do
End If
nIndex += 1
Loop
With declarations :
<DllImport("Msi.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function MsiEnumProducts(iProductIndex As Integer, lpProductBuf As StringBuilder) As UInteger
End Function
<DllImport("Msi.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function MsiGetProductInfo(szProduct As String, szAttribute As String, lpValueBuf As StringBuilder, ByRef pcchValueBuf As Integer) As UInteger
End Function
Please see the code below:
Private Shared ReadOnly log As ILog = LogManager.GetLogger(GetType(ScheduledTasks))
Private Shared TestString As String = ""
Public Shared Sub writeConsole(ByVal i As Integer)
System.Threading.Thread.Sleep(1000)
TestString = TestString & i
End Sub
Public Shared Sub ParallelTest()
Dim int1 As Integer = 1, int2 As Integer = 2, int3 As Integer = 3, int4 As Integer = 4, int5 As Integer = 5, int6 As Integer = 6, int7 As Integer = 7, int8 As Integer = 8, int9 As Integer = 9, int10 As Integer = 10
Dim list As List(Of Integer) = New List(Of Integer)
list.Add(int1)
list.Add(int2)
list.Add(int3)
list.Add(int4)
list.Add(int5)
list.Add(int6)
list.Add(int7)
list.Add(int8)
list.Add(int9)
list.Add(int10)
Dim ParallelOptions As ParallelOptions = New ParallelOptions
ParallelOptions.MaxDegreeOfParallelism = 1 ' Environment.ProcessorCount * 10
Parallel.ForEach(Of Integer)(list.AsEnumerable(),
Sub(test As Integer)
writeConsole(test)
End Sub)
MsgBox("got here")
When the code reaches the message box, TestString contains the following value: 16237594810. I would expect it to be: 12345678910. It seems to indicate that multiple threads are being used even though MaxDegreeOfParallelism is set to: 1. Why is this?
I am writing a script for setting static ip to computers. it reads a file that has mac addr - ip addr pair. based on the computers mac address it gets its ip address from the file. I have problem setting this up. I have never done any kind of .net programming. I wrote a bashscript for linux side which works, but for windows I don't have any experience. I wrote the program in vb.net. Until now the program can get the data from the file, now I have to set static ip based on the mac address and also hostname. there were several different posts 1, 2, but they were all in c# ,and have problem converting them to VB.Net. It would be great if someone could provide a pointer on how to Set Static IP address for a specific NIC on local computer.
Imports System
Imports System.Text.RegularExpressions
Imports System.Net.NetworkInformation
Imports System.IO
Imports System.Management
Module Module1
Const FAILURE = 1
Const SUCCESS = 0
Dim phyAddr As String = getMAC()
Sub Main()
Dim arguments(3) As String
Dim fileName As String = ""
If Environment.GetCommandLineArgs.Count = 3 Then
arguments = Environment.GetCommandLineArgs
fileName = arguments(2)
Else
Console.WriteLine("Wrong Syntax!")
help()
Console.Read()
close(FAILURE)
End If
If validName(fileName) Then
If fileExists(fileName) Then
'search file for ip
Dim confData As String = searchFile(phyAddr, fileName)
If Not String.IsNullOrEmpty(confData) Then
Dim netConf() As String = splitLine(confData)
Dim hostName As String = netConf(1)
Dim ipAddr As String = netConf(2)
Dim netMask As String = netConf(3)
Dim gateway As String = netConf(4)
Dim dns1 As String = netConf(5)
Dim dns2 As String = netConf(6)
Else
Console.WriteLine("Couldn't find MAC {0} in file {1}", phyAddr, fileName)
Console.Read()
close(FAILURE)
End If
Else
Console.WriteLine("File {0} doesn't exist", fileName)
Console.WriteLine("Please provide an absolute path to file")
Console.Read()
close(FAILURE)
End If
Else
Console.WriteLine("File name {0} not recognized", fileName)
Console.Read()
close(FAILURE)
End If
End Sub
Private Sub help()
Console.WriteLine("Please call program as: ")
Console.WriteLine("networkconfiguration -f datafile")
End Sub
Private Sub close(exitCode As Integer)
Environment.Exit(exitCode)
End Sub
Private Function validName(name As String) As Boolean
Static fileNameExpression As New Regex("^[\\:_a-zA-Z0-9.]+")
Return fileNameExpression.IsMatch(name)
End Function
Private Function fileExists(name As String) As Boolean
Return My.Computer.FileSystem.FileExists(name)
End Function
Private Function getMAC() As String
Dim nic As NetworkInterface
Dim result As String = String.Empty
For Each nic In NetworkInterface.GetAllNetworkInterfaces()
If nic.Name.Contains("Ethernet0") Then
result = nic.GetPhysicalAddress.ToString
Exit For
End If
Next
Return result
End Function
Private Function searchFile(keyword As String, fileName As String) As String
'store result
Dim result As String = String.Empty
'search for keyword in returned data
Using reader As New StreamReader(fileName)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If line.Contains(keyword) Then
result = line
Exit While
End If
End While
End Using
Return result
End Function
Private Function splitLine(line As String) As String()
Dim separator As Char = ";"
Return line.Split(separator)
End Function
Private Function setupNetwork(ipAddr As String, netmask As String, gateway As String, dns1 As String, dns2 As String) As Boolean
Dim mc As New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As New ManagementObjectCollection
Dim mo As ManagementObject
moc = mc.GetInstances()
For Each mo In moc
'make sure this is ipenabled device
'not something like memory card or VMWare
Next
End Function
End Module
Ok solved it. I will just post my answer here so others might benefit.
' set the network configuration of a computer
Function setupNetwork(phyAddr As String, ipAddr As String, netmask As String, gateway As String, dns1 As String, dns2 As String) As Boolean
Dim result As Boolean = False
' concatenate two dns addresses into one
Dim dnsSearchOrder As String = dns1 + "," + dns2
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (CBool(objMO("IPEnabled"))) Then
' remove colons from mac address so that it could match the
' provided mac address
Dim origMAC As String = objMO("MacAddress").ToString()
Dim pattern As String = ":"
Dim replacement As String = ""
Dim rgx As New Regex(pattern)
' the mac address with colons removed from it
Dim repMAC As String = rgx.Replace(origMAC, replacement)
If (String.Equals(phyAddr, repMAC)) Then
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
'set defaultgateway
objNewGate("DefaultIPGateway") = New String() {gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'set ipaddress and subnetmask
objNewIP("IPAddress") = New String() {ipAddr}
objNewIP("SubnetMask") = New String() {netmask}
objNewDNS("DNSServerSearchOrder") = dnsSearchOrder.Split(",")
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, Nothing)
result = True
Exit For
Catch ex As Exception
Console.WriteLine("Couldn't Set IP Address!")
Console.Read()
close(FAILURE)
End Try
End If
End If
Next
Return result
End Function
'set computers host name
Private Function setHostname(hostname As String) As Boolean
Dim result As Boolean = False
Dim path As New ManagementPath
path.Server = System.Net.Dns.GetHostName
path.NamespacePath = "root\CIMV2"
path.RelativePath = "Win32_Computersystem.Name='" & path.Server & "'"
Dim objMO As New ManagementObject(path)
Dim params() As Object = {hostname}
objMO.InvokeMethod("Rename", params)
result = True
Return result
End Function
I need to generate a lot of random 2 character strings for my application. it's a VB console application. basically what I have tried for random strings is this:
Private Function GenerateRandomString(ByVal intLenghtOfString As Integer) As String
'Create a new StrinBuilder that would hold the random string.
Dim randomString As New StringBuilder
'Create a new instance of the class Random
Dim randomNumber As Random = New Random
'Create a variable to hold the generated charater.
Dim appendedChar As Char
'Create a loop that would iterate from 0 to the specified value of intLenghtOfString
For i As Integer = 0 To intLenghtOfString
'Generate the char and assign it to appendedChar
appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65)
'Append appendedChar to randomString
randomString.Append(appendedChar)
Next
'Convert randomString to String and return the result.
Return randomString.ToString()
End Function
AND THIS:
Private Function RandomStringGenerator(ByVal intLen As Integer) As String
Dim r As New Random()
Dim i As Integer
Dim strTemp As String = ""
For i = 0 To intLen
strTemp = strTemp & Chr(Int((26 * r.NextDouble()) + 65))
Next
Return r.Next
End Function
But when run, it displays something like this:
SR
SR
SR
SR
SR
SR
SR
SR
SR
SR
BR
BR
BR
BR
BR
BR
BR
KR
KR
KR
KR
and so on.
What is going on? I thought that I used to, a long time ago, be able to just do random.Next.
I've run into similar issues before with the Random object. The problem is that when you instantiate Random it's default seed value is the number of milliseconds since windows started up. And since you are generating random characters at several a millisecond you end up with the same seed number.
Instead you should create a shared random object instead of instantiating a new one on each call.
In another forum I answered a similar question and came up with this generalized function that could be used for your problem. It includes a metric that can be examined to see if there is a bias in the characters being generated.
Dim charUC As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim charLC As String = charUC.ToLower
Dim charNUM As String = "0123456789"
Dim charSPEC As String = "``!##$%^&*()-_=+[{]}\|;:',<.>/?" & ControlChars.Quote
Dim charCounts As New Dictionary(Of Char, Integer)
Dim PRNG As New Random 'note - defined at class level
Private Function GetRandChars(ByVal numChars As Integer, _
Optional ByVal includeUpperCase As Boolean = False, _
Optional ByVal includeLowerCase As Boolean = False, _
Optional ByVal includeNumbers As Boolean = False, _
Optional ByVal includeSpecial As Boolean = False) As String
If numChars <= 0 Then Throw New ArgumentException 'must specify valid character count
Dim includeSel As New System.Text.StringBuilder 'contains set of characters
If includeUpperCase Then includeSel.Append(charUC) 'UC to set
If includeLowerCase Then includeSel.Append(charLC) 'LC to set
If includeNumbers Then includeSel.Append(charNUM) 'numbers to set
If includeSpecial Then includeSel.Append(charSPEC) 'specials to set
If includeSel.Length = 0 Then Throw New ArgumentException 'must tell function at least one include
Dim rv As New System.Text.StringBuilder 'return value
'generate specified number of characters
For ct As Integer = 1 To numChars
Dim chSel As Char = includeSel(PRNG.Next(includeSel.Length)) 'select random character
rv.Append(chSel)
'do counts
If charCounts.ContainsKey(chSel) Then
charCounts(chSel) += 1
Else
charCounts.Add(chSel, 1)
End If
Next
Return rv.ToString 'return the random string
End Function