TelnetExpect Reading Output from Stream in VB.NET - vb.net

Good Morning,
I have been tasked with writing a program that locates the local port a MAC Address is registered to, and to do that I need to SSH and Telnet into Cisco devices and receive the output of the commands so I can parse it and decide what to do with the information.
So far I have the SSH connection and parsing done no problem thanks to Renci.SshNET. But I am having trouble with the Telnet, I set it up to use Telnetlib.dll and I know it works because I can do "show users" on the switch I'm connecting to and see that one of the vty lines are being occupied by my application. But in the application I'm writing all I get is the application freezing up, none of the buttons work, and I can't see the mouse when I hover over the window, so I'm guessing that the application isn't liking something at run-time.
The code I'm using, in VB.NET is:
Using client As TcpClient = New TcpClient(host, 23)
Dim tel As TelnetStream = New TelnetStream(client.GetStream)
Dim buff(client.ReceiveBufferSize) As Byte
Dim result As String
tel.SetRemoteMode(TelnetOption.Echo, False)
Dim exp As Expector = New Expector(tel)
exp.Expect("username: ")
exp.SendLine(username)
exp.Expect("password: ")
exp.SendLine(password)
exp.Expect(">")
tel.Read(buff, 0, buff.Length)
result = System.Text.Encoding.ASCII.GetString(buff)
MessageBox.Show(result)
End Using
Telnetlib.dll include the definitions for the Expector, SendLine, Expect, and TelnetStream.
I did some debugging and found that it freezes when it goes to execute the result = System.Text.Encoding.ASCII.GetString(buff)
command.
Thanks for any help.

Related

Error Printing: No application is associated with the specified file for this operation

I have a VB WinForms app that prints PDFs using Process.Start, and it has been working fine for ages on Windows 10. Today I go to use it and get the following error message:
"No application is associated with the specified file for this operation"
Nothing has changed to cause this, I have not changed PDF Viewer or uninstalled anything. I can open a PDF by double clicking on it no problems.
I wrote a small console app to replicate the issue and prove this had nothing to do with the WinForms app:
Sub Main()
Dim pi As New Diagnostics.ProcessStartInfo
Dim url As String = "C:\PathToPDF\.pdf"
pi.FileName = url
pi.Verb = "PrintTo"
pi.CreateNoWindow = True
pi.Arguments = """Microsoft Print to PDF"""
pi.UseShellExecute = True
Console.WriteLine(url)
Diagnostics.Process.Start(pi)
Console.ReadKey()
End Sub
The above program replicates the error. I have verified that the file exists and is accessible and tried it with double slashes and single slashes, they give the same error:
"No application is associated with the specified file for this operation".
The same application is working fine on other PCs in the office.
Has anyone else had this happen, and if so how did they fix it?
My PDF viewer is PDFXChange Viewer, and it has been working fine PDFs printed using this method for years. I have not updated the program, and it says in the about page that the last installed updated was in 2016.
Regards.
If I am right, I had the same issue. Maybe you can try it in a slightly other way. I have this in my application and it works fine:
Dim myp As New Process
myp.StartInfo.FileName = filename 'Full path to pdf
myp.Start()

ManagementException: Not found

I have a program which runs on some wearable terminals in our warehouse. These terminals connect via remote desktop to our server which actually hosts and runs this program.
This program takes a scan of product, launches another program (if it isn't already running for the current user) which handles some processing, then does some additional processing once finished. One issue I'm running into is checking if the second program is already running. I've tried a lot of different code but this is what I settled on as it seemed to work perfectly fine.
Private Function CheckPrintLabelRunning() As Boolean
Dim selectQuery As String = "Select * From Win32_Process Where Name = 'vbPrintLabel.exe'"
Dim searcher As New System.Management.ManagementObjectSearcher(selectQuery)
Dim processList As System.Management.ManagementObjectCollection = searcher.[Get]()
For Each obj As System.Management.ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
If argList(0).ToString.ToUpper = Environment.UserName.ToUpper Then
Return True
End If
End If
Next
Return False
End Function
On Thursday, while the users were using the application on the terminals, the following error message popped up in my error logs. This application has seemingly been closing itself down, hitting the main form's FormClosing event (indicating that it isn't a full crash, but something that is handled inappropriately or an environment crash perhaps?). Here is the exception:
System.Management.ManagementException: Not found
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)
at vbFullCasePicking.frmFullCasePicking.CheckPrintLabelRunning()
at vbFullCasePicking.frmFullCasePicking.StartPrintLabelListener()
at vbFullCasePicking.frmFullCasePicking.PrintLabel(Boolean blnSMPLabels, String strCartonID)
I would like to point out that in this particular issue, the application did not close itself down, but I am still curious about this error as it's the first I've seen it of all the months this has been in use.
EDIT: More info...the server the application runs on is Windows Server 2003. This issue has not generated any event log entries of any kind as far as we can see.
EDIT 2: I completely forgot about this, but I have a previous question regarding this issue. I was initially querying all the processes which seemed to cause errors when multiple users would try to query at the same time. This is likely the same issue, then, just with a much smaller window. Any input is greatly appreciated.

Opening a file using impersonation

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)
My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.

how to open a vb.application from another vb.application with parameters

i have 2 vb applications. this is the code for the first one which when a button is clicked it will check if the other application is already open. If not, it'll open that application -
Dim sComputer As String
sComputer = Environ("COMPUTERNAME")
Dim LocalByName As Process() = Process.GetProcessesByName("ticket.prices", sComputer)
If LocalByName.Length = 0 Then
System.Diagnostics.Process.Start("http://ticket.prices.application")
End If
this runs fine. but what i need is that the customerid on the application 1 that is calling application 2, should be transfered while opening app 2.
e.g -
Customer 10001 screen is open on app 1. When i click open app 2, the above code runs and opens app 2. how do i make app 2 open to customer 10001 screen. Is there any way to pass parameters while opening app 2 in System.Diagnostics.Process.Start ?
Use the version of 'Process.Start' that takes 2 strings, the second being the commandline parameters. See here for details.
You want the ProcessStartInfo class, or use the Start method taking to strings. ProcessStartInfo gives you a lot of options about how to start your program, which often comes in handy. Its good to get familiar with it.
Dim info as New ProcessStartInfo()
info.Arguments = "10001"
info.FileName = "exename"
Dim LocalByName as New Process()
LocalByName.StartInfo = info
LocalByName.Start()
Getting the arguments in the new program is accomplished via Environment.GetCommandLineArgs()
For Each arg As String In Environment.GetCommandLineArgs()
Console.WriteLine(arg)
Next arg
It looks like what you ultimately want to accomplish is getting the currently selected row from App 1 and passing that to the second program, though. Is this correct? That opens a whole new ball of wax involving interprocess communication.
EDIT: The simplest way to get the selected edit would be to write the id out to a text file. You have to be careful when doing this because if you just write System.IO.File.WriteAllText("selectedrow.txt", "123"), you'll write to the app's startup path directory. You'll want to get the exe's current path as below
Dim u as New Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
dim exepath as String = System.IO.Path.GetDirectoryName(u.LocalPath)
dim fullPath as String = System.IO.Path.Combine(exepath, "selectedrow.txt")
System.IO.File.WriteAllText(fullpath, "123")
This will overwrite the text in the file every time you change rows. You want to wrap this in a try/catch block so as not to crash the program. Make sure you log the errors; don't just swallow them. To read the data, you just do
dim id as string = System.IO.File.ReadAllText(PathToFileYoureWritingToInTheOtherProgram)
in the other program.
This isn't necessarily the best way to go about things, but its the simplest way I know of off the top of my head.
You might could look at MessageQueues if you a better solution, but as long as you're not changing selected rows every 100ms, writing the file should work fine.

Ensure connection to a POSPrinter connected via COM

I need to make sure that the connection to a POS printer is successful before writing data to the database and then printing a receipt. The POSprinter is normally of type BTP 2002NP but may differ. The common thing is that they are all connected via COM-port and NOT usb, so no drivers installed at all on the client.
Can I send some kind of "ping" on a COM-port and check if a device is connected and turned on? Any help or suggestions are very much appreciated.
Additional information, the application is developed in VB.net and Visual Studio 2008
About all you can do is write out a character string to the com port and wait and see if your printer responds with a reply. However the string you write and the string you expect will depend on the printer itself.
Refer to the BTP 2002NP printers programming manual for examples (the first link in google that I looked at)
From looking at the manual an appropriate string to send to the printer is the "DLE EOT n" command which requests that the printer send back its current status.
As for other printers in the range, check out this list of drivers and manuals
btw, this is what i came up with in the end.
Public Function ComTest() As Byte()
Dim TXT As String
TXT = Chr(&H10S) & Chr(&H4S) & Chr(1) 'DLE EOT 1
If OpenCom() Then 'Connect to com
moRS232.PurgeBuffer(Rs232.PurgeBuffers.TxClear Or Rs232.PurgeBuffers.RXClear)
moRS232.Write(TXT)
moRS232.Read(1)
Return moRS232.InputStream
Else
Return Nothing
End If
End Function
the function returns 1 byte. i can then from the manual translate this byte into what state the printer is currently in. this probably works for all ESC/P printers.