make command line with arguments - vb.net

I have textbox1.text and it has the user input text.
There are the main command and such. One of them is ip
If the user types ip local I want it to display the local ip, which I already have the code for
Another example would be ping google.com 1000 It would ping google for 1000MS, again I already have the code for it, but how would I get the 1000 or what if it wasn't there? it would just ping it once. I don't want an error to pop up.
code:
Dim text As String = TextBox1.Text
server.Start()
If text.StartsWith("ip") And text.EndsWith(" local") Then
response = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList(0).ToString()
end if

I Believe you want something like this instead:
Dim array() As String = TextBox1.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Dim cmd as String = array(0).ToUpper()
If cmd = "IP" Then
IpConfig array
Else If cmd = "PING" Then
Ping array
End If
Next add each command as a Sub or Function or whatever....
Public Sub IpConfig( byVal array() as String)
' your code
End Sub
More commands.....

Related

Vb.NET Device Unique Identifier Win10

I'm trying to get a Device Unique Identifier in vb.net code. I have tried with
Private Function SystemSerialNumber() As String
Dim value As String = ""
Dim baseBoard As ManagementClass = New ManagementClass("Win32_BaseBoard")
Dim board As ManagementObjectCollection = baseBoard.GetInstances()
If board.Count > 0 Then
value = board(0)("SerialNumber")
If value.Length > 0 Then value = value.Substring(2)
End If
Return value
End Function
Which works on some computers but of the board doesn't have a serial number it returns "Default String" or whatever they put in there. Even tried with Win32_Processor and some have it and others just return "To be filled by O.E.M" lol
Also tried with,
Private Function SystemSerialNumber() As String
Dim value As String
Dim q As New SelectQuery("Win32_bios")
Dim search As New ManagementObjectSearcher(q)
Dim info As New ManagementObject
For Each info In search.Get
value = info("SerialNumber").ToString
Return value
Next
End Function
But its the same some devices have it some don't and just returns default string.
So I'm now trying is:
Private Function SystemSerialNumber() As String
Dim value As String
value = Windows.System.Profile.SystemIdentification.GetSystemIdForPublisher()
End Function
But I'm having trouble referencing to it. I tried Imports Windows.System but it just gives the error it cant be found.
As a side note I'm using this program in tablets with windows10, laptops, and desktops.
UPDATE: I'll be using as suggested by Heinzi. Thanks!
Also changed variable names to be more accurate.
Private Function NetworkAdapterMacAddress() As String
Dim McAddress As String
Dim netadapter As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim mo As ManagementObject
Dim adapter As ManagementObjectCollection = netadapter.GetInstances()
For Each mo In adapter
If mo.Item("IPEnabled") = True Then
McAddress = mo.Item("MacAddress").ToString()
Return McAddress
End If
Next
End Function
Well, there is no guaranteed ID that identifies every PC out there uniquely (fortunately, I might add. Privacy is a good thing).
You best bets are probably
the MAC of the network adapter (changes when the network adapter is replaced) or
the Windows Computer SID (changes when Windows is reinstalled).
Oh, and on a philosophical note, you might want to ponder on the Ship of Theseus.

how to get windows version for remote computer using code

I'm developing small app using visual studio 2013, VB to scan range of IP addresses in same network
my app will take IP's and return
Ping status (True or False)
Computer Name
MAC address
and all OK
my question is if i need to get remote computer windows (xp or 7 or 8 )
using IP address or computer name how i can do that?
Dim osVer As String
osVer = System.Environment.OSVersion.ToString
Finally I used system management as below
(after importing System.Management)
I used two Functions
first one to connect remote Computer then collect data
Private Function tryConnect(SystemName As String)
Try
Dim ComputerConnection As New System.Management.ConnectionOptions
' to add user name and password
'ComputerConnection.Username = "UserName"
'ComputerConnection.Password = "Password"
With ComputerConnection
.Impersonation = System.Management.ImpersonationLevel.Impersonate
.Authentication = System.Management.AuthenticationLevel.Packet
End With
'connect to WMI
MyMgtScope = New System.Management.ManagementScope("\\" & SystemName & "\root\CIMV2", ComputerConnection)
MyMgtScope.Connect()
Return MyMgtScope.IsConnected
Catch ex As Exception
Return False
End Try
End Function
private sub GetOsdata()
if tryConnect(remoteComputerName) = False then Exit Sub ' or show some message
Dim MyMgtScope As System.Management.ManagementScope
Dim MyObjSearcher As System.Management.ManagementObjectSearcher
Dim MyColl As System.Management.ManagementObjectCollection
Dim MyObj As System.Management.ManagementObject
Dim ComputerOSVersion , ComputerOSServiceBack ,OSbit As String
MyObjSearcher = New System.Management.ManagementObjectSearcher(MyMgtScope.Path.ToString, "Select * FROM Win32_OperatingSystem")
' Execute the query
MyColl = MyObjSearcher.Get
For Each MyObj In MyColl
ComputerOSVersion = MyObj.GetPropertyValue("Caption").ToString
ComputerOSServiceBack = MyObj.GetPropertyValue("ServicePackMajorVersion").ToString
OSbit = MyObj.GetPropertyValue("OSArchitecture").ToString
Next
MyObjSearcher = Nothing
MyColl = Nothing
End Sub
Using wClient As New WebClient
dim myip as string = wClient.DownloadString("http://tools.feron.it/php/ip.php")
End Using
maybe help for find ip easly. good luck

how to write to/read from a "settings" text file

I'm working on a Timer program, that allows the user to set up a timer for each individual user account on the computer. I'm having some trouble writing the settings to a text file and reading from it. I want to know if it's possible to write it in this fashion --> username; allowedTime; lastedLoggedIn; remainingTime; <-- in one line for each user, and how would I go about doing that? I also wanted to know if it's possible to alter the text file in this way, in the case that there's already an entry for a user, only change the allowedTime, or the remainingTime, kinda just updating the file?
Also I'm also having trouble being able to read from the text file. First of all I can't figure out how to determine if a selected user is in the file or not. Form there, if the user is listed in the file, how can access the rest of the line, like only get the allowedTime of that user, or the remaining time?
I tried a couple of ways, but i just can't get it to do how I'm imaging it, if that makes sense.
here's the code so far:
Public Sub saveUserSetting(ByVal time As Integer)
Dim hash As HashSet(Of String) = New HashSet(Of String)(File.ReadAllLines("Settings.txt"))
Using w As StreamWriter = File.AppendText("Settings.txt")
If Not hash.Contains(selectedUserName.ToString()) Then
w.Write(selectedUserName + "; ")
w.Write(CStr(time) + "; ")
w.WriteLine(DateTime.Now.ToLongDateString() + "; ")
Else
w.Write(CStr(time) + "; ")
w.WriteLine(DateTime.Now.ToLongDateString() + "; ")
End If
End Using
End Sub
Public Sub readUserSettings()
Dim currentUser As String = GetUserName()
Dim r As List(Of String) = New List(Of String)(System.IO.File.ReadLines("Settings.txt"))
'For Each i = 0 to r.lenght - 1
'Next
'check to see if the current user is in the file
MessageBox.Show(r(0).ToString())
If r.Contains(selectedUserName) Then
MessageBox.Show(selectedUserName + " is in the file.")
'Dim allowedTime As Integer
Else
MessageBox.Show("the user is not in the file.")
End If
'if the name is in the file then
'get the allowed time and the date
'if the date is older than the current date return the allowed time
'if the date = the current date then check thhe remaning time and return that
'if the date is ahead of the current date return the reamining and display a messgae that the current date needs to be updated.
End Sub
edit: I just wanted to make sure if I'm doing the serialization right and the same for the deserialization.
this is what i got so far:
Friend userList As New List(Of Users)
Public Sub saveUserSetting()
Using fs As New System.IO.FileStream("Settings.xml", IO.FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs, userList)
End Using
End Sub
Public Sub readUserSettings()
Dim currentUser As String = GetUserName()
Dim useList As New List(Of Users)
Using fs As New System.IO.FileStream("Settings.xml", IO.FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
useList = bf.Deserialize(fs)
End Using
MessageBox.Show(useList(0).ToString)
End Sub
<Serializable>
Class Users
Public userName As String
Public Property allowedTime As Integer
Public Property lastLoggedInDate As String
Public Property remainingTime As Integer
Public Overrides Function ToString() As String
Return String.Format("{0} ({1}, {2}, {3})", userName, allowedTime, lastLoggedInDate, remainingTime)
End Function
End Class
edit 2:
I'm not too familiar with try/catch but would this work instead?
Public Sub readUserSettings()
If System.IO.File.Exists("Settings") Then
Using fs As New System.IO.FileStream("Settings", FileMode.Open, FileAccess.Read)
Dim bf As New BinaryFormatter
userList = bf.Deserialize(fs)
End Using
Else
MessageBox.Show("The setting file doesn't exists.")
End If
End Sub
You have a few typos and such in your code, but it is pretty close for your first try:
Friend userList As New List(Of Users)
Public Sub saveUserSetting()
' NOTE: Using the BINARY formatter will write a binary file, not XML
Using fs As New System.IO.FileStream("Settings.bin", IO.FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs, userList)
End Using
End Sub
Public Sub readUserSettings()
' this doesnt seem needed:
Dim currentUser As String = GetUserName()
' do not want the following line - it will create a NEW
' useRlist which exists only in this procedure
' you probably want to deserialize to the useRlist
' declared at the module/class level
' Dim useList As New List(Of Users)
' a) Check if the filename exists and just exit with an empty
' useRlist if not (like for the first time run).
' b) filemode wass wrong - never create here, just read
Using fs As New System.IO.FileStream("Settings.bin",
FileMode.Open, FileAccess.Read)
Dim bf As New BinaryFormatter
' user list is declared above as useRList, no useList
useList = bf.Deserialize(fs)
End Using
' Console.WriteLine is much better for this
MessageBox.Show(useList(0).ToString)
End Sub
<Serializable>
Class Users
' I would make this a property also
Public userName As String
Public Property allowedTime As Integer
Public Property lastLoggedInDate As String
Public Property remainingTime As Integer
Public Overrides Function ToString() As String
Return String.Format("{0} ({1}, {2}, {3})", userName, allowedTime, lastLoggedInDate, remainingTime)
End Function
End Class
ToDo:
a) decide whether you want XML or binary saves. With XML, users can read/edit the file.
b) Use a file path created from Environment.GetFolder(); with a string literal it may end up in 'Program Files' when deployed, and you cannot write there.
c) when reading/loading the useRlist, use something like
FileStream(myUserFile, FileMode.Open, FileAccess.Read)
It wont exist the first time run, so check if it does and just leave the list empty. After that, you just need to open it for reading. For saving use something like:
FileStream(myUserFile, FileMode.OpenOrCreate, FileAccess.Write)
You want to create it and write to it. You might put the Load/Save code inside a Try/Catch so if there are file access issues you can trap and report them, and so you know the list did not get saved or read.
Using a serializer, the entire contents of the list - no matter how long - will get saved with those 3-4 lines of code, and the entire list read back in the 2-3 lines to load/read the file.
I don't have the answer to all your questions however I've been also working on a timer application and just recently started using text file to read and write information. The method I'm using has proven itself fairly easy to use and not very confusing. Here is an extract of my code:
Dim startup As String = "C:\Users\DigiParent\Desktop\Project data\Digitimeinfo.txt"
Dim reader As New System.IO.StreamReader(startup, Encoding.Default)
Dim data As String = reader.ReadToEnd
Dim aryTextFile(6) As String
aryTextFile = data.Split(",")
This will read everything in the text file and in sort separate everything in between the , and store them individual in the array. To put the code back in one line use
Dim LineOfText As String
LineOfText = String.Join(",", aryTextFile)
so you could write someting like this to write your info to a text file:
Dim startup As String = "C:\Users\DigiParent\Desktop\Project data\Digitimeinfo.txt"
Dim objWriter As New System.IO.StreamWriter(startup, False)
Dim aryTextFile(2) As String
aryTextFile(0) = pasword
aryTextFile(1) = user
aryTextFile(2) = remainingtime
LineOfText = String.Join(",", aryTextFile)
objWriter.WriteLine(LineOfText)
objWriter.Close()
and to read it you could use steam reader.

Hex Edit with BinaryWriter (VB.NET)

I'm opening an .exe file in Hex Workshop, and I want to edit this line:
How is that possible with VB.NET using a BinaryWriter? The line represents the IP of the exe. I want to have a program that includes a textbox where you put the new IP. So, I have so far:
Using writer As BinaryWriter = New BinaryWriter(File.Open("C:\localhost.exe", FileMode.Open))
writer.BaseStream.Position = ???
writer.write???
End Using
So, what position do I set it to, and what type do I write? Bytes? Thanks.
Find the offset of the first character in your string and use this method:
Private Sub Patch(ByVal TargetFile As String, ByVal FileOffset As Long, ByVal NewValue() As Byte)
Try
Dim br As BinaryReader = New BinaryReader(File.Open(TargetFile, FileMode.Open))
br.BaseStream.Position = FileOffset
Dim byteB As Byte
For Each byteB In NewValue
If (byteB.ToString <> String.Empty) Then
br.BaseStream.WriteByte(byteB)
Else
Exit For
End If
Next byteB
br.Close()
Catch
End Try
End Sub
Like this:
Patch("C:\localhost.exe", Val("OFFSET OF FIRST CHARACTER IN STRING"), New Byte() {&H31, &H32, &H37, &H2e, &H30, &H2e, &H30, &H2e, &H38})
Or instead of your byte-array, use this:
System.Text.Encoding.ASCII.GetBytes("127.0.0.8") 'It'll change 127.0.0.1 to 127.0.0.8
Just make sure you have the right offset for the first character of your string

Web Service saving a string value from a function

I was just wondering if a Web Service can save something i send to it as a string without resetting it everytime i call the WS?
<WebMethod()> _
Public Function sendLCDBrightnessLevel(ByRef command As String) As String
'This reads a number for the LCD brightness level and store it
'The phone will call this function every 5 minutes to see what the value is
'android phone->WS
Dim lcdLevel As String = ""
If command <> "READ" Then
lcdLevel = command
Return "Stored: " & lcdLevel
Else
Return lcdLevel
End If
End Function
Would lcdLevel retain the value in command if the app just checks it?
Example:
I send it 30 for the command and since its not READ it stores it in lcdLevel. Once the Android phone gets around to the "every 5 minutes" check, will it read 30 or will it be nothing?
I'm thinking that i need to move Dim lcdLevel As String = "" outside the function since its at the start of the function call each time? Do i just need to place that outside the function in order to keep the value stored or is there something else i also need to do?
Thanks!
<WebMethod()> _
Public Function sendLCDBrightnessLevel(ByRef command As String) As String
'This reads a number for the LCD brightness level and store it
'The phone will call this function every 5 minutes to see what the value is
'android phone->WS
Dim lcdLevel As String = ""
Dim path As String = "c:\temp\lcdValue.txt"
If command <> "READ" Then
lcdLevel = command
Dim objWriter As New System.IO.StreamWriter(path, False, Encoding.UTF8)
objWriter.WriteLine(lcdLevel)
objWriter.Close()
Return "Stored: " & lcdLevel
Else
Dim objReader As New System.IO.StreamReader(path, Encoding.UTF8)
lcdLevel = objReader.ReadToEnd
objReader.Close()
Return lcdLevel
End If
End Function
Guess this is the only way to store a value easily in a WS?
Seems to work as i needed it too.