Exception on Application Closing - c#

I developed a WPF Application where I have problems when closing the application.
Only on Windows 2003 PCs, the application throws the following exception on closing. But it does not seem to be thrown from my code, because I can't get a callstack.
That's why I can't post any further details.
Do you have a clue where I can start digging into it?
System.InvalidOperationException was unhandled
Message=Handle is not initialized.
Source=mscorlib
StackTrace:
at System.WeakReference.set_Target(Object value)
at System.Windows.Threading.Dispatcher.FromThread(Thread thread)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.IntDestroyWindow(HandleRef hWnd)
at MS.Win32.HwndWrapper.DestroyWindow(Object args)
at MS.Win32.HwndWrapper.Dispose(Boolean disposing, Boolean isHwndBeingDestroyed)
at MS.Win32.HwndWrapper.Finalize()
InnerException:
Thanks for your ideas.
EDIT
I found out which lines of code produces the failure. But how can I fix it?
It's the following line of code:
try
{
return DesignerProperties.GetIsInDesignMode(new DependencyObject());
}
catch (Exception)
{
return true;
}
I'm using this to check if the code runs in the designer. But on closing this code fails, although I catched the exception.
Any other ideas to check the designmode?
Thanks for your help.

To answer my own question ...
I could solve the issue by implementing a backing field for the IsInDesignMode Property. The backing field is now going to bet set within the constructor of the ViewModel, instead of my prior solution which checked the DesignMode on every method call.
That means, that even within the Dispose Method it can be checked if the application is/was running in DesignMode.

Related

Using Console.Clear() in a Windows Docker Image?

I'm trying to containerize a .net framework console application for testing and learning.
The application works just fine outside the container.
However, I'm getting this error for every Console.Clear() call:
Unhandled Exception: System.IO.IOException: The handle is invalid.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.Clear()
at project.Program.Main(String[] args) in C:\Users\project\Program.cs:line xxx
I can "sort" this out by encasing the Console.Clear() lines in try-catch, but that would be a mess and won't really solve the issue, just hide it under the carpet.
I want to understand why is this happening and how to solve it.
For propietary reasons I can't post the entire solution here.
This is the dockerfile i'm using:
FROM mcr.microsoft.com/windows/servercore:ltsc2019
ADD "release" "c:/release"
CMD powershell "C:/release/project.exe"
EXPOSE 80 443
I suspect this is because a console is not well handled by a container, but why exactly is the Clear() method of Console falling and not everything else?
Why does the container lacks the handler for that particular method? Is it because it's windows core?
You are getting an error because System.Console.Clear (along with other methods that attempt to control/query the console such as System.Console.[Get|Set]CursorPosition) requires a console/TTY but none is attached to the program.
To run your code as-is, you should be able to use the --tty option to docker run to allocate a pseudo-TTY, e.g. docker run --tty <image>.
To modify your code to not require this, you'd probably want to create your own wrapper for System.Console.Clear that wraps it in a try-catch:
void ClearConsole()
{
try {
System.Console.Clear();
}
catch (System.IO.IOException) {
// do nothing
}
}
If only targeting Windows, you can alternatively do a P/Invoke call to GetConsoleWindow to check whether a console exists before calling System.Console.Clear:
class Program
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern System.IntPtr GetConsoleWindow();
static void ClearConsole()
{
if (GetConsoleWindow() != System.IntPtr.Zero)
{
System.Console.Clear();
}
}
}

IDocHostUIHandler crashing MSHTML.dll with error 0xc0000409

I am using slightly modified IDocHostUIHandler from https://stackoverflow.com/a/21699086/592212 in simple one main window test application with only WPF WebBrowser component in that Window. The initialization code is as follows:
public MainWindow()
{
InitializeComponent();
_wbHostHandler = new WebBrowserHostUIHandler(PART_WebBrowser);
_wbHostHandler.Flags |= HostUIFlags.DpiAware;
PART_WebBrowser.Navigate("SOME_URL");
}
There is really nothing else going on in the Application. Still, after running the application, an error is thrown in COM component (therefore, I can not use a debugger to trap it) and 0xc0000409 (STATUS_STACK_BUFFER_OVERRUN) is reported in Event Viewer.
Any ideas of what is causing the error or how to get rid of it?
(Win10 Pro 1703 (build 15063.483) and .NET 4.6.2)
Source Code: https://www.dropbox.com/s/ddob6p7jh4dfsda/UIHostCrashDemo.zip?dl=1
I don't know where you got your WebBrowserHostUIHandler.cs content from but it's wrong. The definition of IDocHostUIHandler simply misses the TranslateAccelerator method.
I guess it's because my initial code used System.Windows.Forms.Message type which is a reference to the System.Windows.Forms (winforms) assembly. If this is such a problem, the method can just be replaced by this if the message is not used (wich is the case in my initial code).
So in the interface you must add this, just after ResizeBorder:
[PreserveSig]
uint TranslateAccelerator(IntPtr msg, ref Guid group, int nCmdID);
And you must implement it anywhere in the code, like this:
uint Native.IDocHostUIHandler.TranslateAccelerator(IntPtr msg, ref Guid group, int nCmdID)
{
return S_FALSE;
}
But again, this is optional, if you want something that works just carefully copy/paste my code from my post and add a reference to System.Windows.Forms if needed.

UnmanagedFunctionPointer causes stackoverflow when using .NET 4.0, 3.5 works

I have a simple function inside of a click handler that has a try catch block. If I throw an exception within this try catch block it catches the exception successfully.
If I put a call to an unmanaged DLL before I throw the exception the exception is unhandled and not caught.
What is the unamanged DLL call doing that could be breaking my programs exception handling?
If I run the program in debug mode it catches the exception even with "break on exception" unticked for all exceptions. The application does not crash and runs as expected.
If I run the program as "start without debugging" and hit debug when it crashes I get the following error "Stack cookie instrumentation code detected a stack-based buffer overrun"
edit:
It appears the stack overflow breaks the exception handling
I've attached a simplified program that produces the crash.
ISOConnection _comm; //This is instantiated at another time in the same thread
//C# test function that crashes when run without a debugger attached
bool DoMagic()
{
try
{
//if I uncomment this line the exception becomes unhandled and cannot be caught
//_comm.ConnectISO15765();
throw new Exception();
}
catch (Exception ex)
{
MessageBox.Show("Caught exception")
}
//Within ISOConnection class
public void ConnectISO15765(){
...
lock(syncLock){
uint returnCode = J2534Interface.PassThruConnect((uint)DeviceId, (uint)ProtocolID.ISO15765, (uint)ConnectFlag.NONE, (uint)BaudRate.ISO15765, ref ChannelId);
//C# UnmanagedFunctionPointer allocation code
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate uint PassThruConnect(uint deviceId, uint protocolId, uint flags, uint baudRate, ref uint channelId);
public PassThruConnect Connect;
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
m_pDll = NativeMethods.LoadLibrary(path);
...
pAddressOfFunctionToCall = NativeMethods.GetProcAddress(m_pDll, "PassThruConnect");
if (pAddressOfFunctionToCall != IntPtr.Zero)
Connect = (PassThruConnect)Marshal.GetDelegateForFunctionPointer(
pAddressOfFunctionToCall,
typeof(PassThruConnect));
//C++ function declaration
long PassThruConnect(unsigned long DeviceID, unsigned long ProtocolID, unsigned long Flags, unsigned long Baudrate, unsigned long *pChannelID);
UPDATE
If I replace the call to the UnmanagedFunctionPointer PassThurConnect with the following the crash does NOT occur
[DllImport("op20pt32.dll", EntryPoint = "PassThruConnect", CallingConvention = CallingConvention.Cdecl)]
public static extern uint PassThruConnect2(uint deviceId, uint protocolId, uint flags, uint baudRate, ref uint channelId);
Is there something I am not performing or I am performing incorrectly when assigning the UnmanagedFunctionPointer that would cause the lack of a debugger to create a stackoverflow crash?
What is even stranger is this code appeared to work a few weeks ago. The main changes is the try catch was in another thread and I wasn't using lock(syncLock). Everything is now in one thread however the same crash occurred when run in a BackgroundWorker as well.
UPDATE #2 PROBLEM SEMI-SOLVED
Ok so I rolled back through my commits one by one until it worked. What changed is I went from .NET 3.5 to .NET 4.0
.NET 3.5 does not crash regardless of attaching a debugger or not. .NET 4.0 crashes if a debugger is not attached. To rule out a bug in my code I simply deleted the ConcurrentQueue for my log (the only 4.0 feature I was using) and converted my current code base back to 3.5 and I do not get this error.
To be 100% sure it is an issue with 4.0 I then converted my code base back to 4.0 from 3.5 and left the ConcurrentQueue out (literally just changed the build options and did a rebuild) and the StackOverflow crash is back.
I would prefer to use 4.0, any ideas how to debug this issue?
edit: .NET 4.6.1 also crashes
UPDATE #3
http://codenition.blogspot.com.au/2010/05/pinvokestackimbalance-in-net-40i-beg.html
Apparently pinvokestackimbalance is basically ignored in .NET 3.5, so the problem still exists, it just doesn't crash my application.
Adding the following code to App.Config causes .NET to repair the stack when transitioning back to managed code. A small performance hit but it will fix the problem.
Whilst this does fix the problem, I'd like to know what is wrong with my UnmanagedFunctionPointer to cause the problem in the first place.
<configuration>
<runtime>
<NetFx40_PInvokeStackResilience enabled="1"/>
Edit: this thread isn't a duplicate, the other one is deleted...
Ok so the problem is the calling convention should be StdCall not Cdecl
This makes sense as the generic J2534 API documentation specifies the following header. Although the header file I was supplied does not make this specification.
extern "C" long WINAPI PassThruConnect
(
unsigned long ProtocolID;
unsigned long Flags
unsigned long *pChannelID
)
Where WINAPI is also known as StdCall not Cdecl like most C/C++ libraries would typically use.
.NET 3.5 allows the wrong calling convention and will "fix" the stack. As of 4.0 this is no longer the case and a PinvokeStackImbalance exception is raised.
You can force 4.0 to also fix the stack with the following code added to your App.Config
<configuration>
<runtime>
<NetFx40_PInvokeStackResilience enabled="1"/>
Or you can simply fix your calling convention by changing Cdecl to StdCall:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate uint PassThruConnect(uint deviceId, uint protocolId, uint flags, uint baudRate, ref uint channelID);

Strange intermittent error using TxNTFS

I'm using Transactional NTFS to read and write to files on the filesystem and I've noticed that the application encounters intermittent faults which as only solved by an app restart.
The stack trace for the error is:
System.Runtime.InteropServices.COMException (0xD0190052): Exception from HRESULT: 0xD0190052
at ...KtmTransactionHandle.IKernelTransaction.GetHandle(IntPtr& handle)
at ...KtmTransactionHandle.CreateKtmTransactionHandle(Transaction managedTransaction)
at ...KtmTransactionHandle.CreateKtmTransactionHandle()
at ...TransactedFile.Open(String path, FileMode mode, FileAccess access, FileShare share)
at ...TransactedFile.ReadAllText(String path)
IKernelTransaction is a COM Interface that I get a handle to:
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("79427A2B-F895-40e0-BE79-B57DC82ED231")]
private interface IKernelTransaction
{
void GetHandle([Out] out IntPtr handle);
}
here
IKernelTransaction tx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
My code is very similar to http://msdn.microsoft.com/en-us/library/cc303707.aspx
The problem is that I cannot find any information of this COM error 0xD0190052. Just knowing what this error code is would be hugely helpful.
Thanks
Pure speculation
The HRESULT 0xD0190052 is very similar to STATUS_TRANSACTIONMANAGER_NOT_ONLINE which is 0xC0190052... the difference is in the "N"-Bit which indicates whether the code is a so-called NTSTATUS (see http://msdn.microsoft.com/en-us/library/0642cb2f-2075-4469-918c-4441e69c548a%28PROT.10%29.aspx and http://msdn.microsoft.com/en-us/library/cc231200%28v=PROT.10%29.aspx and http://msdn.microsoft.com/en-us/library/cc704588%28v=PROT.10%29.aspx )...
From what you describe it seems either your application sometimes looses the connection to the transaction manager or the transaction manager is unstable/restarted or similar...
Also definig PreserveSig(true) on your COM import could help getting some HRESULT description...
Hope this makes any sense in your case...
EDIT:
I am not sure that the code you linked to is taking into account all possibilities... in the method TransactedFile.Open there is a call to scope.Complete(); which is good and necessary BUT if some code before this call within the using-block throws some exception it does not get called which is bad according to http://msdn.microsoft.com/en-us/library/ms172152.aspx

Marshal.ThrowExceptionForHR throws a NotSupportedException

im using the following pattern for translating win32 exceptions into .NET exceptions.
var result = A_KERNEL32_PINVOKE_CALL();
if (result == 0)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
For completeness the pinvoke call is one of the following: LoadLibrary, GetProcAddress, SetWindowsHookEx.
This works well most of the time, throwing exceptions like this one:
System.ArgumentException: Argument out of range.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
But sometimes I get the following exception:
System.NotSupportedException: This Stream does not support seek operations.
at System.Net.ConnectStream.get_Position()
at System.Net.WebClient.WebClientWriteStream.get_Position()
at System.Drawing.UnsafeNativeMethods.ComStreamFromDataStream.Seek(Int64 offset, Int32 origin)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
I can't think of a reason for this exception. Please note that the stack trace doesn't start with ThrowExceptionForHRInternal like the first exception. Hence I think this might be a exception of the ThrowExceptionForHR method itself.
EDIT: Please note that I'm not calling any Stream methods directly. However the code is executed in a thread pool thread, so there might be other code in the same thread using Stream methods.
Any suggestions how to solve this issue?
UPDATE: I just found out, that the stack trace
at System.Net.ConnectStream.get_Position()
at System.Net.WebClient.WebClientWriteStream.get_Position()
at System.Drawing.UnsafeNativeMethods.ComStreamFromDataStream.Seek(Int64 offset, Int32 origin)
belongs to a call to Image.Save(Stream, Format). There a the NotSupportedException is caught. These code peaces are completely independant, but maybe they are executed on the same thread pool thread.
So why does this exception influence my code in another method?
By now I think, that I misused the Marshal.ThrowExceptionForHR() method. I suppose that it's not intended to be used with a Win32 call. My interpretation of the behavior is, that the function uses context information of the current thread to gather more details about the exception. See this blog for a similar problem.
In my case the issue can be solved by creating my own ThrowExceptionForWin32ErrorCode(errorCode) method.
Please keep answering, if you got a better solution.
I don't know why ThrowExceptionForHRInternal tries to manipulate some stream.
While call stack looks strange, consider not passing stream directly from Web response to drawing functions which seem to cause exception in your case but copy data to memory stream first. This will likely allow you to see what original problem is (as ThrowExceptionForHRInternal will no longer fail trying to manipulate a stream).

Categories

Resources