PowerToolsBlockExtensions.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (c) Microsoft. All rights reserved.
  2. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  3. using System;
  4. using System.Linq;
  5. using System.Xml;
  6. using System.Xml.Linq;
  7. using DocumentFormat.OpenXml.Packaging;
  8. namespace OpenXmlPowerTools
  9. {
  10. public static class PowerToolsBlockExtensions
  11. {
  12. /// <summary>
  13. /// Begins a PowerTools Block by (1) removing annotations and, unless the package was
  14. /// opened in read-only mode, (2) saving the package.
  15. /// </summary>
  16. /// <remarks>
  17. /// Removes <see cref="XDocument" /> and <see cref="XmlNamespaceManager" /> instances
  18. /// added by <see cref="PtOpenXmlExtensions.GetXDocument(OpenXmlPart)" />,
  19. /// <see cref="PtOpenXmlExtensions.GetXDocument(OpenXmlPart, out XmlNamespaceManager)" />,
  20. /// <see cref="PtOpenXmlExtensions.PutXDocument(OpenXmlPart)" />,
  21. /// <see cref="PtOpenXmlExtensions.PutXDocument(OpenXmlPart, XDocument)" />, and
  22. /// <see cref="PtOpenXmlExtensions.PutXDocumentWithFormatting(OpenXmlPart)" />.
  23. /// methods.
  24. /// </remarks>
  25. /// <param name="package">
  26. /// A <see cref="WordprocessingDocument" />, <see cref="SpreadsheetDocument" />,
  27. /// or <see cref="PresentationDocument" />.
  28. /// </param>
  29. public static void BeginPowerToolsBlock(this OpenXmlPackage package)
  30. {
  31. if (package == null) throw new ArgumentNullException("package");
  32. package.RemovePowerToolsAnnotations();
  33. package.Save();
  34. }
  35. /// <summary>
  36. /// Ends a PowerTools Block by reloading the root elements of all package parts
  37. /// that were changed by the PowerTools. A part is deemed changed by the PowerTools
  38. /// if it has an annotation of type <see cref="XDocument" />.
  39. /// </summary>
  40. /// <param name="package">
  41. /// A <see cref="WordprocessingDocument" />, <see cref="SpreadsheetDocument" />,
  42. /// or <see cref="PresentationDocument" />.
  43. /// </param>
  44. public static void EndPowerToolsBlock(this OpenXmlPackage package)
  45. {
  46. if (package == null) throw new ArgumentNullException("package");
  47. foreach (OpenXmlPart part in package.GetAllParts())
  48. {
  49. if (part.Annotations<XDocument>().Any() && part.RootElement != null)
  50. part.RootElement.Reload();
  51. }
  52. }
  53. private static void RemovePowerToolsAnnotations(this OpenXmlPackage package)
  54. {
  55. if (package == null) throw new ArgumentNullException("package");
  56. foreach (OpenXmlPart part in package.GetAllParts())
  57. {
  58. part.RemoveAnnotations<XDocument>();
  59. part.RemoveAnnotations<XmlNamespaceManager>();
  60. }
  61. }
  62. }
  63. }