Settings.Default.Save() and Cursor.LoadFromStream lead to System.IO.IOException - c#

Two strange exceptions happened in .NET built-in components.
It's the same IO exception: "The process cannot access the file '......' because it is being used by another process".
In "cursor" case it's about ".tmp" file and exception happens somewhere at the end of the sequence of calls, when WPF grid is remeasured:
System.Windows.Controls.Grid.MeasureCell
...
System.Windows.Controls.GridViewColumnHeader.GetCursor
...
System.Windows.Input.Cursor.LoadFromStream <-- here
In "settings" case it's about ".newcfg" file and happens exactly on "save" method call.
The question is: how is this possible? And how to handle/prevent it?
I guess default implementations close XMLWriters and do everything correctly.

We had a single user with the same problem as your "settings" case (it's about ".newcfg"). It turns out that when they switched off their Norton Antivirus, the problem went away!
Some research I did prior to that may be of use:
Check if you have more than one thread capable of calling Settings.Default.Save(). If multiple threads are competing, it might produce this error, although I understand .NET is supposed to make this thread-safe.
It might possibly be happening if you have multiple calls to Settings.Default.Save() in quick succession, within the same thread. This can happen if several classes (e.g. user/custom controls) each want to save some settings, but none should have to be aware of the others' need to do this, and closing down the parent form causes each control to call the Save().
Check the user has appropriate write permissions in the target folder AND in the folder where the .exe is located. My colleague has seen a bizarre connection between the two!
Find all instances in your code where you call Settings.Default.Save(), and set a break point on all of them. When you run the program, you might notice some suspicious behaviour or pattern in the way they get called.
Hope this helps!

Related

How to fix random IOException: Sharing violation during import, build or compile?

From time to time, when I try to import, build or just compile, randomly Unity says that an:
IOException Sharing violation
I did a small research, but all the answers point to that error, when executing the code, not just build, and I say that is Random because It happens from time to time and every time the .dll in the Library folder that is marked in the Error, is completely different.
As some of the comments said, the error stopped appearing once I disabled the "Ransom/Encryption Protection" from my Antivirus (In this case Kaspersky) and also disabled it in the Windows options.
This can also happen, if a program interfers with itself in anyway, for example by having several projects run in parallel or a crashed instance holding onto a handle. Other candidates for handles might be Editors, other Background processes getting handles (e.g. thumbnail generators etc.).
Debugging should happen with a system tool to look at handles. Under windows for example ProcessExplorer(https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer) or Handle (https://learn.microsoft.com/en-us/sysinternals/downloads/handle). Set a breakpoint and then look at what caused the sharing violation.
Prerequisit is a clean software, meaning your own opened handles should be closed once they go out of scope. Some languages provide constructs for that, for example C#s using. Use them to preven dangling buffers.

COM Add-in: Resolve the error DisconnectedContext in WinWord.exe

I built an add-on to Microsoft Word. When the user clicks a button, it runs a number of processes that export a list of Microsoft Word documents to Filtered HTML. This works fine.
Where the code falls down is in processing large amounts of files. After the file conversions are done and I call the next function, the app crashes and I get this information from Visual Studio:
Managed Debugging Assistant 'DisconnectedContext' has detected a problem in 'C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE'.
Additional information: Transition into COM context 0x56255b88 for
this RuntimeCallableWrapper failed with the following error: System
call failed. (Exception from HRESULT: 0x80010100
(RPC_E_SYS_CALL_FAILED)). This is typically because the COM context
0x56255b88 where this RuntimeCallableWrapper was created has been
disconnected or it is busy doing something else. Releasing the
interfaces from the current COM context (COM context 0x56255cb0). This
may cause corruption or data loss. To avoid this problem, please
ensure that all COM contexts/apartments/threads stay alive and are
available for context transition, until the application is completely
done with the RuntimeCallableWrappers that represents COM components
that live inside them.
After some testing, I realized that if I simply remove all the code after the file conversions, there are no problems. To resolve this, I place the remainder of my code in yet another button.
The problem is I don't want to give the user two buttons. After reading various other threads, it sounds like my code has a memory or threading issue. The answers I am reading do not help me truly understand what to do next.
I feel like this is what I want to do:
1- Run conversion.
2- Close thread/cleanup memory issue from conversion.
3- Continue running code.
Unfortunately, I really don't know how to do #2 or if it is even possible. Your help is very much appreciated.
or it is busy doing something else
The managed debugging assistant diagnostic you got is pretty gobbledygooky but that's the part of the message that accurately describes the real problem. You have a firehose problem, the 3rd most common issue associated with threading. The mishap is hard to diagnose because this goes wrong inside the Word plumbing and not your code.
Trying not to commit the same gobbledygook sin myself, what goes wrong is that the interop calls you make into the Office program are queued, waiting for their turn to get executed. The underlying "system call" that the error code hints at is PostMessage(). Wherever there is a queue, there is a risk that the queue gets too large. Happens when the producer (your program) is adding items too the queue far faster than the consumer (the Office program) removes them. The firehose problem. Unless the producer slows down, the queue will grow without bounds and something is going to fail if it is allowed to grow endlessly, at a minimum the process runs out of memory.
It is not allowed to get close to that problem. The underlying queue that PostMessage() uses is protected by the OS. Windows fails the call when the queue already contains 10,000 messages. That's a fatal error that RPC does not know how to recover from, or rather should not try to recover from. Something is amiss and it isn't pretty. It returns an error code to your program to tell you about it. That's RPC_E_SYS_CALL_FAILED. Nothing much better happens in your program, the CLR doesn't know how to recover from it either, nor does your code. So the show is over, the interop call you made got lost and was not executed by Word.
Finding a completely reliable workaround for this awkward problem is not that straight-forward. Beware that this can happen on any interop call, so catching the exception and trying again is pretty drastically unpractical. But do keep in mind that the Q+D fix is very simple. The plain problem is that your program is running too fast, slowing it down with a Thread.Sleep() or Task.Delay() call is quite crude but will always fix the issue. Well, assuming you delay enough.
I think, but don't know for a fact because nobody ever posts repro code, that this issue is also associated with using a console mode app or a worker thread in your program. If it is a console mode app then try applying the [STAThread] attribute to your Main() method. If it is a worker thread then call Thread.SetApartmentState() before starting the thread, but beware it is very important to also create the Application interface on that worker thread. Not otherwise a workaround for an add-in.
If neither of those workarounds is effective or too unpractical then consider that you can automagically slow your program down, and ensure the queue is emptied, by occasionally reading something back from the Office program. Something silly, any property getter call will do. Necessarily you can't get the property value until the Office program catches up. That can still fail, there is also a 60 second time-out on the interop call. But that's something you can fix, you can call CoRegisterMessageFilter() in your program to install a callback that runs when the timeout trips. Very gobbledygooky as well, but the cut-and-paste code is readily available.

C# Application crashing upon closing custom form

I have went through different questions and didn't really find anything that suited my problem, but I also didn't exactly know what to look up to get any results either, so I may have missed some entries. If anyone could link to something that might be of assistance, I would greatly appreciate it.
I'll start off by posting a code example that I'm using (Is not the exact code, as I cannot release this) that I think is causing the application to crash.
using (var editForm = new frmEditableText("Alarm Note", "Title"))
{
var result = editForm.ShowDialog(this);
if (result == DialogResult.OK)
{
string temp = editForm.ReturnValue;
string xPath = String.Format("AlarmsDb/Alarm[Id = '{0}']/Notes", alarmID);
if (!Tools.OverWriteXMLSingleNote(alarm_xml_path, xPath, temp))
logErr("Error overwiting XML alarm: {0}", xPath);
AlarmDb.SetNote(alarmID, temp);
}
}
Tools is a private codebase that houses miscellaneous universal tools that get ported from project to project.
I'm not exactly sure what is going on. I know this code works as it is working on all other code lines I have used it in.
The only thing that is different is the PC itself.
The way it's setup is in a datagridview, on cell click it pops up a form for you to put your notes for that specific row and save them.
Once the form pops up, I close it and immediately the app crashes and won't recover, but there is no exception being reported either.
This only happens when not running through visual studio (matters not if it's a release or debug build, only if it is or isn't running in visual studio).
I'm sure I may have missed some details, please let me know if there is any other information you need from me, but this about sums up my issue.
EDIT:
With some further debugging, I've added multiple log statements in all places possible that would have to do with the form closing, opening, doing it's intended purpose.
What I've found is the FormClosing event makes it all the way through.
ShowDialog(this) is expected to return a DialogResult enum value, but hangs at the point of which it is actually attempting to return this value causing the application to freeze up.
I've also found that setting thread priority to AboveNormal for the thread which ends up calling the form gets rid of the issue. However I do not think that is a good enough solution.
It appears there was an oversight on my end, although I'm still not certain if this is the correct way to resolve my issue.
I don't have very much knowledge on the whole ApartmentState being MTA or STA, or how to identify when which should be used.
What did solve my issue though was going through all the threads that are spun off my main thread and setting their ApartmentState to STA, which I thought was already done from a previous codeline to resolve another issue I was having (such is the problem with collaboration).
But yes, I went through the entirety of my solution and found all instances of new threads being created and explicitly setting their ApartmentState to STA has resolved the crashing issue.
If anyone can provide some good material defining the differences and when to use either, or how to identify when one should be used over the other, it would be greatly appreciated.
did you try subscribing to the AppDomain.UnhandledException event? You can use this as a final catch all (no pun intended) and log to a file the exception see
https://msdn.microsoft.com/en-gb/library/system.appdomain.unhandledexception(v=vs.110).aspx
Alternatively/additionally - did you look in the event viewer?
Good luck

how to set error message for C# application supporting application missing

I am maintaining C# desktop application, where the application becomes unresponsive during setup if the supporting application (say, excel, audio driver) is disabled or not installed. I need to set an error message corresponding to the application that was not installed. what would be the modification I need to do and the corresponding code that need to be changed?
Thanks in advance!!
I'm going to assume that by "Setup" you mean first-time execution; this answer may not cover installer problems. If you're having a problem with an installer, please updates your tags accordingly.
In a nutshell, there's no code you can modify to make this work as described. You're receiving exceptions from .NET, and while .NET is open source and you could potentially modify in changes, you won't be able to guarantee that your modified assemblies appear on client machines, and thus the changes are useless.
You're better off trying to catch exceptions as they happen, report, and cleanly exit. The easiest way to do this is to make sure your Main function wraps most/all execution in a try-catch, and assume anything caught by this top-level catch is a critical error and results in immediate shutdown.
For debugging, note that you can always attach to the FirstChanceException, however this is rarely recommended as a reporting feature as it will catch a number of exceptions that don't actually kill your application.

Program do not stop after close Window [duplicate]

whenever i try to run program for example,
if i have to run "frmphonebook" so in
Application.Run(new frmphonebook());
I typed but when i run it it run another form, and it happens to each and every form and it is displaying output as
The thread 'vshost.RunParkingWindow' (0x63c) has exited with code 0 (0x0).
The thread '<No Name>' (0xb24) has exited with code 0 (0x0).
how to solve this ?
You can give your threads a name it would also help you in your debugging...
But in many apps threads are created implicitly and you have no control over the name.
So that is not an error message. Code 0 means everything went according to plan. Any non-zero code usually indicates an error.
edit: You can also disable the display of these messages, when debugging, do right click on output, and choose what do you want see.
If a thread has exited with code 0 it ran successfully. On Codeproject is a Beginners-Guide-to-Threading
This article on threading might also be helpfull. This question on so could also be of use. A list of System Error Codes
One of the things you will learn about using the Debugger is that you will see what we might call "the soft white underbelly" (an allusion to alligators' anatomy) of the system: all kinds of DLLs being loaded and unloaded, the somewhat complex arrangement of "helper" threads being started and stopped... etc.
It can be distracting to a less experienced user, to see all of these messages. However, over time, you will come to understand that the Debugger is simply being truthful and verbose. The details it is displaying for you might not really be relevant to your debugging process, but it cannot "know" that; it is only displaying factual information, and you have to sort out what is relevant and what is not.
As for Windows Forms applications, I have myself noticed that there seem to be several "helper" threads, typically with no name, or (as is frequently seen by me when debugging), they are named things like "vshost.RunParkingWindow". Typically, you have to trust that the system is creating threads on your behalf, in addition to any threads you might create yourself. As others have suggested, give your own threads meaningful names so you can tell them apart from the system's threads.
You can get further insight into the multithreaded structure of your Windows Forms app by putting a breakpoint somewhere in your UI update code, and when it hits, use Debug/Windows/Threads to bring up a view of all the threads running in your process space. You'll be quite surprised, I think, by how many there are! Try creating and .Show()-ing several forms in your app, one by one. I think you'll see that each .Show() operation creates a new window, and with it, several supporting threads for that window.
You may also see messages in the debug window such as the following: "A first chance exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll". Many times there are system exception handlers that perform a reasonable default action on your behalf. This message appearing without a break in the debugger indicates that some default handler took care of this exception for you.
The system support for something like a Windows forms application is somewhat complicated, to make YOUR implementation easier and simpler. When you run the debugger, you get to see some of these details. Over time, you will learn what is "usual" and what is indicative of a problem.
Check to see if there are some files in your web app that have been rendered inaccessible. For my case my chart control created a text file which was read only and it threw an exception. Deleted the file and the folders and voila
i found your solution i think....i the visual studio go to project >properties >linker >system look for the Subsystem line and click the down arrow and change to Console(....words....).
it worked for me !! ENJOY"

Categories