Reputation: 3529
I recently ran into an issue in Word that was really strange and I didn't expect to be able to resolve. But I did, and now I want to share that solution.
The behavior I saw was that table manipulation would often mess up the graphics and hang word, to the point that it needed to be restarted unless you undid the change once it stopped hanging. The reproducible test case I found was:
My solution did a lot of different things during saves, and there were no exceptions or anything showing up in my logs to indicate anything was wrong.
This did not happen in normal Word.
Upvotes: 0
Views: 229
Reputation: 3529
To identify the cause, I started removing large swathes of code and retesting it to determine whether it made any difference.
I eventually created this MCVE:
Note that this is a document-level template project.
using System;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Interop.Word;
namespace TableUndoBug
{
public partial class ThisDocument
{
private void ThisDocument_Startup(object sender, System.EventArgs e)
{
BeforeSave += ThisDocument_BeforeSave;
}
private void ThisDocument_BeforeSave(object sender, SaveEventArgs e)
{
try
{
foreach (Table table in Tables)
{
int numRows = table.Rows.Count;
var c = table.Cell(numRows, 0); // this line is the culprit
// this call should be using 1, not 0, but it completes successfully anyway.
// if you change it, this bug disappears
}
}
catch (Exception)
{
}
}
private void ThisDocument_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisDocument_Startup);
this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
}
#endregion
}
}
And here are the steps to test with (I also found a few more test cases while putting this together):
This sample project illustrates a bug in Word 2013/VSTO.
To replicate:
Run it from Visual Studio.
Save the document anywhere.
Insert a table.
Test case 1:
Save it again 2 more times.
Try to insert a column using the controls that pop up on hover.
Graphics will be messed up but it will not hang.
Test case 2:
- Add a caption using the table's context menu (I think what matters here is the style application).
- Save it again 2 more times.
Try to insert a column using the controls that pop up on hover.
Graphics will be messed up and it will hang for a while.
Test case 3:
- Save it again 2 more times.
- Use the undo button in the Quick Access Toolbar.
Use the redo button in the Quick Access Toolbar.
Graphics will be messed up and it will hang for a while.
The solution is right there in the code: check for 0-based indices that should be 1-based. The API should probably fail here but for some reason it doesn't.
Upvotes: 1