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
Related
I have this code that starts some threads by iterating through a list of strings and send each one to a Sub which connects to a webservice and waits for a result:
Public Shared Function StartThreading(names As String())
Dim threads As List(Of Thread) = New List(Of Thread)()
For Each name In names
Dim t As Thread = New Thread(New ParameterizedThreadStart(Sub() CallWebService(name)))
threads.Add(t)
Next
For i As Integer = 0 To threads.Count - 1
Dim t = threads(i)
Dim name = names(i)
t.Start(name)
Next
For Each t As Thread In threads
t.Join()
Next
End Function
The Sub for the webservice caller is:
Public Shared Sub CallWebService(inputxml As String)
Dim _url = "http://10.231.58.173:8080/ps/services/ProcessServer?WSDL"
Dim _action = "http://10.231.58.173:8080/ps/services/ProcessServer"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(inputxml)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, _action)
Dim appPath As String = System.AppDomain.CurrentDomain.BaseDirectory
Dim configpath As String = appPath + "\Config.ini"
Dim configdata As IniData = Functii.ReadIniFile(configpath)
Dim outputxmlsave = configdata("PATHS")("OUTPUTXML")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using rd As StreamReader = New StreamReader(webResponse.GetResponseStream())
soapResult = rd.ReadToEnd()
End Using
File.WriteAllText(outputxmlsave & "\" & "test.xml", soapResult.ToString)
Console.Write(soapResult)
End Using
End Sub
How can I know that all threads are done successfully or not? Is there something I can use to return a True value if they are all done?
I have a Public class with a Public Shared Dictionary in vb.net. The constructor does not seem to be running. I have a breakpoint in the constructor which does not break. Also when I make a database update, the new values do not show up in the dictionary.
Public Class SkywalkerPolicy
Public Shared CustomPolicies As Dictionary(Of String, String)
Shared Sub New()
CustomPolicies = New Dictionary(Of String, String)
Dim bvin As String = String.Empty
Dim title As String = String.Empty
Dim poldescr As String = String.Empty
Dim dtResult As New DataTable("Result")
dtResult.Locale = System.Globalization.CultureInfo.InvariantCulture
Dim request As New DataRequest
request.Command = "sky_PolicyDictionary_s"
request.CommandType = CommandType.StoredProcedure
request.Transactional = False
Dim result As DataSet
result = SqlDataHelper.ExecuteDataSet(request)
If Not result Is Nothing Then
If result.Tables.Count() > 0 Then
dtResult = result.Tables(0)
For Each row In dtResult.AsEnumerable
bvin = row.Item(1)
title = row.Item(0)
poldescr = row.Item(2)
If CustomPolicies.ContainsKey(title) Then
CustomPolicies(title) += poldescr
Else
CustomPolicies.Add(title, poldescr)
End If
Next
End If
End If
End Sub
End Class
When I access the dictionary, any changes I've made to the data do not show up.
Dim pol As String = SkywalkerPolicy.CustomPolicies("Orders and Shipping Details")
Does anyone have any suggestions as to how I can get the constructor to work?
Or should I have an additional Sub which duplicates initializing the dictionary before I use it?
Thanks
I have a workaround with an Update routine which I call just before accessing the dictionary. But I am still unclear why I can't step through the constructor. So if anyone can answer the original question, I would appreciate an update. Thank you.
Public Class SkywalkerPolicy
Public Shared CustomPolicies As Dictionary(Of String, String)
Shared Sub New()
CustomPolicies = New Dictionary(Of String, String)
Dim bvin As String = String.Empty
Dim title As String = String.Empty
Dim poldescr As String = String.Empty
Dim dtResult As New DataTable("Result")
dtResult.Locale = System.Globalization.CultureInfo.InvariantCulture
Dim request As New DataRequest
request.Command = "sky_PolicyDictionary_s"
request.CommandType = CommandType.StoredProcedure
request.Transactional = False
Dim result As DataSet
result = SqlDataHelper.ExecuteDataSet(request)
If Not result Is Nothing Then
If result.Tables.Count() > 0 Then
dtResult = result.Tables(0)
For Each row In dtResult.AsEnumerable
bvin = row.Item(1)
title = row.Item(0)
poldescr = row.Item(2)
If CustomPolicies.ContainsKey(title) Then
CustomPolicies(title) += poldescr
Else
CustomPolicies.Add(title, poldescr)
End If
Next
End If
End If
End Sub
Public Shared Sub UpdateDictionary()
CustomPolicies.Clear()
Dim bvin As String = String.Empty
Dim title As String = String.Empty
Dim poldescr As String = String.Empty
Dim dtResult As New DataTable("Result")
dtResult.Locale = System.Globalization.CultureInfo.InvariantCulture
Dim request As New DataRequest
request.Command = "sky_PolicyDictionary_s"
request.CommandType = CommandType.StoredProcedure
request.Transactional = False
Dim result As DataSet
result = SqlDataHelper.ExecuteDataSet(request)
If Not result Is Nothing Then
If result.Tables.Count() > 0 Then
dtResult = result.Tables(0)
For Each row In dtResult.AsEnumerable
bvin = row.Item(1)
title = row.Item(0)
poldescr = row.Item(2)
If CustomPolicies.ContainsKey(title) Then
CustomPolicies(title) += poldescr
Else
CustomPolicies.Add(title, poldescr)
End If
Next
End If
End If
End Sub
End Class
I have a situation when I am trying to run a rs.exe to run my report (with parameter).
I am using this bat script below:
"\\server\R\subfolder\working\app\rs.exe" -i \\server\R\subfolder\working\inputfile\coo.rss -s "http://server/ReportServer_MSSQLSERVER2" -v FILENAME="\\server\R\subfolder\working\inputfile\file.csv" -v REPORTSERVER_FOLDER="/FILE_REPORT/FILE" -v Inputfile='DocType' -t -v FORMAT="EXCEL" -e Exec2005
In the above bat script (names coo.bat), I hard coded report parameter (which isInputfile='DocType) and I then referenced this in report service script below:
Public Sub Main()
Dim separators As String = " "
Dim Commands As String = Microsoft.VisualBasic.Command()
DIm inputid As string
Dim args() As String = Commands.Split(separators.ToCharArray)
Dim argcount As Integer = 0
For Each x As String In args
argcount += 1
Next
inputid = args(0).ToUpper
TRY
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER, inputid)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
But, whenever I execute the coo.bat, I keep getting :Unhandled exception:The parameter value provided for 'snapshotID' does not match the parameter type.
I will appreciate your inputs.
I finally found the solution. Please see the edited code
Public Sub Main()
Dim separators As String = " "
Dim Commands As String = Microsoft.VisualBasic.Command()
Dim args() As String = Commands.Split(separators.ToString)
'Report Parameters
Dim parameters(1) As ParameterValue
parameters(0) = New ParameterValue()
parameters(0).Name = "Inputfile"
parameters(0).Value =Inputfile
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER,historyID )
rs.SetExecutionParameters(parameters, "en-us")
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
I am currently making a VB.net console application that calls upon a web based API to get results back into the console.
What I would like to do is allow the user to input the IP themselves.
Dim sURL As String
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1"
I would like to be able to replace the 1.1.1.1 with a user input
Thank you
EDIT:
When I run the program I need to insert the IP twice into the console
Dim nL As String = Environment.NewLine
Console.Write("Please enter an IP Address: ")
Dim input = Console.ReadLine()
This is my code I use to take the user input
EDIT2:
Full Code
Imports System
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
IP:
Dim nL As String = Environment.NewLine
Console.Write("Please enter an IP Address: ")
'Console.WriteLine()
Dim input = Console.ReadLine()
Dim sURL As String
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1".Replace("1.1.1.1", Console.ReadLine())
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Console.ReadLine()
GoTo IP
End Sub
End Module
You should use -
Dim sURL As String
Console.Write("Please enter an IP Address: ")
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1".Replace("1.1.1.1", Console.ReadLine())
When I try to get the phone number of a person from Active Directory, all the properties are loaded but except mail nothing is returned. Can someone please help out in how to retrieve the phone number with some changes in the below code? In myrelustpropcollection.propertynames only 2 is the count ADSPATH and mail. No other property is loaded.
Public Function GetPhoneByName(ByVal Name As String) As String
Dim srch As DirectorySearcher
Dim results As SearchResultCollection = Nothing
Dim phone As Integer
srch = New DirectorySearcher(New DirectoryEntry())
srch.Filter = "(mailnickname=" + Name + ")"
srch.PropertiesToLoad.Add("homephone")
srch.PropertiesToLoad.Add("mail")
srch.PropertiesToLoad.Add("mobile")
srch.PropertiesToLoad.Add("telephoneNumber")
Try
results = srch.FindAll()
Catch ex As Exception
End Try
For Each result In results
Dim myKey As String
Dim myResultPropCollection As ResultPropertyCollection
myResultPropCollection = result.Properties
For Each myKey In myResultPropCollection.PropertyNames
Dim tab1 As String = " "
Dim myCollection As Object
Select Case myKey
Case "mobile" ' Telephone Number
For Each myCollection In myResultPropCollection(myKey)
phone = myCollection.toint
Next myCollection
End Select
Next myKey
Next
Return phone
End Function
This works fine for me and the code is more concise:
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices
Imports System.Collections
Public Function GetPhoneByName(Name As String) As String
Dim ctx As New PrincipalContext(ContextType.Domain, "DomainName")
Dim q As New UserPrincipal(ctx)
q.DisplayName = Name
Dim s As PrincipalSearcher = New PrincipalSearcher(q)
Dim ds As DirectorySearcher = s.GetUnderlyingSearcher
ds.PropertiesToLoad.Clear()
ds.PropertiesToLoad.Add("homephone")
ds.PropertiesToLoad.Add("mail")
ds.PropertiesToLoad.Add("mobile")
ds.PropertiesToLoad.Add("telephoneNumber")
For Each dsResult As SearchResult In ds.FindAll()
For Each itm As DictionaryEntry In dsResult.Properties
Select Case itm.Key
Case "mobile"
Return itm.Value(0)
End Select
Next
Next
Return "Not found"
End Function
The following code will return all values available for the user from the active directory:
Imports System.DirectoryServices
Module AdTest
Sub Main()
GetPhoneByName("Persons Display Name")
Console.ReadLine()
End Sub
Public Sub GetPhoneByName(ByVal Name As String)
Dim srch As New DirectorySearcher(New DirectoryEntry())
srch.Filter = "(displayname=" + Name + ")"
For Each result As SearchResult In srch.FindAll()
For Each key As DictionaryEntry In result.Properties
For Each keyVal In result.Properties(key.Key)
Try
Console.WriteLine(key.Key + ": " + keyVal)
Catch ex As Exception
'value of keyVal could not convert to string (probably byte array)
End Try
Next
Next
Next
End Sub
End Module