I am running a C# windows console application and passing in a couple of arguments via Task Scheduler. It runs all day loading flat file data created by other applications into SQL server. The program fails intermittently and I have Try/Catch logic that writes information regarding the exception using Console.WriteLine().
So basically I need to track down the location of the console output so I can take steps to eliminate the intermittent failures. I've had a good look around online thinking this must be a fairly common requirement to diagnose errors from Task Scheduler scheduled apps. My online search has revealed a couple of work around solutions but no direct answer as to where the console output goes when running a c# console application directly via Task Scheduler.
The two workarounds I have seen are:
(1) Get Task Scheduler to run a windows batch script (.bat file) instead of running the console app (.exe file) directly. Within the batch script use ">" or ">>" to redirect the console output to a flat file (e.g C:\app\myapp.exe arg1 arg2 > "C:\log\myapp_console_output.txt")
(2) A very similar solution is to get Task Scheduler to run the windows command line cmd.exe with /C option and passing arguments into cmd.exe to run my console app and also redirect the console output. e.g. something like:
cmd.exe /C "C:\app\myapp.exe" arg1 arg2 > "C:\log\myapp_console_output.txt"
While I acknowledge that the above workarounds may well help me to capture future failures it doesnt really help me to track down output from the intermittent failures that have already occurred. They also seem quite messy workarounds to achieve what I would have thought was a pretty common standard requirement.
Can anyone please confirm that the console output is definitely not retained somewhere when running a c# console app directly via Task Scheduler?
Related
I have a C# console application program running on windows server anytime.
On the same machine I have zend server and apache running.
It is possible to send a command to the running C# program directly from the PHP without having an endless loop on the C# program that taking the info from outsourced files?
For example, the command "/init" would initialize all the variables on the C# program.
Can I write a init.php file to send the "/init" command to the running C# windows application?
This will be in order to initialize all the variables on the running "Program.exe" by opening the URL "http://example.com/init.php".
Thanks in advance.
There is a number of approache for IPC.
As I understand it, you want to do that without a loop. The thing is: You have to have a loop anyway to keep the console application alive. The programm is staretd. Executes all code. And then ends. You could block it via stuff like ReadKey(), but then it would not be able to process anything.
Unfortunately all approaches to IPC I know either require a loop. Or a GUI that already has a loop - the EventQueue. You will not get around some multitasking, and for that alone I always advise a GUI application.
It is also pretty unclear what data you actually want to send and what that application doe with that data. Depending on those requirements, it might be possible to just do this via commandline parameters.
However the biggest issue might be rights. Web Servers are notoriously vulnerable to hacking, being online 24/7/365. As a result, they are usually run under the most restrictive user rights imaginable. Read access to it's content and programm folder is the only thing you can asume. Reading anywhere else, writing or even Execution is not usually on the list of things it can do. And will raise some eyebrows from the admin too.
I have a .Net windows C# application, fairly complete and working, that I have been asked to support calling it from another program like LabView. I have added the ability to parse command line arguments at startup so I can detect that it is supposed to behave like a console application and be provided with enough information to function.
What I would like to do is have the program print out to the console its results and have the calling program pipe it or just pull the data and use it.
The printing to the console works fine but when I start the program up, it tells the command prompt window that it is done (a new prompt immediately shows up and the command prompt is waiting for input). In the process it also closes the redirection that was part of the startup line. Is there anyway to keep it from telling the calling program that it has completed before it has actually finished?
The simple solution is to pass a file to save the data to but I would prefer not to have to do that. I could also do a separate version that is a console app, but that means supporting two separate programs.
Thanks
Instead of invoking the program directly, you can use cmd /c myapp.exe.
I am still pretty much new to c# so you will have to bear with me.
I have developed a windows form program which updates some SQL records as an end of day process for one of our clients.
The next step is that I need to install the program on a server and simulate a button click in the program to become a scheduled task.
I know how to setup the task on the server side where you start program and enter the arguments. But I am unsure as to what code I need to include in my program to achieve this.
Consider using Windows Task Scheduler.
You could extract your business logic to a separate DLL and write a simple Console app that will just run your task after accepting the parameters through command line.
My recommendation would be to get away from running a GUI-based/windowed application from a scheduled task - this is generally madness in practice. Ideally, deploy a console-based version of your application that requires execution (perhaps with parameter arguments) and doesn't require any user (or quasi-user-) interaction.
If you simply can't create a 'system version' of your application, then I guess you have two choices, both immensely ugly: 1) create some kind of macro script which is executed instead of your program, this script could execute the program and issue 'the click', 2) perform 'the click' on startup of your application by invoking the button click handler (maybe based on a parameter to give it a duality in execution modes.)
I think you are also asking about command-line argument passing. See the answers to this question.
In particular, I highly recommend the accepted answer: NDesk.Options.
I have similar task to do making winforms as windows task. what i did is
in windows task scheduler in the task tab,under Run put your exe and then /Auto,it will run as schedule.
Example:winform.exe /Auto
If I'm understanding your question correctly, this is how you could possibly proceed:
Best way to parse command line arguments in C#? -> check the answers and choose a library to process the args or write your own code to do so.
Create a scheduled task if those arguments are present by Creating Scheduled Tasks
If it is a windows application, just go to the bin folder, get the executable file, and finally schedule a task for it by using windows schedule task and choose the exe file as you targeted application.
if it is web application, you may want to include your code in a quartz.net scheduled job, details are on quartz.net website.
Very popular solution is Quartz.NET http://quartznet.sourceforge.net/
Take a look in the Timer class
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
Why not extract your database update logic as a windows service
you can segregate the sql handling part in a separate DLL and use the common DLL for both your form application and the windows service.
A window service run in background and can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.
Moreover you need not to install any third party software for same and window service code base can be ported to any windows machine with required version of .Net Framework installed.
Add reference: Microsoft.Win32.TaskScheduler
then write this code:
using (TaskService ts = new TaskService())
Microsoft.Win32.TaskScheduler.Task task = ts.GetTask(TaskName);
task.Run(); //start
task.Stop(); //End
This question already has answers here:
C# API for Task Scheduler 2.0 [closed]
(4 answers)
Closed 5 years ago.
My application requires a re-start at midnight time daily. For this job, according to me, the task scheduler would be the ideal thing to use but I haven't been able to find how to use the Task Scheduler APIs in C# (no external libraries to be used)
Once starting the application from Task Scheduler is done, I also wanted suggestions how to shutdown the application automatically at a certain time (even if the app at that particular time might be unresponsive, displaying some error message box or not working due to some problem)
Well, I suppose you don't know about the schtasks command.
You could simply open a command prompt and type schtasks /? to see the options available.
The one needed here is /create. Of course this option requires a series of parameter to configure your scheduled task. But at the end you could resolve all calling:
Process.Start("schtasks", commandParams);
For the close process part, I use a little utility called pskill found in the Sysinternals suite from Microsoft's Mark Russinovich. Also this could be called inside a batch file set as scheduled task.
EDIT: Changed from psshutdown to pskill (You need to close only your app right?)
I suggest you write a service to handle this. Also, why does it require a restart?
If however you must use task scheduler, try it like this:
schtasks /create /SC DAILY /TN AppName /TR AppExecutablePath /ST 0
0:00 /ET TIMEFORENDTASK
You can simply type this in a batch script and run the batch script when the user is installing the app, then put this in the uninstall batch script:
schtasks /delete /TN AppName
I am not quite sure about the difference among the console (in "windows console application"), cmd.exe, a shell.
I know cmd.exe is a stand-alone process when running, is cmd.exe == shell ? So shell is just a process?
is console == cmd.exe?
MSDN says ProcessStartInfo.UseShellExecute==True means use the shell when starting the process, does it mean that the process is started just the same as i run a cmd.exe and run the program from that command prompt? What's the point of doing this? Does the process started this way has its own console?
Thanks in advance.
- MSDN says ProcessStartInfo.UseShellExecute==True means use the shell when starting the process, does it mean that the process is started just the same as i run a cmd.exe and run the program from that command prompt? What's the point of doing this? Does the process started this way has its own console?
Actually it works like this:
if UseShellExecute is false, the application will be started using the CreateProcess API; this API lets you specify a lot of startup options, among which there is the possibility to redirect stdin/stdout/stderr, but will only start executables. If you try to launch a file (e.g. a word document) with CreateProcess, it will fail, because word documents aren't executable files.
if UseShellExecute is true, the process will be started using the ShellExecuteEx API; this function is the same function that Windows Explorer ("the shell", at least in Microsoft terminology) uses when you double click on a file in a folder; its main advantage is that it "knows" how to start documents (opening them with the associated programs), it's aware of shell folders, ... because it uses a lot of the shell facilities. However it has some major drawbacks: it's quite heavyweight compared to the bare CreateProcess (because it has to perform a lot of extra work), it fails to open even executables if something is wrong with file associations/shell extensions/... and it can't redirect stdin/stdout/stderr. Not that theoretically it would be impossible: after all ShellExecuteEx internally calls CreateProcess; the problem is that it doesn't expose this feature.
So, the two methods of creating a process are really quite different; the Process class does a great job at flattening them, but a feature that absolutely cannot be reproduced with the ShellExecuteEx function is the IO streams redirection, since it's not made available by the ShellExecuteEx function and it can be enabled only at process start via CreateProcess.
The use of the console by the started program is another question. The console is allocated/reused inside CreateProcess (actually IIRC it has to do with the windows PE loader, that checks the required subsystem in the PE header); the rules for console creation/reusing are specified here.
If the started application is a GUI application, no consoles are created at all; on the other hand, if a console application is started it reuses its parent process' console, unless it specified in the CreateProcess call the CREATE_NEW_CONSOLE flag. The default is not to specify this flag, but I'm not sure of what does ShellExecuteEx do with console applications, and I don't have a Windows box at hand to check. I'll leave this as an exercise to the reader. :P
Additional answers
Hi, Matteo, another question. If i create a new process as a detached process which don't have a console attached. Where is the process's stdout now? Where does's the process's output go? Is the process's stdout differnt from console's ouput?
It's not clear to me what you mean. When you start a new process with CreateProcess/ShellExecuteEx the console is allocated as needed, i.e. if the exe is a console executable (as specified in the PE header), Windows provides it a console (that is a new one or the parent's one depending on the rules I specified above); if the exe is a GUI application no console is allocated for it.
IIRC, for GUI applications stdout/stdin/stderr are just bit buckets, i.e. they point to nothing useful and all IO to them is discarded; by the way, nothing stops a GUI application from allocating a console and redirecting its own std* streams to it.
Keep in mind that the console, the Windows std streams and the CRT std streams are three separate things. The console is just an interface, that for console applications is conveniently bound by default to the Windows std streams.
The Windows std streams are the ones that are redirected when you specify stdin/stdout/stderr redirection in CreateProcess; you can get handles to them with the GetStdHandle function, and redirect them with the SetStdHandle.
The CRT stdin/stdout/stderr, finally, are yet another abstraction, built by the C runtime library; they are bound by default to the Windows std streams.
All this normally work seamlessly and you don't even have to bother about the difference between the Windows std streams and the CRT streams; however, when you start to think about streams redirection this difference becomes important.
If process's stdout stream is differnt from console's output, And Shell make the binding of these 2 streams for us. Would the ouput of a process be copied from process.stdout to console.output? is that efficient?
The shell isn't involved in this process, is the kernel that does the plumbing, following the instructions used in the CreateProcess (or subsequently modified from inside the new process with other APIs). For your performance concerns, with a layered structure like this it's the only way to go; and moreover, the copying part (if it's really a copy, I suspect that the whole thing is just a matter of passing pointers around) is the fastest part of the process, the real bottleneck is the console window painting/scrolling/etc. In facts, if you want to run a console application letting it produce data at full speed, you usually redirect its standard output to a file or through a pipe.
Many many thanks. Matteo Italia. You are a good problem sovler. :D
Thank you. :)
As far as I know:
Shell: A interface for the operating system and ultimately, the kernel. this includes explorer.exe and cmd.exe
Console: You instantiate the Win32 Console. That is the window that outputs your Console.WriteLine
cmd.exe : the windows command line interpreter. it instantiates the Win32 Console
More reading:
http://en.wikipedia.org/wiki/Win32_console [The win32 console, the console that you use if you don't require a graphical user interface]