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.
Related
I searched many times in this topic but with no luck, I have an application on WPF that use Click Once to published and there fore I can't use Admin Privilege, and I need to implement some actions in the installation Process like restart SQL server for example and for that I need Admin Privilege and since i start publishing using click once I had to remove Admin Privilege now, i tried restart my application to force Admin rights using the following code but didn't work
Public Function IsRunAsAdmin() As Boolean
Try
Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principal As WindowsPrincipal = New WindowsPrincipal(id)
Return principal.IsInRole(WindowsBuiltInRole.Administrator)
Catch __unusedException1__ As Exception
Return False
End Try
End Function
Public Sub AdminRelauncher()
If Not IsRunAsAdmin() Then
Dim proc As ProcessStartInfo = New ProcessStartInfo()
Dim procExecuting As New Process
proc.UseShellExecute = True
proc.WorkingDirectory = Environment.CurrentDirectory
proc.FileName = Assembly.GetEntryAssembly().CodeBase
proc.Verb = "runas"
Try
procExecuting = Process.Start(proc)
Application.ExitThread()
Application.Exit()
Catch ex As Exception
Console.WriteLine("This program must be run as an administrator! " & vbLf & vbLf & ex.ToString())
End Try
End If
End Sub
I still get the Error "Can not open MSSQL$****** on computer" after i searched of course i found the cause is admin rights needed.
So now i'm working on Code Signing Certificates as some one advise me that this will work for me.
but i'm an individual and my application price is not high enough to buy a paid certificate so i was wondering if i can make a self Code Signing Certificate and use it with click once.
Thank you.
I finally manged to figure out the problem my self, it was the admin rights.
The problem was that the code simply need like 2-3 mile seconds to execute so when i tracked the code i found that my code manged to stop the service indeed but wasn't able to start it again as it didn't take the time for the service to fully stop.
The solution was simple as it just needed couple of seconds to after it execute the code to stop the service.
So simply need to add a code in between.
First
Imports System.Threading
Then use the code as following
Dim service As ServiceController = New ServiceController("SQL Server (SQLEXPRESS)")
service.Stop()
Thread.Sleep(10000)
service.Start()
You see the code where Thread.sleep is make the application wait 10 seconds before it complete to execute the code.
This time is depends on the machine it self, 2-3 sec was enough but some other machine needed more time so to be in the safe side just add more seconds as I did.
Thank you, and "Stay Safe".
I'm trying to fetch the files inside a folder ordered by LastWriteTime.
The code is running very fast when accessing to a local path (C:\MyFolder), but is hanging when accessing to a remote path (\\MyServer\MyFolder)
Dim myOrderedList As List(Of String) = (From item In IO.Directory.GetFiles(strFolderSource) _
Let file = New IO.FileInfo(item) _
Order By file.LastWriteTime _
Select item).ToList()
Should this code work? Is not allowed this method to get files from a remote folder?
Which alternative code could I use to get the same result without hanging?
EDITED (2019-01-18 16:32):
Sorry guys, I've tried the proposed solution from Rango, and still the same hang. Finally I created a small logging system to catch the step that caused the problem, and realized that all is a credential problem.
Just before the code I posted I do a NET USE to grant access to the remote computer, and the net use is executed, but for any reason, the GetFiles() fails because of Logon failure: unknown user name or bad password.
So, Could I ensure the credentials with the net use before call the GetFiles()?
Maybe using a pause or something like this?
FULL CODE:
Dim processInfo As New System.Diagnostics.ProcessStartInfo()
processInfo.FileName = "C:\WINDOWS\system32\net"
processInfo.Arguments = "net use \\MyServer\IPC$ ""password"" /USER:Username"
System.Diagnostics.Process.Start(processInfo)
Dim myOrderedList As List(Of String) = (From item In IO.Directory.GetFiles("\\MyServer\g$\MyFolder") _
Let file = New IO.FileInfo(item) _
Order By file.LastWriteTime _
Select item).ToList()
You could try to use DirectoryInfo.EnumerateFiles instead wich has two advantages:
No consecutive security handshakes from the remote server necessary
Streaming the files instead of loading all into memory before you start ordering them
Dim di = new DirectoryInfo(strFolderSource)
Dim files = From fi In di.EnumerateFiles() Order By fi.LastWriteTime Select fi.FullName
Dim myOrderedList As List(Of String) = files.ToList()
Finally solved including a sleep of 5 seconds after the net use and before the GetFiles():
System.Threading.Thread.Sleep(5000)
Thanks for your time, and hope this helps anybody with a similar problem.
I am running a dos command from my app, however the dos window just hangs without returning any output. It does work under Windows 8, but not Windows 7.
This is my code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.UseShellExecute = False
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.Start()
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
RichTextBox1.Text = output
End Sub
picoscope.com is a 'wrapper' supplied by the PicoScope vendor - it appears to be a very small .net app, which calls the main PicoScope.exe program with some commands (unknown). The PicoScope.exe app needs to be running for this to work.
I wrote a small console app, and this works just fine - however I can't even call my console app from a forms based application.
Code for console app:
Sub Main()
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.Start()
' Synchronously read the standard output of the spawned process.
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
process.WaitForExit()
process.Close()
End Sub
This seems to be some strange issue with Windows 7.
I can open cmd.exe without any issue, as well as spawn other applications.
It's almost as if there is some conflict between the running picoscope programs and my application.
Attempting to debug doesn't seem to help at all, with the exception of this:
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
I have tried several different approaches, disabling shell redirection, even trying to redirect the output to a file. But it would appear that anything to do with this Picoscope app just prevents it working.
I even tried writing another console app to redirect text output to the console and to a file and they worked (because the picoscope app wasn't involved!).
Likewise, a simple dos batch file with "echo Hello World" in it is successfully redirected to my forms app - so I'm sure my code is correct.
I am now at a loss as to what the issue could be here.
I'm using Visual Studio 2013, Windows 7 on SP1.
Can anyone offer any suggestions?
Apologies for the long post, I was trying to give as much detail as possible.
EDIT: Even more curious is that I tried my working app on another Windows 7 PC and it works...
I suspect this must be related to my specific Windows 7 PC (a fresh build).
I compared UAC settings with the other PC - they are the same.
Thanks.
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.
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.