Console application not closing - c#

I'm developing a console application that is supposed to run under WinCE 6.0 and WinCE 7.0. I'm using C#, Compact Framework 2.0 for different compatibility reasons.
My application is started by an external runtime called TwinCAT (from Beckhoff). Within this application, my teammate used a function block called nt_startProcess (documentation here) that is in charge of starting my application on demand.
My problem - Two different behaviors depending on the OS :
When started manually (without TwinCAT) from a cmd line :
My application behaves properly on both systems. It means that, the applications starts, displays "Hello World" and then returns to the cmd line.
When started from TwinCAT :
a) On WinCE 6.0, I can see a cmd line opening, displaying "Hello World" and shutting itself right after. Perfect behavior to me.
b) On WinCE 7.0, I can see a cmd line opening, displaying "Hello World" but it remains open forever. This is my problem!
Code snippet :
using System;
using System.Collections.Generic;
using System.Text;
namespace MyBasicExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Compilation information
In Visual Studio 2008, within the Project compilation's properties :
Plateform target : Any CPU
Additionnal note :
Please note that the computer who is running WinCE 6.0 is using a i486 processor while the one running WinCE 7.0 is using a Freescale ArmCortex process.
WinCE 6.0 :
WinCE 7.0 :
What I tried :
1) Using return 0; at the end of application.
Doesn't change anything on WinCE 7.0.
2) Using Environment.Exit(0);
Is not available in Compact Framework 2.0.
3) Using the property : IsBackground
Snippet :
// ... Same snippet as above except for the next line...
Thread.CurrentThread.IsBackground = true;
Console.WriteLine("Hello World");
// ...
4) From TwinCAT, calling a batch file (which calls my exe) instead of my exe.
Doesn't work with TwinCAT. I get an error of type "General Sub-Windows error".
5) Tested with the Compact Framework 3.5.
Same behavior.
6) Tested with another CX computer (model 2020) using Windows CE 7.0 and another processor architecture (Intel Pentium III Xeon Model A).
Same behavior.

try this code:
Environment.Exit(0);

Try this:
Tools > Options > Debugging > Automatically Close the Console When Debugging Stops

Are you putting you .exe file in Arguments property of ProcessStartInfo ?
If you must do that, I believe that you're using CMD in FileName property, so you must use /K before your .exe name.
Or just put in FileName the .exe path.
You can clarify a lot if you put the code that calls your application.

Try calling Application.Exit
This works in windowed applications, and may force the console window to close.

I had exactly the same problem. Running console app on Beckhoff PLC which never closed.
Instead of creating Console app I created Windows App.
My code stayed the same as for console app. I just commented out:
// Application.Run(new Form1());
Seems now codes run without opening a form.

Related

Are there any dependencies for UI Automation?

I have a Windows application which captures the details from screen based on the configuration. I am using UI Automation to capture the details from the screen. Everything works fine on the developer's machine where Visual Studio is installed. When I run the same application on another system where we have only .NET Framework 4.5 installed, it started behaving strangely, and it's not able to detect the child element.
My question is why it works fine on the developer's machine where Visual Studio and .NET Framework are installed. What's the difference? Is there anything we are missing as far as prerequisites? Any dependencies of UI Automation or any library we are missing..?
Thanks in advance - please help me out.
It looks like a known bug in .NET wrapper around native UIAutomationCore.dll (yes, its core is not a .NET). And it's included into WinVista+ (.NET Framework also adds it even to WinXP).
Here is a C# example how to use native COM API (UIAutomationCore.dll) from C#. Just copying the code here:
using System;
using interop.UIAutomationCore;
namespace PrintDesktopUiaElementNameViaCom
{
class PrintDesktopUiaElementNameViaComProgram
{
static void Main(string[] args)
{
// Instantiate the UIA object:
IUIAutomation _automation = new CUIAutomation();
// Get the root element
IUIAutomationElement rootElement = _automation.GetRootElement();
// Get its name
string rootName = rootElement.CurrentName;
Console.WriteLine(
"The root automation element's name should be 'Desktop'.");
Console.WriteLine("The actual value is: '{0}'", rootName);
}
}
}
Yeah at last after doing day's reading, i came to know the solution is that der is no dependency on Visual studio.
This behavior is due to lack of privileges to the application. so to overcome this behavior we have to get signed our application and one more thing its very important thing is place your executable file in Program Files
Reference Links : https://msdn.microsoft.com/en-us/library/windows/desktop/ee671610(v=vs.85).aspx

Running C++ app from C# process running on Mono. run-detectors error

I'm currently working on porting a tool to Linux. I'm using mono to to this, and have got the main tool running. However, this tool calls another program, which is written in C++ and compiled natively on Linux with g++. I've had a lot of difficulty porting this over, but have it working and running (runs as expected with ./othertool.exe).
However, when trying to run the original tool on Mono, it fails at launching the other tool, giving a error.
run-detectors: unable to find an interpreter for .../othertool.exe
I'm not sure why this happens, as when testing with a hello world, I managed to get a C++ program running by calling it from C# on Mono. I'm running the other tool using the Process class (see code) which works fine with the hello world example.
var process = new Process
{
StartInfo =
{
FileName = baseDir +
Path.DirectorySeparatorChar +
"tools" +
Path.DirectorySeparatorChar +
"othertool.exe",
Arguments = arguments.ToString(),
UseShellExecute = false
}
};
process.Start();
process.WaitForExit();
Anyone know why this happens? Google does not yield anything so I guess this might not be common. Feel free to ask for more information or clarity, as I've probably left something out.
Ok so turns out that I was somehow using the Windows built version of othertool instead of the Linux one. Who let that happen? Runs 'fine' when using the correct one. – Cameron
Cool, run-detectors/interpreter failures usually (always?) are related to PE executable (.exe) issues (and other non-Linux binaries), assuming you are on a Linux disto (like Ubuntu) that support launching PE format but without something like Wine installed, you will get a failure. IMHO: Naming non-PE/non-CIL files as an .exe is bad-form on Linux...
– SushiHangover

ServiceBase service error 193:0xc1 on Windows XP

I have a service that I've built using the C# ServiceBase class. It works when I run it in Windows 7 and Windows Server 2008; however, it doesn't work on Windows XP.
I created the service using sc create PBUService binpath= "C:\PBULogger.exe". This is the correct path.
Nothing is logging in the Event Viewer under anything and my exception handling code doesn't fire either.
I thought maybe I didn't have the correct .NET version installed, but I have 4.0 installed on the XP machine. However, I created this project using Visual Studio Express 2012, which I'm pretty sure uses .NET 4.5 by default. Is this causing an issue? All the classes I'm using are version 4.0.
I have stripped down all my code to the base methods and this still doesn't work. Here is my code:
namespace PBULogger {
class PBULoggerService : ServiceBase {
protected override void OnStart(string[] args) {
try {
base.OnStart(args);
} catch (Exception ex) {
EmailUtility.sendEmail("Service Error", ex.Message + ex.StackTrace);
}
}
protected override void OnStop() {
base.OnStop();
}
}
Since it doesn't log in the event viewer, it tells me it isn't even trying to start the service.
I found these entries in my registry for the service under 'HKEY_LOCAL_MACHINE/System/ControlSet001/Enum/Services/PBUService/Enum'.
Not really sure what it means.
Anybody know what's going on?
You must have compiled your exe either for .Net 4.5 or for 64-bit architecture (or both). This is the explanation of error code you run into from WinError.h:
// %1 is not a valid Win32 application.
//
#define ERROR_BAD_EXE_FORMAT 193L
Make sure you have compiled it for x86 platform or Any CPU, and whatever version of .Net Framework you compiled against is installed on the machine.
I found this after googling the windows service error number:
*Generally the error message means that the service manager couldn't find the exact .exe path to run the service. Sometimes, the service is installed from a directory with multiple words for the directory name. So the registry path to the service needs to be placed with double quotes.
Click ‘Start’ and type ‘services.msc’ and hit Enter
Check for the multimedia class scheduler and audio endpoint builder service.
Check for the path under "path to executable:" for both the services. Make a note of the same.
Also make a note of the service name for both the services.
The services are as follows:
AudioEndpointBuilder - AudioEndpointBuilder
Multimedia Class Scheduler - MMCSS
Now, let’s check if the paths under these two services are the same as well in the registry.
Click ‘Start’, type regedit and hit Enter
Locate the following key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
Under services, check for these services: MMCSS and AudioEndpointBuilder.
Corresponding to the above two services, the Image path (on the right pane) should be same as the path in ‘services.msc’*
I found it here
In our case this happened after a server crash and the exe file got corrupted. We re-deployed the binaries and then the service started successfully.
In my case, this was due to building with target of 64-bit only. I forgot that one of my test servers running Server 2003 was 32-bit. My service runs fine on the 64-bit Server 2008 R2 box.
I think that there is a compatibility problem with .net framework that you use and windows server 2003.Do you use .net 4.5? Windows server 2003 can't run applications which target net framework 4.5.
http://www.microsoft.com/visualstudio/eng/products/compatibility
So you could change your target framework to 4.0.

PerformanceCounters on .NET 4.0 & Windows 7

I have a program that works fine on VS2008 and Vista, but I'm trying it on Windows 7 and VS2010 / .NET Framework 4.0 and it's not working. Ultimately the problem is that System.Diagnostics.PerformanceCounterCategory.GetCategories() (and other PerformanceCounterCategory methods) is not working. I'm getting a System.InvalidOperationException with the message "Cannot load Counter Name data because an invalid index '' was read from the registry."
I can reproduce this with the very simple program shown below:
class Program
{
static void Main(string[] args)
{
foreach (var pc in System.Diagnostics.PerformanceCounterCategory.GetCategories())
{
Console.WriteLine(pc.CategoryName);
}
}
}
I did make sure I'm running the program as an admin. It doesn't matter if I run it with VS/Debugger attached or not. I don't have another machine with Windows 7 or VS2010 to test it on, so I'm not sure which is complicating things here (or both?). It is Windows 7 x64 and I've tried forcing the app to run in both x32 and x64 but get the same results.
It seems performance counters were corrupted on my system. Although I didn't follow this post exactly, it led me to the solution. Here is what I did:
In an command prompt with administrator/elevate privileges typed the following:
lodctr /?
Useful stuff in there...
Then typed:
lodctr /R
According to the docs from the prior step, this gets windows to rebuild the perf registry strings and info from scratch based on the current registry settings and backup INI files. I have a feeling this is what did the magic. However, next I noticed the .NET performance counters were not there anymore so based on this I typed the following to reload them:
lodctr "C:\Windows\Microsoft.NET\Framework64\v4.0.20506\corperfmonsymbols.ini"
Note that this path is for .NET Framework 4.0 on x64. You can imagine the path for other variations of the framework/platform. I'm guessing you should always load the counters from the highest version of the .NET framework that you have installed, but that is just a guess.
I hope this helps someone else someday!

What makes an app console or Windows Form application?

[Visual Studio 2008]
I created a new project for console application and modified it to look like this:
class Program
{
static void Main (string[] args) {
Thread.Sleep (2000);
}
}
Then I created another project for Windows Form application and modified it:
static class Program
{
//[STAThread] commented this line
static void Main (string[] args) { //Added args
//Commented following lines
//Application.EnableVisualStyles ();
//Application.SetCompatibleTextRenderingDefault (false);
//Application.Run (new Form1 ()); commented this line
Thread.Sleep (2000);
}
}
Now I have neither written Console functions (Console.Write etc.) in first application nor I have written forms related operations in second one. Looks identical to me.
Still first application shows BLACK window and second one doesn't show anything. What makes it work like this?
If you inspect the exe files usine ILDASM you can see that there is a difference in the Manifest (look for "subsystem").
In a Winforms application:
.subsystem 0x0002 // WINDOWS_GUI
In a console application:
.subsystem 0x0003 // WINDOWS_CUI
There may be more differencies in the IL code.
When it comes to what makes the compiler emit this differently in the two cases, this is controlled by the project file's OutputType value:
In a Winforms application:
<OutputType>WinExe</OutputType>
In a console application:
<OutputType>Exe</OutputType>
Out of curiosity I also checked that value for a Class Library project:
<OutputType>Library</OutputType>
In project properties, Application Tab, Output Type you can set to 'Windows Application' or 'Console Application'.
I believe that behind the scenes VS does exactly what Fredrik presented in his post.
Also, setting it to Console Application will show you the black console application for the windows Forms project.
Under the bonnet, there is no difference in a winform vs console exe except for a flag in the PE-header that says "I need a console". The PE header is not controlled from your C# (since it is a compile thing, not a runtime thing), so this is defined in the project file instead (<OutputType>...</OutputType>).
Or at the command-line (csc /target:exe vs csc /target:winexe).
Arguably, they could have used an assembly-level attribute that the compiler intercepted - but would that really have helped? Probably not.
If you look in the project file (csproj) you'll see that the target is defined there as either a console or windows app.

Categories