Strange intermittent error using TxNTFS - c#

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

Related

How to fix random FileSystemEnumerableIterator.MoveNext Error. The handle is invalid

I just started randomly getting the error on a program that has been running for years. all this program does is look at a set of directories and delete files based on their last write time.
Here is the error and stack trace.
Error: The handle is invalid.
Stack Trace: at System.IO.__Error.WinIOError(Int32 errorCode, String
maybeFullPath) at System.IO.FileSystemEnumerableIterator`1.MoveNext()
at DirectoryCleaner.Program.GetNewFiles()
Here is the code
DirectoryInfo di = new DirectoryInfo(sourcePath);
foreach (FileSystemInfo file in di.EnumerateFileSystemInfos(variablePattern == true ? "*" : SearchPattern, searchSubDirectories == true ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
{
creates queue of records to delete. I removed the logic as it is rather long...
}
I have spent several hours searching. I found
System.IO.IOException: The handle is invalid, when using Directory.EnumerateDirectories but it does not have an answer.
The stack trace shows that it is in the MoveNext method which I do not directly call. I assume the foreach loop calls it. How can I correct what is causing this?
This error occurs because the various file/directory EnumerateX methods are effectively wrappers around the native Win32 FindFirstFile function, and as per its documentation:
If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.
If we look at the relevant portion of the Framework Reference Source, we see that any error not handled explicitly is surfaced as an IOException. This would include INVALID_HANDLE_VALUE.
In other words, this is an expected potential exception while calling an EnumerateX method and your code should handle it correctly by catching the generic IOException. The docs for the various EnumerateX methods fail to call this out, which IMO is an omission, and as such I've opened an issue to get that fixed.

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();
}
}
}

Index was outside the bounds of the array in calling WCF API

I have developed a web application with ASP.net(C#, .Net Framework 4.0) in some part of the application I am calling an API to get some information. I noticed that some of the calls to API are failed and I got this error:
Index was outside the bounds of the array.
when I checked the stack trace I saw this :
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary2.set_Item(TKey key, TValue
value)
at Navitaire.Ncl.Validation.ValidationManager.getValidationAttributes(MemberInfo mi, Boolean& skip)
at Navitaire.Ncl.Validation.ValidationManager.validate(Object declaringObject, Object value, MemberInfo mi, List1 results)
at Navitaire.Ncl.Validation.ValidationManager.Validate(Object obj)
at Navitaire.Ncl.ServiceModel.ParameterValidationInspector.BeforeCall(String operationName, Object[] inputs)
at Navitaire.Ncl.ServiceModel.Remoting.BoilerplateSinkBase.InvokeBeforeCallInspectors(StateData stateData, RemotingMessage& message)
at Navitaire.Ncl.ServiceModel.Remoting.BoilerplateServerSink.ProcessMessage(IServerChannelSinkStacksinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders&
responseHeaders, Stream& responseStream)
at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders&
responseHeaders, Stream& responseStream)
I put a break point on the catch exception part, so every time that I got the error, application will stop and I can read the exception. I noticed that if in this moment I call the API again (move the cursor to the API call line) it works fine. so it means there is no problem with parameter that I am passing to the API.
I tried to run the application on three different environments with totally different network and different internet connection, but still I got the same error.
Can you please someone help me on this case?
Thanks
I suspect this is a problem with the API, rather than your code, especially if it works the second time you make the same call.
I believe the API is doing something with an internal dictionary, that doesn't quite get set up correctly the first time you call it, but by the second time, it has been and works "correctly".
Are you able to view / have access to the code for the API method your calling?
If so, you are best running that in debug alongside your application, placing a breakpoint on the entry to that method and stepping over the lines within it to see what it is doing and why it may be breaking.
If it's your API, or you're allowed to share the code of this method and you can't find the error yourself, please post up the code of the API method and I'll help you find what the cause could be.
If you are not able to view the code, I would suggest contacting the producer of the API if it's a private one, or if it's an open source API, share the link and provide a code sample of what your code looks like (showing how you make the API call) and we can help diagnose it.
I checked with the API developer and I found that there was some thing wrong on their side after they fixed the bug I did not get any error anymore.

Exception on Application Closing

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.

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