String not recognised in for each loop - vb.net

If I do the loop and write "ComputerName" arguments, it displays them so that works!
but when I add the actual code I want it to work with it fails, I don't understand why ?
If I run the loop but hard code the ComputerName variable I'm testing with it works i.e. ComputerName = "computer01"
Imports Microsoft.Win32
Module Module1
Sub Main()
'----------------------------------------------------------------------------------------
'to be tested later
'-------------------
'Dim co As New ConnectionOptions
'co.Impersonation = ImpersonationLevel.Impersonate
'co.Authentication = AuthenticationLevel.PacketPrivacy
'co.EnablePrivileges = True
'co.Username = username
'co.Password = password
'Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
'scope.Connect()
'----------------------------------------------------------------------------------------
For Each ComputerName As String In Environment.GetCommandLineArgs()
Dim uninstallKey As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
'Using rk As RegistryKey = Registry.LocalMachine.OpenSubKey(uninstallKey)
Using rk As RegistryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName, RegistryView.Registry64).OpenSubKey(uninstallKey)
Dim Applications As New List(Of String)()
For Each skName As String In rk.GetSubKeyNames()
Using sk As RegistryKey = rk.OpenSubKey(skName)
If Not CStr(sk.GetValue("DisplayName")) = "" Then
Try
Applications.Add(CStr(sk.GetValue("DisplayName")) & " " & CStr(sk.GetValue("DisplayVersion")))
Catch ex As Exception
Console.WriteLine("!!!!!! error: " & ex.Message)
End Try
End If
End Using
Next
Applications.Sort()
For Each app As String In Applications
Console.WriteLine(app)
Next
End Using
Next ComputerName
Console.Write("Press any key to exit . . .")
Console.ReadLine()
End Sub
End Module

I changed this
Sub Main()
For Each ComputerName As String In Environment.GetCommandLineArgs()
to this
Sub Main(args() As String)
For Each ComputerName As String In args
and that seems to work ? any other \ better way I should do it ?

Related

Create an object in VB.Net to use in VBA

Firstly, I'm quite new to this so be gentle!
I am trying to create a class/object in VB.net for use in vba. I have used Gary Whitcher's code from the bottom of this post:
Sample vb.net code to upload file to Amazon S3 storage
I have created a class in Visual Studio and managed to get it to output a TLB file which i can import to VBA in Excel.
I can then use the object in VBA to create a new folder in the S3 storage system however I am running into problems when using the 'AddFileToFolder' method.
I have had to edit Gary's code a little to get it to compile in VS, the edited version is below.
Imports Amazon.S3
Imports Amazon.S3.Model
Imports Amazon
Imports Amazon.S3.Util
Imports System.Collections.ObjectModel
Imports System.IO
Public Class aws_s3
Const AWS_ACCESS_KEY As String = "AccessKey" 'is set to MY actual key
Const AWS_SECRET_KEY As String = "SecretKey" 'is set to MY actual key
Private Property s3Client As IAmazonS3
Sub New()
Try
s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USEast1)
Catch ex As Exception
End Try
End Sub
Public Function CreateFolder(bucketName As String, folderName() As String) As String
Dim returnval As String = ""
Try
Try
Dim folderKey As String = ""
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
returnval = "Bucket does not exist"
Else
For i = 0 To folderName.Length - 1
folderKey += folderName(i) & "/"
Next
' folderKey = folderKey & "/" 'end the folder name with "/"
Dim request As PutObjectRequest = New PutObjectRequest()
request.BucketName = bucketName
request.StorageClass = S3StorageClass.Standard
request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
' request.CannedACL = S3CannedACL.BucketOwnerFullControl
request.Key = folderKey
request.ContentBody = String.Empty
s3Client.PutObject(request)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval
End Function
Public Function AddFileToFolder(FileName As String, bucketName As String, folderName As String) As String
Dim returnval As String = ""
Try
Try
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
Dim fname() As String = folderName.Split("/")
CreateFolder(bucketName, fname)
Else
Dim path As String = FileName
Dim file As FileInfo = New FileInfo(path)
Dim key As String = String.Format("{0}/{1}", folderName, file.Name)
Dim por As PutObjectRequest = New PutObjectRequest()
por.BucketName = bucketName
por.StorageClass = S3StorageClass.Standard
por.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
por.CannedACL = S3CannedACL.PublicRead
por.Key = key
por.InputStream = file.OpenRead()
s3Client.PutObject(por)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval & " dll"
End Function
End Class
Using VBA, I have created the above object and can successfully execute CreateFolder but when executing addfiletofolder i get the error "Class does not support automation or does not support expected interface"
the VBA code looks like this:
Dim aws As AWS_S3
Dim Result As String
Dim UploadFile As String
UploadFile = "C:\Zipped Builds\Hinchley Legion.zip"
Set aws = New AWS_S3
Dim fld(1) As String
fld(0) = "folder"
fld(1) = "subfolder"
Result = aws.CreateFolder("nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Result = aws.AddFileToFolder(UploadFile, "nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Exit Sub
errHandle:
MsgBox Result
End Sub
I'm guessing from the fact that CreateFolder works fine but AddFileToFolder doesn't, there is a problem in the class as created in VS, missing a dependancy or something?
Thanks Anu6is, that was indeed the problem. The author of the class had wrote the following for usage which had thrown me off:
ADD FILE TO FOLDER
Dim fld(1) As String
fld(0) = <foldername>
fld(1) = <subfoldername>
'List each sub folder as an element in array
Dim rtrn As String = aws.AddFileToFolder(<local file name>,<bucketname>, fld)
I need to get better at reading VB.Net i think! Many thanks for your quick reply, much appreciated.

how to use serial port in a service application environment constantly listening for data

Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,
Application: BondTestService.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException at
System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean
ByRef) at
System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,
Boolean ByRef) at
Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,
System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at
System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at
System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at
System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?
I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?
Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.
Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration
Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10
#Region "Commport Traffic and Configuration Validations"
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
End If
Try
With serialPort
.PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
.BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
.Parity = Parity.None
End If
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
.StopBits = StopBits.One
End If
.DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
.Handshake = Handshake.None
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
.RtsEnable = True
Else
.RtsEnable = False
End If
End With
serialPort.Open()
'debug
'ErrorLog2("Listening to COM 19, SerialPort has been Opened")
Catch ex As Exception
ErrorLog2(Now.ToString & ex.tostring)
End Try
End Sub
Public Function Filelocator() As String
' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
'Dim reader As New System.IO.StreamReader(filePath)
Dim LineNumber = 4
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To LineNumber - 1
If file.ReadLine() Is Nothing Then
ErrorLog2("LineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
ErrorLog2("LineNumber")
End If
Return line
End Using
End Function
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Try
If GetBondInterfaceStatus = 1 Then
UPdateVariable()
Else
exit Sub
End If
Catch ex As Exception
Errorlog2(Ex.Tostring)
End Try
End Sub
#End Region
#Region "String Handling"
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
try
ErrorLog2(now.ToString & RawString.ToString)
InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
RawString.Clear()
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Public Function StringParser(RawString As String)As Double ()
Dim Moisture = RawString
Dim pattern As String = "[0-9],"
Dim regex As New Regex(pattern)
Dim Counter As Integer = 0
Dim dblValues(1) As Double
Dim values As String() = Moisture.Split(New Char() {" "c})
for i = 0 to values.Count - 1
if regex.IsMatch(values(i)) Then
dblValues(Counter) = CDbl(values(i).Substring(0,1))
Counter = Counter + 1
Elseif values(i) = "" Then
continue for
else
if Double.TryParse(values(i), dblValues(Counter)) Then
Counter = Counter + 1
End If
End If
Next
Return dblValues
End Function
#End Region
#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime)"
Try
conn.ExecuteNonQuery(InsertQuery)
IncrementTestPosition
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#RawString") = rawString
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime, #RawString)"
Try
conn.ExecuteNonQuery(InsertQuery)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub IncrementTestPosition()
Dim tempPosition As Integer = GetBondPosition()
Dim FrontOriginalMax = 5
Dim CenterOriginalMax = 15
Dim BackOriginalMax = 25
Dim FrontRetestOrWinderMax = 10
Dim CenterRetestOrWinderMax = 20
Dim BackRetestOrWinderMax = 30
If tempPosition = FrontOriginalMax Then
tempPosition = 11
else if tempPosition = CenterOriginalMax Then
tempPosition = 21
else if tempPosition = BackOriginalMax Then
tempPosition = 1
Else If tempPosition = FrontRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = CenterRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = BackRetestOrWinderMax then
tempPosition = 1
else
tempPosition = tempPosition + 1
End If
SetBondPosition(tempPosition.tostring)
End Sub
#End Region
#Region "Get PiValues"
Private Function GetRecordID() As Int64
Dim RecordID As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return RecordID
End Function
Private Function GetBondPosition() As Int64
Dim BondPos As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return BondPos
End Function
Private Sub SetBondPosition(pos As String)
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Function BondTestType() As String
Dim TestType As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return TestType
End Function
Private Function BondReelLoc() As String
Dim ReelLoc As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return ReelLoc
End Function
Private Function GetBondInterfaceStatus() As Integer
Dim Status As Integer = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return Status
End Function
#End Region
#Region "Debug"
Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
' For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
' Next
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
'For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
'Next
End Using
End If
End Sub
Private Sub ErrorLog2(dataArray as string)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
' Dim TestPos = StartingTestPos
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
End If
End Sub
#End Region
This is a screenshot of the errors:
Thanks in advance
Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.
According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.
Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.
This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.
The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.
Also check your power management settings on your USB port if USB-to-RS232 converter is used. Try to uncheck this option on USB device to which converter is connected.
SW bug in your code.
It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.
Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class
Shared Dim WithEvents serialPort as IO.Ports.SerialPort
and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.

Visual Basic: i have a file containg usernames and passwords but i want to read them back in so the user can log back in

Do
Do
Console.WriteLine("Create a password. It must be 8 characters in length")
password1 = Console.ReadLine()
Loop Until password1.Length = 8
Console.WriteLine("Please re-enter the password.")
password2 = Console.ReadLine()
Loop Until password2 = password1
password = password1
Console.WriteLine("your password has been created.")
Console.ReadLine()
The below code generates the file
Dim fileName = "C:\Users\emily\Documents\Details.csv"
Dim fileAppend As New System.IO.StreamWriter(fileName, True)
fileAppend.WriteLine(name & ", " & age & ", " & username & ", " & password & ", " & yeargroup)
fileAppend.Close()
So basically I have details about the users stored in a csv file. The columns are arranged as follows: name, age, username, password, yeargroup. I need to be able to input a username and for it to be found in the array/list and then input the password and if the password doesn't match for it to start again.
Nice homework. You should think about storing password. Clear text is obviously risky. With the user file load in a table like this will let you manage all of the user. Add,Remove, Change then just save over the userfile.
Public Class Form1
Dim UserTable As New DataTable("UserTable")
Dim SomeUserName As String = "slims"
Dim SomePassword As String = "abc1234!"
Sub ReadUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileReader As New System.IO.StreamReader(fileName)
UserTable.Columns.Add("Name")
UserTable.Columns.Add("Age")
UserTable.Columns.Add("Username")
UserTable.Columns.Add("Password")
UserTable.Columns.Add("YearGroup")
Do Until fileReader.EndOfStream = True
Dim OneLine As String = fileReader.ReadLine()
UserTable.Rows.Add(OneLine.Split(","))
Loop
fileReader.Close()
End Sub
Sub WriteUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileWriter As New System.IO.StreamWriter(fileName)
For Each xRow As DataRow In UserTable.Rows
fileWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}", xRow("Name"), xRow("Age"), xRow("Username"), xRow("Password"), xRow("YearGroup")))
Next
fileWriter.Close()
End Sub
Function CheckUserPassword(UserName As String, Password As String) As Boolean
Dim Found As Boolean = False
For Each xRow As DataRow In UserTable.Rows
If (xRow("Username") = SomeUserName) And (xRow("Password") = SomePassword) Then
Found = True
Exit For
Else
Found = False
End If
Next
Return Found
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadUserFile()
If CheckUserPassword(SomeUserName, SomePassword) = True Then
'Good to go
Else
'bad user/pass
End If
WriteUserFile()
End Sub
End Class
You can use IO.File.ReadAllLines(fileName) to read the lines into an array of strings. Then you can use String.Split() on each line to split the fields and pick out the username and password.
dim allLines as String() = IO.File.ReadAllLines(fileName)
for each line as String in allLines
dim lineArray() as string
lineArray = line.Split(New Char() {","c})
username = lineArray(2)
password = lineArray(3)
if username = theUsernameYouWant then
'Found the user. Now check their password
endif
next
I havn't tested this code. Might have syntax errors.

I want to retrieve a person phone number using Active directory

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

Grabbing values sent to a console application in VB.net

What I'm trying to accomplish I have a textbox control and a button control on a form. When clicked whatever is entered into the textbox control, I want to send that data to a console application, which in turn create a text file. I have it mostly working but I can't get the data sent from the web application. How do I accomplish this? Here is what I have so far.
Here is my sub to send to the console application:
Public Sub send_to_console()
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
Dim p As Process = Process.Start(info)
End Sub
Console App Code:
ublic Sub Main(ByVal args As String)
Dim w As StreamWriter
Dim filepath As String = "C:\xml_files\testFile.txt"
Dim new_string As String
new_string = "This has been completed on " & Date.Now
If args = "" Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args & " " & Date.Now
End If
If System.IO.File.Exists(filepath) Then
File.Delete(filepath)
End If
w = File.CreateText(filepath)
w.WriteLine(new_string)
w.Flush()
w.Close()
End Sub
Currently i'm getting an error: no accessible Main
'#######################EDITS###########
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
info.UseShellExecute = False
Dim p As Process = Process.Start(info)
main takes an array of string not a string.
so
Public Sub Main(ByVal args As String())
.....
If args.length < 1 Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args(0) & " " & Date.Now
End If
.....
End Sub
In order to prevent windows from splitting your arguments concatenate a quote character before and after
Dim info As ProcessStartInfo = New ProcessStartInfo(file, """" & TextBox1.Text & """")
Four double quote characters represent a string literal containing a single double quote.