Changing environment variables of the calling process - c#

This one seems trivial but the answer has eluded me for a few days now.
I have a Windows batch file, that calls a C# program to do an extra verification that cannot be done in a batch file. After the verification is complete I need to return a status and a string back to the calling shell.
Now the return value is trivial and my C# console app simply sets a return value (exit code if you will). And I thought the string will also be a piece of cake. I attempted to define a new shell variable using the:
Environment.SetEnvironmentVariable("ERR", "Some text");
This call should (and does) define a shell variable within the current process - that is the very C# process that created the variable. The value is lost as soon as the C# app terminates and the shell that created the C# app knows nothing about the variable. So... A call with no particular use... At all... Unless perhaps if I created a child process from the C3 app, perhaps it would inherit my variables.
The EnvironmentVariableTarget.Machine and EnvironmentVariableTarget.User targets for the SetEnvironmentVariable call don't solve the problem either, as only a newly created process will get these new values from the registry.
So the only working solution I can think of is:
write to stdout
write to a file
encode extra meaning into the return value
The first two are a bit ugly and the last one has its limitations and problems.
Any other ideas (how to set a shell variable in the parent process)? Maybe such shell variable modifications are a security concern (think PATH)...
Thank-you for your time.

I had the same problem as Ryan and the only thing that came to my mind as a work-around was to write a batch in error out to set the variable and to call it from the batch.
ConsoleApplication1.exe:
'put some sensible code here
'put result in variable myResult
Dim myResult As String = Guid.NewGuid().ToString("D").ToUpperInvariant()
Console.WriteLine("Normal output from the consonle app")
Console.Error.WriteLine("#ECHO OFF")
Console.Error.WriteLine("SET zzzResult={0}", myResult)
Test.cmd (the calling batch):
#ECHO OFF
:Jump to folder of batch file
PUSHD %~d0%~p0
:Define a temp file
SET zzzTempFile=%TEMP%\TMP%Random%.CMD
:Call .NET console app
ConsoleApplication1.exe 2>%zzzTempFile%
:Call the generated batch file
CALL %zzzTempFile%
:Clean up temp file
DEL %zzzTempFile%
:Clean up variable
SET zzzTempFile=
:Do something with the result
ECHO Yeah, we finally got it!
ECHO:
ECHO The value is "%zzzResult%".
ECHO:
:Clean up result variable
SET zzzResult=
:Go back to original folder
POPD
That should do the trick. And yes, I do know this is an old post and Ryan is solving other issues by now, but there might be still somebody else out there having the same problem...

What you are asking is to be able to arbitrarily write to the memory space of a running process. For good reason, this is not possible without SeDebugPrivilege.
Any of the three solutions you list will work. Stdout is the standard way to communicate with a batch script.
By the way, you're writing a Windows batch file. I'm pretty sure the ship has already sailed on "a bit ugly".

If you want to put a value of some output into a variable in the batch you can use the following construct:
FOR /F "usebackq tokens=4 delims=\[\] " %i IN (`ver`) DO set VERSION=%i
ECHO %VERSION%
Output on my OS:
6.1.7601
'usebackq' means we are using back quotes which gives the ability to use a fileset in the command quoted with double quotes. You may not need this. 'tokens' means the index in the resulting string array to select (it can be a range M-N). If you need to skip lines use 'skip=X'). 'delims' are the string separators to use (like string-Split() in .Net).
You will put your console app instead of 'ver' and adapt the delimiters and tokens to match your specific output. If you have more variables to fill you will need to make the if a bit more complex but that should make a good start.

My BAT is a bit rusty, but I think it's possible to retrieve the 'exit' code from processes you've run externally, perhaps via %ERRORLEVEL%. If that's the case, make sure to exit your program via
Environment.Exit(123); // where 123 = error code
You can't add any messages, so you'll have to do that in the .bat file.
If this isn't the case, stdout is probably the best way.

After stumbling on this myself as well recently, I came up with this approach. What I did is run the bat file using the Process class, i.e.
// Spawn your process as you normally would... but also have it dump the environment varaibles
Process process = new Process();
process.StartInfo.FileName = mybatfile.bat;
process.StartInfo.Arguments = #"&&set>>envirodump.txt";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// Read the environment variable lines into a string array
string[] envirolines = File.ReadAllLines("envirodump.txt");
File.Delete("envirodump.txt");
// Now simply set the environment variables in the parent process
foreach(string line in a)
{
string var = line.Split('=')[0];
string val = line.Split('=')[1];
Environment.SetEnvironmentVariable(var, val);
}
This seems to have worked for me. It's not the cleanest approach, but will work in a bind. :)

Related

Two things; console app run without .exe and args (C# console app)

Hi I would like to make my self able to maybe define my app into CMD by that I can type program instead of program.exe kind of like how ping works for example.
I also need help with arguments.
The point of my app is to send a get request to a local server evaling PHP fetching a result from it so I can easy quick debug things and calculate things ect from CMD.
So for example I have to do.
W:\Users\example>e.exe
echo "example";
.....
example
W:\Users\example>
Tow things with the above are very annoying. I need to enter e.exe and THAN I need to enter the code to eval :-/
How could I make it so I could just do
W:\Users\example>e echo "example";
.....
example
W:\Users\example
I really would like to get this working to make use faster + more simple ! this is a programmers way to calculating math :P
EDIT:
Below is the code;
static void Main(string[] args)
{
WebClient client = new WebClient();
Console.WriteLine("...");
string input = Console.ReadLine();
string php = client.DownloadString("http://192.168.1.50/test.php?exec="+input);
Console.WriteLine(".....");
Console.WriteLine("");
Console.WriteLine(php);
Console.WriteLine("");
}
I've tried to do "+arg[0] but does nothing at start :?
Don't type ".exe" as you don't need to type it... You may want to put your e.exe some place listed in PATH environment variable (or add path to the executable to the PATH).
Main(string[] args) are arguments passed to your program - use them whatever way you want. Note that they will be split on spaces, so you may need to String.Join them back if you need all arguments as one.
You can also use Environment.CommandLine if you need access to comple not parsed command line.

StartInfo.Arguments in c#

I found the following snippet of the code:
using System;
using System.Diagnostics;
public class RedirectingProcessOutput
{
public static void Main()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c dir *.cs";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
}
}
but I can't figure out what this p.StartInfo.Arguments = "/c dir *.cs"; is doing? thanks in advance for any explanation
It's passing command line arguments to the process that will be launched.
In this particular case, the process is the Windows shell (cmd.exe). Passing a command line to it will cause it to execute this command when started; then, because of the /c parameter at the beginning it will terminate itself.
So the output of the process will be exactly what you will get if you open a command prompt and enter the command dir *.cs.
In the beginning was exec(3) and its friends, which accept the path to an executable and a variable length list of pointers to arguments. In sane operating systems, The process that gets started receives a point to the argument list, each word of which contains a pointer to and individual string. Sane shells parse the command line and populate the argument list required by exec(3).
You can see a direct correlation between the argument list accepted by exec(3):
exec ("some.executable.file", "arg1" , "arg2" , "arg3" , ... ) ;
and what gets passed to the entrypoint of the process:
int main ( char *arg[] ) { ... }
where argv[0] is the executable name, and argv[1]—argv[n-2] are the individual arguments, and argv[n-1] is a NULL pointer to indicate the end of the argument list.
Both conceptually simple and simple to implement.
CP/M didn't do it that way (I assume because of limited memory). It passed the started process the address of the raw command line from the shell and left its parsing up the process.
DOS followed in 1982 as clone of CP/M, handing a started process the address of the raw command line as well.
Windows hasn't deviated from that model since its inception. The Win32 CreateProcess() function
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
...
);
still does the same thing, passing the raw command line to be passed to the program. The C runtime library, of course, takes care of the command line parsing for you...more or less.
So...in the CLR/.Net world, because of all this history, and because the CLR was designed to be dependent on the Win32 APIs, you have pass a complete command line to the process to be started. Why they didn't let you pass a params string[], instead and have the CLR build the command line is something that Microsoft's developers kept close to their chest.
Building the command line required by the started program is simple. You just join each argument into a single string with an SP character separating the arguments. Easy!
...until one of your arguments contains whitespace or a double quote character (").
Then you have to quote one or all of the arguments. Should be easy, but due to the bizarre quote rules, there are a lot of edge conditions that can trip you up.
A Windows command-line is broken up into words separated by whitespace, optionally quoted with double-quoted ("). Partly because Windows also got the path separater wrong (\ rather than /), the quoting rules are...byzantine. If you dig into the Windows CRT source code (the file is something like {VisualStudioInstallLocation}\VC\crt\src\stdargv.c), you'll find the command line parsing code.
That line just gives an argument to that proccess.

C# can I add the command prompt control to my app

Title says it. I know I can use Process or ProcessStartInfo to run arguments, but I mean actually adding a command prompt control to my app (because I use it very often and it'd be convenient if it was already built-in.
Is there any way to do this other than coding a custom control? If not I can live with it, but it would definitely help.
Something like this (not tested):
ProccessInfo pi = new ProccessInfo("cmd.exe");
pi.RedirectStandardError=true;
pi.RedirectStandardInput=true;
pi.RedirectStandardOutput=true;
Process cmd = Process.Start(pi);
cmd.StandardInput.WriteLine("Dir");
textBox1.Text = cmd.StandardOutput.ReadToEnd();
Watch out for deadlocks, those method can be blocking!
You can also use this solution from codeproject.com: http://www.codeproject.com/KB/miscctrl/commandprompt.aspx
See this question and related. Also this source code for example.
You can start a console near your win app's window which you will control and can output some data or get input from a user.
What is the problem with doing Console.ReadLine()/Console.WriteLine() in a loop? It is the most efficient way and you have fully control over what you are doing.

I need to open several VLC clients in order to "monitor" the stream they're receiving

I want to be able to specify how many clients do I want opened, and be able to manually switch between the windows after they're opened- meaning "streaming in background" (if such a thing is possible? ) won't do here.
I need to specify different inputs for the different clients as well.
Additionally -and this is the part I'm totally clueless about as it's VLC-specific - I need the clients to be logging some info re:the stream they're receiving, so as to be able to determine that it has been received completely etc -such as frame rate/total frames' number or similar.
I'd appreciate helpful suggestions for
running the instances+ controlling
them
getting info about
the stream
Language-wise - I know Java, some C#, and wouldn't mind learning some new language for this purpose if it's a better solution .
Thanks!
Depending on your version of VLC, you may need to enable an option to run multiple instances. See here: http://wiki.videolan.org/How_to_play_multiple_instances_of_VLC
It does sound like a 'run windows processes in a loop' thing, which you could do several ways.
You could make a windows batch file (.bat):
"C:\path\to\vlc.exe" -vvv "http://www.whatever.com/mystream.mms"
"C:\path\to\vlc.exe" -vvv "http://www.whatever.com/mystream2.mms"
"C:\path\to\vlc.exe" -vvv "C:\music\whatever.mp3"
Or you could use a real programming language and perhaps open a variable number of instances... C# for example:
using System.Diagnostics;
...
foreach (string stream in streamList) {
Process myProc = new Process();
string myCmd = #"C:\path\to\vlc.exe";
string myArgs = "-vvv \"" + stream + "\"";
ProcessStartInfo myStart = new ProcessStartInfo(myCmd, myArgs);
myStart.UseShellExecute = false;
myProc.StartInfo = myStart;
myProc.Start();
}
See this page for a full list of VLC command line options: http://www.videolan.org/doc/vlc-user-guide/en/ch04.html
Hope this helps.
You'll either need to run several processes (as above) or hook somehow into libvlc and instruct it to start up several players.
A good demo of this is the python wrapper to libvlc--I think--it shows how to sample to know where the stream is--however I've never tried it with multiple things running at the same time but I think it would work.
Another option might be something like http://wiki.videolan.org/Mosaic

Embedding Perl Interpreter

just downloaded ActivePerl. I want to embed the perl interpreter in a C# application (or at least call the perl interpreter from C#). I need to be able to send send out data to Perl from C#, then receive the output back into C#.
I just installed ActivePerl, and added MS Script Control 1.0 as a reference. I found this code on the internet, but am having trouble getting it to work.
MSScriptControl.ScriptControlClass Interpreter = new MSScriptControl.ScriptControlClass();
Interpreter.Language = #"ActivePerl";
string Program = #"reverse 'abcde'";
string Results = (string)Interpreter.Eval(Program);
return Results;
Originally, it had 'PerlScript' instead of 'ActivePerl', but neither work for me. I'm not entirely sure what Interpreter.Language expects. Does it require the path to the interpreter?
Solved... I'm not sure how, but when I changed it back to PerlScript it works now. Still, I would like to know if MSScript Control is using ActivePerl or another interpreter.
You can run an external program as Maxwell suggests, in which case the external program can be Perl or anything else. It might be easier to use temp files to send the input data and get the output, but that depends on how the external program expects to get its data.
The alternative, which is what I think you're looking for, is to use the PerlNET compiler that comes with ActiveState's Perl Dev Kit. It lets you add a class wrapper around the Perl code so you can expose it to C# just like any C# class. It's fairly simple to use; you add POD comments to your Perl code to specify the method names and signatures to expose, including type information, then you compile your Perl module into a DLL .NET assembly. Once that's done you can reference the assembly from any .NET program, construct an object from your Perl class, and call its methods.
I am not sure about the script control but I have done a similar thing where I had to 'embed' spamassasin (which is a Perl program). I basically used the Process to do the job. Something along the lines of:
var proc = new Process
{
StartInfo =
{
FileName = "perl",
WorkingDirectory = HttpRuntime.AppDomainAppPath,
Arguments = " myscript.pl arg1 arg2",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false
}
};
proc.Start();
proc.StandardInput.BaseStream.Write... // feed STDIN
proc.StandardOutput.Read... // Read program output
var procStdErr = proc.StandardError.ReadToEnd(); // errors
proc.StandardError.Close();
proc.StandardOutput.Close();
proc.WaitForExit(3000);
int exitCode = proc.ExitCode;
proc.Close();
This obviously not just Perl specific and it has the process creation overhead, so if you are running your script too often probably you need to think of a different solution.

Categories

Resources