Application exit code always return 0 - c#

We have a legacy VB6 application that runs a separate C# EXE. The VB6 application relies on the C# application to perform a particular task. When the task is done successfully it will return with exit code 0, or 1 if failure.
This works well on our development machines (yes, we tried on more than 1 machine). But, when we tried it on the client machine it always returns a 0 exit code no matter the result of the task.
The really strange part is that this scenario has been working perfectly for about 8 months until this first happenned.
We even tried to make a simple C# 'runner app' that only calls an exe and catches its exit code. Again, it worked fine on our development machine but always return 0 on the client machine. So, we concluded that the problem is not in the VB6 program.
This is the C# 'runner app' code snippet that call the .exe program:
System.Diagnostics.Process installProcess = new System.Diagnostics.Process();
installProcess.StartInfo.FileName = this.textBox1.Text;
installProcess.StartInfo.Arguments = this.textBox2.Text;
installProcess.Start();
installProcess.WaitForExit();
MessageBox.Show("Exit code : " + installProcess.ExitCode.ToString());
And this is the C# code snippet that exit the program with custom exit code:
Environment.Exit(1);
Well, we suspect there's some configuration on the client machine OS that causes this strange behavior on the client machine.

Based on the comment from Michael Gosselin on this question, it is critical to compile your project as a "console application" and not as a "windows application".

Related

C# Console Application fails reading files on restart

Its hard to place everything in the title, but I hope I can explain this as good as I can. Basicly I made a C# Console Application that reads a certain file every now and then. The Application runs on a Virtual Machine from Google Instances. Now I have created another Console Application that is capable of managing the other application, like closing them or restarting the executables.
The Issue:
When I start the Console Application by hand (manual), it works fine and reads the files like it should. I could close and open this as much as I like and it still works. The problem is when my second Console Application tries to restart the first Console Application. The restart works fine and most functions like certain ftp connections work, but it stops reading files and gives a null back as result. There happen to be no debug errors nor does it display an error on the console.
What I want is that the second application could restart my first application without making it run where some functions appear to be blocked.
The Code I use:
string loc = File.ReadAllText(Directory.GetCurrentDirectory() + "\\"+ "location.txt");
Process p = new Process();
p.StartInfo.FileName = loc;
p.StartInfo.UseShellExecute = true;
p.Start();
I tried running it as p.StartInfo.Verb = "runas"; but this has no positive result either. Could this be an issue with the Google Virtual Machine, possible firewall settings or code related issues.
Extra
This code does work on my own laptop and so does it work after restarting.

Process.Start() does nothing when called from a C# written service

I have created a service that works good, except for this section that don't do what I want
shutdownProcess.StartInfo.RedirectStandardError = true;
shutdownProcess.StartInfo.WorkingDirectory = #"C:\Program Files (x86)\Siemens\Automation\WinCC RT Advanced";
shutdownProcess.StartInfo.FileName = #"C:\Program Files (x86)\Siemens\Automation\HmiRtmShutdown.exe";
shutdownProcess.Start();
string errors = shutdownProcess.StandardError.ReadToEnd();
eventLog1.WriteEntry(errors, EventLogEntryType.Error, eventId++);
The problem is that the process is not executed;
as you can see I tried to record errors in a log, but the log records a empty string so it seems that there is no error;
This application works perfectly when I call it from cmd.exe; I also tried to use process.start() with cmd.exe passing the path as argument, but it did not work;
I installed the service as LocalSystem to give it maximum privileges;
I also tried to put the service into same folder and call only the .exe to exclude errors in writing the path; nothing
please help!
You cannot execute applications or executables which try to render a User Interface or are designed to require interactive login from a Windows Service which runs in background in UI less mode ( Session 0 from Vista onwards as others have comemnted ).
try to wite some unit tests and run your code from the unit tests in Visual Studio, if all works fine but then from the Windows Service does not work, then the problem is exactly the one explained above.

Running DLL/EXE program from windows service in Windows 7

I actually need an expert advice in resolving a situation regard calling InitPK.dll (C++ dll) as a service in windows 7 (Code attached). The dll is loaded successfully but PKAgentInit method is returning 0(false) on Windows 7 using windows service the same works okay in windows XP also the code works fine when exec as a console program on windows 7 .
Could you please guide us why PKAgentInit method is returning 0 on Windows 7 and what is the recommended way of calling Agent under Windows 7 using windows service.**
Code:
typedef UINT (CALLBACK* INITPK)();
m_LogDebug->Log(2,nThreadId,cMethod,
"Pre-requisite applications are running so executing Agent...");
hDll = LoadLibrary(AgentPath.c_str());
if(hDll == NULL)
{
m_LogDebug->Log(0,nThreadId,cMethod,
"Failed to load [%s]",AgentPath.c_str());
return false;
}
INITPK InitPK_Func;
if((InitPK_Func = (INITPK)GetProcAddress(HMODULE(hDll), "PKAgentInit")) == NULL)
{
m_LogDebug->Log(0,nThreadId,cMethod,
"Failed to load proc address [%s]",AgentPath.c_str());
return false;
}
UINT Res = InitPK_Func();
// returning 0 which means Agent is not executed successfully.
// Ideally it should return 1.
m_LogDebug->Log(0,nThreadId,cMethod,"PKAgentInit returned [%d]",Res);
Without seeing the source to InitPK_Func() it's hard to say but I'd guess that it's a privileges problem and the service isn't running as a user that can do what you need to do. Perhaps the code in question needs to be elevated (might be why it works on XP), or perhaps it's touching a network resource (might be why it works as a console app on Win7).
But really, you need to debug the problem function and maybe change it to return a little more information about why it failed.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I have written a few C# apps that I have running via windows task scheduler. They are running successfully (as I can see from the log files that they are writing ) but windows task scheduler shows them returning a last run result of 0xE0434352. Is there something I need to do in my C# application so that it returns a success code to the windows task scheduler?
Another option is to simply use the Application log accessible via the Windows Event Viewer. The .Net error will be recorded to the Application log.
You can see these events here:
Event Viewer (Local) > Windows Logs > Application
When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second.
If you will not do that and your program start not in directory with exe, it will not find files that are located in it.
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS instead of MAPDRIVELETTER: and I am up and running.
In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
I got the same error but I have fixed it by changing the file reading path from "ConfigFile.xml" to AppDomain.CurrentDomain.BaseDirectory.ToString() + "ConfigFile.xml"
In my case, this error due to file path error because task manager starts program from "System32" as initial path but the folder we thought.
I was getting the same message message within dotNet Core 2.2 using MVC 5, however nothing was being logged to the Windows Event Viewer.
I found that I had changed the Project sdk from Microsoft.NET.Sdk.Web to Microsoft.NET.Sdk.Razor (seen within the projects.csproj file). I changed this back and it worked fine :)
In my case it was because I had message boxes. Once I commented that code out, it started working. I remembered that could be a problem when I looked at the event log as suggested in this thread. Thank you everyone!
I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...
Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!
Also message box in PowerShell. I converted PowerShell script to exe. When running as admin it's worked but in task schedule I received this error also.
There was an line in PowerShell script with write-output. After commented this line and compile new exe Task Schedule was completed successfully.
It is permission issue in my case the task scheduler has a user which doesn't have permission on the server in which the database is present.

Start executable that uses python

I'm new to programming and C#, I am attempting to write a program that detects errors or server crashes from my battlefield 2 server, it will then shut the server down (if the server is not already down) and start it back up but I have ran in to a small bump. When I try to start battlefield 2 back up again I receive this error from bf2:
Debug assertion failed! Version 1.0.2446.12 Build date:
Module: Python
File:
c:\dice\Projects\BF2Branches\BF2Demo\Code\BF2\Game\Python\PythonHost.Cpp
Line:243
Text: couldn't import the bf2 module:
Current confile:
The path in the error doesn't exist.
I have researched a couple different ways to start up an application but they all have the same results. These are a couple I have tried so far:
Process proc = new Process();
proc.StartInfo.FileName = #"txtServerPath.Text";
proc.Start();
and
Process.Start(txtServerPath.Text);
When I manually start the bf2 Server it starts fine. So what am I doing wrong?
My program will be ran from both Windows Server 2003 and Windows 7 if that matters.
Debug assertion failed! Version 1.0.2446.12 Build date: Module: Python File:
c:\dice\Projects\BF2Branches\BF2Demo\Code\BF2\Game\Python\PythonHost.Cpp
Line:243
Text: couldn't import the bf2 module:
Current confile:
The path in the error does not exist because it is the path on the machine on which PythonHost.cpp was written. 'Debug assertion' means that the developer of the code put a condition check at the specified line number in the cpp file to check for a certain condition to be sure that 'everything works fine.' but obviously it isn't. It seems strange though that BF2 has installed a debug version.
Anyhow, your process does start but it errors out. And the problem, it seems is that it is unable to find a python module named 'bf2' when you start the process from within C#.
So first and foremost verify that {BF2 Install folder}\python\bf2\ __init__.py exist.
In order to gain more insight on why this might be happening, try to start BF2 like this (assuming your C# application is a console application):
Process bf2 = new Process();
bf2.StartInfo.FileName = #"C:\Program Files\EA Games\Battlefield 2\BF2.exe";
bf2.StartInfo.Arguments = "+debugOutput 1";
bf2.StartInfo.UseShellExecute = false;
bf2.StartInfo.RedirectStandardOutput = true;
bf2.StartInfo.RedirectStandardError = true;
bf2.Start();
Console.WriteLine(bf2.StandardOutput.ReadToEnd());
Console.WriteLine(bf2.StandardError.ReadToEnd());
This should print some logs on the console going through which, I suspect, something useful can be deduced.
By the way can you post the remaining error message (i.e. after 'Current confile:' line)

Categories