InsertParagraphAfterSelf throws an error after update to v2.5.0 or v3.0.0

Open
#474 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
csharp
Domain
backend

Research direction

Start at Paragraph.InsertParagraphAfterSelf and the Paragraphs enumeration shown in the issue. Reproduce the provided loop against 2.4.1 and 2.5.0 or 3.0.0, then investigate why the second insertion modifies the collection during enumeration. Done means the loop completes without the collection-modified exception while preserving the inserted paragraphs.

Written by the indexing model from the issue text.

Description

I was using the InsertParagraphAfterSelf method of Paragraph to insert paragraphs from one document to another without issues until release 2.4 (including 2.4.1), but the code is now throwing an error if I update DocX to 2.5.0 or the latest 3.0.0

Collection was modified; enumeration operation may not execute.

The release notes of 2.5.0 state:

In Paragraph, using the InsertParagraphAfterSelf or InsertParagraphBeforeSelf methods no longer breaks the Paragraphs collection.

Is there a chance there is a regression?

My code (edited) is next; InsertParagraphAfterSelf(paragraph) is successful the first time, but the next iteration always throws the above-referenced error.

foreach (var par in subdocument.Paragraphs)
{
	if (par.Hyperlinks.Count > 0)
	{
		Paragraph paragraph = template.InsertParagraph();
		foreach (var magicWord in par.MagicText)
			if (string.Equals(magicWord.formatting?.StyleId?.ToLower(), "hyperlink"))
			{
				paragraph.InsertText(string.Concat("[[", magicWord.text, "]]"), false, magicWord.formatting);
			}
			else
				paragraph.InsertText(magicWord.text, false, magicWord.formatting);

		bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf(paragraph);
	}
	else
	{
		bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf(par);
	}
}

Thanks!

Dominant language
C#
Stars
1.9k
Forks
483
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from xceedsoftware/DocX

All issues in xceedsoftware/DocX

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.