Send signal from one winforms application to another - c#

I have a C# Win forms application, it has UI and optionally take command line argument to execute some process. I have a new request where an external application will provide command line argument and my application need to provide progress status to the external application. I want to make minimum change to my application for this task.
For example, my application launch by external program as below:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Program Files\ProgramFolder\MyProgram.exe";
startInfo.Arguments = #"C:\arguments.txt";
Process.Start(startInfo);
While my application running, it need to send information like, account in progress, account processed, all accounts completed, etc signal.
Should my application write progress status to a predefined folder then external application use file watcher to monitor new files and get status? My research shows another option named pipes, which new to me but hopefully can manage it. Is there any other alternative approach?

It's a bit late to give you any advice...but it can be useful for someone else.
To send informations between two or more different procceses, you can use MMFs,
"Memory Mapped File"
What is? : you can find a good description by clicking Here
I'm sorry if i can't be accurate enough but i'm still studying the argument
...
you can use the MemoryMappedFile class from C# using System.IO:MemoryMappedFile

Related

Capture ALL (stdout, stderr AND CON) output of cmd executing plink with C# (std out+err ok, CON not working)

I want to open SSH connections from c# via opening a process and running plink. All output should be collected and depending on the results the program will fire actions to the ssh.
My big problem is, that i am using a couple if different scripts and i need (automated) user interaction. Therefore i have to capture ALL output data (standard output, standard error AND CONSOLE).
Looking at the following test batch should make the case more clear:
1: #ECHO OFF
2: ECHO StdOut
3: ECHO StdErr 1>&2
4: ECHO Cons>CON
The code is like:
Process process;
Process process;
process = new Process();
process.StartInfo.FileName = #"cmd.exe";
process.StartInfo.Arguments = "/c test.bat";
process.StartInfo.UseShellExecute = false;
process.StartInfo.ErrorDialog = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
StreamWriter inputWriter = process.StandardInput;
[...]
I am able to capture lines 2+3, but not 4 (used by some programs).
I have also tried powershell (or directly plink) instead of cmd.exe as starting point, but same result.
Is there any way in c# to capture the console out as well or do you know any third party command line being able to redirect CON out to stdout or something like this?
I'm not sure that is even possible - well at least not using some plain simple API.
Please note that I have not found (although I tried) any information on the web that directly confirms that, but here is how I come to this conclusion.
The console in Windows is its own subsystem, managed by csrss.exe (and starting with Windows Vista also conhost.exe, but I digress). It has it's own set APIs (AttachConsole, WriteConsole, etc.) and you can only have one "console" per process.
CMD.EXE on the other hand is just another console mode application, that just happens to use the console and being launched it a console window. You can observe this effect, by launching a different console mode application and watch the process tree in e.g. Process Explorer: there is no CMD.EXE parent process (but rather it is Explorer or whatever you used to start it - including of course CMD.EXE).
Thus far I was trying to show the difference between "the console" and CMD.EXE, batch files, or console mode applications in general.
So when in CMD.EXE you use > CON you are actually causing the same effect as doing a write to CONOUT$ in native applications (or your typical write to /dev/console on a UNIX-like OS). There doesn't seem to be a direct equivalent for managed code, as Console.Out and Console.Error equal stdout and stderr in native applications (or 1 and 2 as file descriptors in CMD.EXE).
Having all that said, when you start a process you're only enabled to redirect it's standard output and standard error streams, but not (per se) the messages it writes to the console (or CONOUT$ handle). I guess that would be the same as trying to redirect output that a process writes to some file, which is also not (generically) possible.
You could possible achieve this using some hooking or injecting something inside the child process to grab the console output.
Being not able to easily do this, is also (one of) the reason(s) why writing a complete terminal (i.e. console window, not CMD.EXE!) replacement for Windows is not easily possible and requires some hacks or workarounds.
AFAIK know what you want (redirecting CON) is only possible by hooking/injecting which is rather complex and basically not necessary to do SSH.
For SSH you can use any number of C# libraries out there (free and commercial):
http://www.chilkatsoft.com/ssh-sftp-component.asp (commercial)
http://www.tamirgal.com/blog/page/SharpSSH.aspx (free)
http://sshnet.codeplex.com/ (free)
http://www.rebex.net/ssh-pack/default.aspx (commercial)
http://www.eldos.com/sbb/desc-ssh.php (commercial)
The main advantage of using a library is that you have much greater control over the SSH session than you could ever achieve via some redirected console AND it is much easier to implement...
UPDATE - as per comments:
To get all output from the remotely running program you need to use a library which comes with an "interactive/terminal" class for SSH - for example the one at http://www.rebex.net/ssh-pack/default.aspx comes with such a class and works really fine (not affilliated, just a happy customer), it can be used as a code-only component or as a visual control (whatever suits your needs).
Here are some CodeProject projects which do this (via native code), which AFAICT better handle redirecting all console output:
Universal Console Redirector
Redirecting an arbitrary Console's Input/Output
Also, the command freopen allows a program to redirect its streams. However, if a program does an explicit WriteConsole() I'm not sure if it is possible to redirect that.

Process.Start Permissions Problem

I'm trying to run an external problem from C# by using Process.Start, but am running into permissions issues. When I open a command prompt normally (not as an admin) and run my commands they work fine, but when I open a command prompt via Process.Start, I get a write error on the directory. ("I can't write on file test.log")
If I run it as an admin via Process.Start it works fine, but I get the permissions popup. Does anyone have any ideas that might help me figure this out? Thanks!
Here is the code I'm using:
Process proc = new Process();
proc.StartInfo.FileName = #"cmd.exe";
proc.StartInfo.Arguments = #"/k latex C:\Users\Shane\Documents\test.tex";
proc.Start();
proc.WaitForExit();
I wonder whether it's trying to write a diagnostic log to the current working directory, which you may not have permissions for. (I don't know offhand whether it will inherit the working directory, or be the directory that contains cmd.exe.) I suggest you specify the working directory for the new process using ProcessStartInfo.WorkingDirectory.
(As an aside, I personally find it cleaner to create a new ProcessStartInfo an populate that - C# object initializers make this particularly nice) and then call Process.Start(ProcessStartInfo) to start it. Otherwise it looks like there's already a process when there isn't really one yet. Just MHO though, and unrelated to the problem you're investigating, probably.)
Instead of using cmd.exe as a FileName property of Process object, keep your commands in one batch file and then use that file for execution.
Also you can mention administrator's privilages like username, password, domain etc via StartInfo property of Process class. If you use these properties I think permission problem will not come. Here you can find more information about StartInfo property.
Hope it helps.

Java and .net interoperability

I have a c# program through which i am opening cmd window as a a process. in this command window i am running a batch file. i am redirecting the output of that batch file commands to a Text File. When i run my application everything seems to be ok.
But few times, Application is giving some error like "Can't access the file. it's being used by another application" at the same time cmd window is not getting closed. If we close the cmd process through the Task Manager, then it's writing the content to the file and getting closed. Even though i closed the cmd process, still file handle is not getting released. so that i am not able to run the application next time onwards.Always it's saying Can't access the file. Only after restarting the system, it's working.
Here is my code:
Process objProcess = new Process();
ProcessStartInfo objProInfo = new ProcessStartInfo();
objProInfo.WindowStyle = ProcessWindowStyle.Maximized;
objProInfo.UseShellExecute = true;
objProInfo.FileName = "Batch file path"
objProInfo.Arguments = "Some Arguments";
if (Directory.Exists(strOutputPath) == false)
{
Directory.CreateDirectory(strOutputPath);
}
objProInfo.CreateNoWindow = false;
objProcess.StartInfo = objProInfo;
objProcess.Start();
objProcess.WaitForExit();
test.bat:
java classname argument > output.txt
Here is my question:
I am not able to trace where the problem is..
How we can see the process which holding handle on ant file.
Is there any suggestions for Java and .net interoperability
In situations like this I start up the Process Explorer ( by Sysinternals, awesome tool btw ) click Ctrl+F, and enter the name of the file. It will search across all running processes and will list the file handles to this file by the applications that have it open.
You can then either drop the handle, or kill the app - whatever you think is better )
You can try forking and attaching file descriptor from C# rather than launching a bat file.
I think the problem is because the java program is accessing the text file when the C# program is writing something on it, and hence a "file cannot access" problem.
If I were you, I would do everything in C#-- I won't use Java to read the state of the C# program. And I would access the file only after I've completed whatever the C# needs to do.
As for to see what process is locking up your file, you can use Process Explorer for this purpose.

If I have the URL of a torrent, how can I just "launch" it using the Process.Start()?

I found a way to obtain the URL of a torrent file, if I have this in string format, is there a way for me to just launch it whenever a user presses a button in my app?
I know I could save the file and then call it up, but I'd rather just open it. Is this possible?
You can just start it, but what will happen then is your default browser will open and it will download the file. And depending on the local settings on that machine it will do the default thing.
I would not recommend this method, it means the end user will have to do alot of extra steps. And the different browsers behave differently, and may not obey windows file extentions ( thing firefox )
If your doing this inside a application you should download it yourself, you can read about that here. .NET Frameworks offers great solutions to download the file yourself.
Also if you do it via Proccess you will not get a refere when downloading, some sites may then block you to stop hot linking. but if you control the download class you can send a refere url
Don't know if this is OK for you, but if you have the torrent protocol registered to an installed application, simply launching the URL as if it were the path of an executable file (for example by using the Process class) will launch the associated application. See here: http://kb.mozillazine.org/Register_protocol
Try this:
Process p = new Process();
p.StartInfo.FileName = "http://domain/folder/file.torrent";
p.Start();
Or, if you like one-liners:
new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "http://domain/folder/file.torrent"
}
}.Start();
That will call your default browser to download that file and tries to open it. Clicking "Open" you associate program takes control.

From C#, open an arbitrary application

Related question [stackoverflow] here.
I'm trying to do the above, but I want to take the process one step further. I want to open an arbitrary file using the default editor for the file type. From that point, I want to allow my user to interact with the file as they would normally, or continue to work in my application. The extension is what happens after the user finishes editing. Is there a way I can capture a close (and ideally save) event from the external application and use that as a trigger to do something else? For my purposes, tracking the closing of the external application would do.
I can do this in the specific case. For example, I can open a Word instance from my application and track the events that interest my application. However, I want to de-couple my application from Word.I want to allow my users to use any document editor of their choice, then manage the storage of the file being edited discretely behind the scenes.
You can do this in a manner similar to the referenced question, but the syntax is slightly different:
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo =
new System.Diagnostics.ProcessStartInfo("C:\...\...\myfile.html");
process.Start();
process.WaitForExit(); // this line is the key difference
The WaitForExit() call will block until the other application is closed. You would use this code in a separate thread so that the user can keep using your application in the meantime.
Use the FileSystemWatcher class to watch for changes to the file.
EDIT: You can also handle the Exited event of the Process object to find out when the program is exited. However, note that that won't tell you of the user closes your file but doesn't exit the process. (Which is especially likely in Word).
To listen for file change, you can use the FileSystemWatcher and listen for a change in the last modified date.
You can also monitor the process and check then file when the process close.
I found this useful tip online just now. It seems to be what you are looking for. This article (link broken) has some more detail and useful, to-the-point tips on C# programming.
string filename = "instruction.txt";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#filename);
System.Diagnostics.Process rfp = new System.Diagnostics.Process();
rfp = System.Diagnostics.Process.Start(psi);
rfp.WaitForExit(2000);
if (rfp.HasExited)
{
System.IO.File.Delete(filename);
}
//execute other code after the program has closed
MessageBox.ShowDialog("The program is done.");

Categories