My application uses Word interop for "active reporting" functionality. When the Word document is launched from the application, we set a EventWaitHandle to pause the application (creating a 'modal' effect) until the document is closed:
wh.WaitOne();
We have set an event on the word Application Quit event, where we then set the wait EventWaitHandle for the application to continue
wordGenerator.WordApplication.ApplicationEvents2_Event_Quit += WordApplication_ApplQuit;
private void WordApplication_ApplQuit()
{
wh.Set(); // signal that word has closed
wordGenerator.Dispose();
wordGenerator = null;
}
After this is called, the application then reads the document from the location it was stored and saves it into our database. All works great. UNLESS... the user makes changes in the document and doesn't CTRL+S but rather clicks close and gets prompted with the "would you like to save changes" prompt.
What happens in this instance that the quit event is fired as soon as you click close in Word, but Word is still open whilst the dialog to save changes is there. The application then continues to run and gets IO exceptions "Document is in use by another process" when trying to read the document to save to the database. Even waiting and retrying doesn't work as it seems that Word and the Application are waiting on eachother.
Is there another event I can use? I can't bypass the alert and automatically save as perhaps the user doesn't want to save.
Problem solved... easy one this time. Moved the dispose code above the .Set().
private void WordApplication_ApplQuit()
{
wordGenerator.Dispose();
wordGenerator = null;
wh.Set(); // signal that word has closed
}
Related
My goal is to force a process to run for at least 5 seconds (any amount of time really). I am working of the .NET Framework 3.5, with Service Pack 1. The idea is that the document holds some information that the user must see, so to safe guard against them immediately clicking to close the document, we can force it to stay open for some time. I developed a small test UI, consisting of a button, and then three radio buttons (one for each document). Here is my code behind...
I define the strings for the file paths, the string for the chosen file's path, and int to store the process's ID, a boolean for if they can exit the program, and the thread and timer declarations such as..
string WordDocPath = #"Some file path\TestDoc_1.docx";
string PowerPointPath = #"Some file path\Test PowerPoint.pptx";
string TextFilePath = #"Some file path\TestText.txt";
string processPath;
int processID;
bool canExit = false;
System.Threading.Thread processThread;
System.Timers.Timer processTimer;
In the constructor, I initialize the thread and timer, setting the thread's start method to a method called TimerKeeper(), and then I start the thread.
processTimer = new System.Timers.Timer();
processThread = new System.Threading.Thread(new System.Threading.ThreadStart(timeKeeper));
processThread.Start();
I have the timer set to count to 5 seconds, upon which it will set the canExit boolean to true.
public void timeKeeper()
{
processTimer.Elapsed += new System.Timers.ElapsedEventHandler(processTimer_Elapsed);
processTimer.AutoReset = false;
processTimer.Interval = 5000; //5000 milliseconds = 5 seconds
}
void processTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
canExit = true;
}
The rest is my button's click event, which deicides which file path to use to start the process, starts the timer, and then starts the process itself..
private void button1_Click(object sender, RoutedEventArgs e)
{
if ((bool)PowerPointRadioButton.IsChecked)
{
processPath = PowerPointPath;
}
if ((bool)WordDocRadioButton.IsChecked)
{
processPath = WordDocPath;
}
if ((bool)TextDocRadioButton.IsChecked)
{
processPath = TextFilePath;
}
try
{
canExit = false;
processTimer.Start();
while (!canExit)
{
processID = System.Diagnostics.Process.Start(processPath).Id;
System.Diagnostics.Process.GetProcessById(processID).WaitForExit();
if (!canExit)
{
processTimer.Stop();
MessageBox.Show("Document must remain open for at least 5 seconds.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
processTimer.Start();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error dealing with the process.\n" + ex.Message.ToString());
}
This actually works, for the most part. The user still can close the document, but if it has not been 5 seconds, it will reopen. Except for the word document (.docx). Things go smoothly for the powerpoint and text files, but the word document has some strange behavior (please note that all 3 files are in the same file directory). When I choose the word documents radio button and click the button, the word document opens, BUT I am also prompted with the message box from the catch block, alerting me that a "Object reference not set to an instance on an object" exception was thrown. This only occurs for the word document. Like I said, the word document still opens (I can see it's contents, just like the powerpoint or textfile). The exception causes the lines that check to see if they can exit to be skipped, so the document can close immediately, which is a problem.
Can anyone see my issue here? Or if there is a better way to doing all of this (I am a wpf/c# newbie)? I just don't understand why this only occurs for the word document, and not the powerpoint and text files.
If this is run on the user's desktop you are subject to the proper app being installed (e.g. Word) and how it is configured. If these are read only files on a share then I could convert them to XPS so you could show them in a DocumentViewer. And rather than force them to wait 5 seconds to click make them say yes to a dialog box that they have read and understand the document. Or have this on a page with an "I agree" button as MilkyWayJoe suggested.
The problem could be that the associated application is not the word application itself, but some intermediate application that launches word on your behalf.
To find out, keep a reference to the process object, and check if it has already terminated, what it's executable path is.
Having said that, why do you need this annoying behavior? You cant stop people from looking the other way. Is it supossed to fullfill some legal requirement or something?
If the user closes the Application a Save-File-Message have to be shown (to be sure that he wants to discard the changes of edited files).
to implement this, i have a menuitem with a command-binding (without key-gesture):
private void Command_Exit(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
the mainwindow has a closing-event. in this event i check if there unsaved files. if yes, the savedialog has to be opened (to choose, which files have to be saved):
private void Window_Closing(object sender, CancelEventArgs e)
{
if (sdl.Count() > 0)
{
SaveDialog sd = new SaveDialog();
IEnumerable<Doc> close = sd.ShowDialog(this);
if (close == null)
e.Cancel = true;
else
foreach (Doc document in close)
document.Save();
}
}
in this ShowDialog-Method (implemented in my SaveDialog-Class) i call
bool? ret = ShowDialog();
if (!ret.HasValue)
return null;
if (!ret.Value)
return null;
The problem is:
If i use the Alt+F4-Shortcut to close the Application (default-behaviour of the mainwindow) it works and i get the savedialog if there are unsaved files. but if i close the application by executing the Command_Exit-Method, the Method-Call
bool? ret = ShowDialog();
returns null and the dialog does not appear.
If i assign the Alt+F4 KeyGesture to the CommandBinding, the problem is switched: Executing Command_Exit works well but Alt+F4 Shortcut not.
What is the reason that the ShowDialog()-Method works not in both cases and how to fix it?
The Application.Current.Shutdown route allows you to listen for the shutdown request by handling the Exit event as detailed here:
http://msdn.microsoft.com/en-us/library/ms597013.aspx
It doesn't detail how it closes windows, so I wouldn't necessarily be convinced that the closing event handler would fire before it closes the application.
The other very standard way to shut the application down is to close the main window (the one shown at the very beginning). This would likely be the Window.Close method, if you are in the context of the window already, just call Close(). This will then hit the closing event handler.
Your Command_Exit implementation is wrong. Application.Current.Shutdown() means that the application is already shutting down, which can prevent the dialogs from opening.
You should implement the command other way: in the command you should ask your business logic if it's safe to shutdown, and issue Application.Current.Shutdown() only in that case. Otherwise, you should ask the business logic to start the shutdown sequence, which would in turn save the open files, and issue a Shutdown upon completing save operations.
Moreover, you should trigger the same routine when the user tries to close the main window (that is, on its Window.Closing).
In our C# WinForms application, we generate PDF files and launch Adobe Reader (or whatever the default system .pdf handler is) via the Process class. Since our PDF files can be large (approx 200K), we handle the Exited event to then clean up the temp file afterwards.
The system works as required when a file is opened and then closed again. However, when a second file is opened (before closing Adobe Reader) the second process immediately exits (since Reader is now using it's MDI powers) and in our Exited handler our File.Delete call should fail because it's locked by the now joined Adobe process. However, in Reader we instead get:
There was an error opening this document. This file cannot be found.
The unusual thing is that if I put a debugger breakpoint before the file deletion and allow it to attempt (and fail) the deletion, then the system behaves as expected!
I'm positive that the file exists and fairly positive that all handles/file streams to the file are closed before starting the process.
We are launching with the following code:
// Open the file for viewing/printing (if the default program supports it)
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = tempFileName;
if (pdfProcess.StartInfo.Verbs.Contains("open", StringComparer.InvariantCultureIgnoreCase))
{
var verb = pdfProcess.StartInfo.Verbs.First(v => v.Equals("open", StringComparison.InvariantCultureIgnoreCase));
pdfProcess.StartInfo.Verb = verb;
}
pdfProcess.StartInfo.Arguments = "/N"; // Specifies a new window will be used! (But not definitely...)
pdfProcess.SynchronizingObject = this;
pdfProcess.EnableRaisingEvents = true;
pdfProcess.Exited += new EventHandler(pdfProcess_Exited);
_pdfProcessDictionary.Add(pdfProcess, tempFileName);
pdfProcess.Start();
Note: We are using the _pdfProcessDictionary to store references to the Process objects so that they stay in scope so that Exited event can successfully be raised.
Our cleanup/exited event is:
void pdfProcess_Exited(object sender, EventArgs e)
{
Debug.Assert(!InvokeRequired);
var p = sender as Process;
try
{
if (_pdfProcessDictionary.ContainsKey(p))
{
var tempFileName = _pdfProcessDictionary[p];
if (File.Exists(tempFileName)) // How else can I check if I can delete it!!??
{
// NOTE: Will fail if the Adobe Reader application instance has been re-used!
File.Delete(tempFileName);
_pdfProcessDictionary.Remove(p);
}
CleanOtherFiles(); // This function will clean up files for any other previously exited processes in our dictionary
}
}
catch (IOException ex)
{
// Just swallow it up, we will deal with trying to delete it at another point
}
}
Possible solutions:
Detect that the file is still open in another process
Detect that the second process hasn't really been fully exited and that the file is opened in the first process instead
I just dealt with this a couple of days ago.
When there is no instance open already, the document opens in a new instance directly.
When there is an instance already open, I believe that instance spawns a new instance which you don't actually get a handle to. What happens is control returns to your function immediately, which then goes and deletes the file before the new instance has had a chance to read the file -- hence it appears to not be there.
I "solved" this by not deleting the files immediately, but keeping track of the paths in a list, and then nuking all of them when the program exits (wrap each delete in a try/catch with an empty catch block in case the file has disappeared in the meantime).
I would suggest following approach:
Create files in user's temp directory (Path.GetTempPath). You can create some sub-folder under it.
Attempt to delete files only when last instance of process gets exited (i.e. you need to count number of processes that you had launched, on exit, decrement the count and when it becomes zero, attempt to delete (all) files that are open so far)
Try to clean-up created sub-folder (under temp directory) while starting and ending the application. You can even attempt for periodic clean-up using timer.
I have an application that uses MSWord automation to edit some documents, after they save and close word I need to grab the modified file and put it back on the repository, there is only one scenario where I can't get it to work and that is
when the user makes changes to the file, selects to close word and selects yes to save the file
there are 2 events that I'm using:
DocumentBeforeSave
Quit
on the Quit event I'm trying to load the .docx file from disk but on this particular scenario I get an IOException because the file is still in use, somehow I need to wait until after the Quit event has been processed, which is when Word is actually closed and the file is no longer being used
right now I have it working using this
word.Visible = true;
while (!wordDone) { //gets changed to true on the Quit event
System.Threading.Thread.Sleep(100);
}
bool error = false;
do {
try { //need to load the contents of the modified file
ls.Content = System.IO.File.ReadAllBytes(provider.GetFileName());
error = false;
}
catch (System.IO.IOException) {
error = true;
System.Threading.Thread.Sleep(200);
}
} while (error);
while this works it is very ugly, I need a way to fire an event after the Quit event has been handled, or block the current thread while word is still running, or get an event after the document has been saved, the bottom line is I need a clean way to load the file after it has been saved and word is closed. DocumentAfterSave would be awesome, but doesn't seem to exist.
I Also tried unhooking the Quit handler and calling word.Quit on the Quit handler, that made no difference
I'm also investigating the use of ManualResetEvent or related classes, so far it almost works, but I still need to pause after it has been signaled to make sure word is closed and the file is no longer in use
I faced similar problem in the past as well. I dont think there is any nice clean way but instead of doing it like your above, how about considering this (will suit if you have a controlled environment)
Create word app
Get the Process ID immediately by using GetProcesses matching Winword and the last one in the list return should be the one you are after. This is not 100% reliable in multiuser environment.
After word quit, use the Thread.Sleep loop to ensure the PID no longer exist.
Reading the docx for your custom operations
I used to have the same problem. Using ReleaseComObject on all COM-related objects did the trick (that is, on your Word document object and your Word.Application object). That way you ensure that all dirty locks are removed after the COM object has been destroyed. Close the document and application with the Interop API. I use:
var localWordapp = new Word.Application();
localWordapp.Visible = false;
Word.Document doc = null;
// ...
if (doc != null)
{
doc.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
}
localWordapp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(localWordapp);
In WPF App.Current.SessionEnding must return in a few seconds, otherwise the "application does not respond" window appears. So the user can't be asked in this event handler to save his data, because the user's response takes longer than a few seconds.
I thought a solution would be to cancel the logoff / shutdown / restart, and resume it when the user answered to the file save dialog.
ReasonSessionEnding _reasonSessionEnding;
App.Current.SessionEnding +=
new SessionEndingCancelEventHandler(Current_SessionEnding);
void Current_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
if (_dataModified)
{
e.Cancel = true;
_reasonSessionEnding = e.ReasonSessionEnding;
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(EndSession));
}
}
void EndSession()
{
if (SaveWithConfirmation()) // if the user didn't press Cancel
//if (_reasonSessionEnding = ReasonSessionEnding.Logoff)
// logoff
//else
// shutdown or restart ?
}
The problem is that ReasonSessionEnding does not tell me if Windows was shutting down or restarting (it does not differentiate between the two).
So, what should my program do on the session ending event ?
Should it even do anything, or doing nothing on this event is the standard ?
The user is asked to save his changes in my main form's OnClosing method, so he does not lose data, but I think that the "application does not respond" window does not suggest a normal workflow.
Canceling the shutdown is not desired I guess, because some of the other programs have been shut down already.
What seems to be the accepted way is to display the save as dialog regardless.
Cancelling the shutdown, then resuming it later is most certainly not an option, for the reason you state and various others.
Since simply discarding the data is unacceptable, there really is no other options.
Well, except to save the data to a temporary file, then automatically restoring them the next time the program is run. Rather like MS Word after it has crashed. Actually, the more I consider it, the better it sounds.
Edit: There's yet another avenue, namely to save continously, the way eg. MS OneNote does. What has struck me before is that, provided you implement decent multilevel undo in your application, the whole manual saving business is actually somewhat dated - an anachronism from the days when disk operations were expensive and error-prone, nowadays mostly old habit.
But I'm digressing. Anyway, it's probably not applicable to your application, since I imagine it needs to be implemented from the beginning.