StronglyTypedBlock.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 DocumentFormat.OpenXml.Packaging;
  5. namespace OpenXmlPowerTools
  6. {
  7. /// <summary>
  8. /// Provides an elegant way of wrapping a set of invocations of the strongly typed
  9. /// classes provided by the Open XML SDK) in a using statement that demarcates those
  10. /// invokations as one "block" before and after which the PowerTools can be used safely.
  11. /// </summary>
  12. /// <remarks>
  13. /// <para>
  14. /// This class lends itself to scenarios where the PowerTools and Linq-to-XML are used as
  15. /// the primary API for working with Open XML elements, next to the strongly typed classes
  16. /// provided by the Open XML SDK. In these scenarios, the class would be used as follows:
  17. /// </para>
  18. /// <code>
  19. /// [Your code using the PowerTools]
  20. ///
  21. /// using (new NonPowerToolsBlock(wordprocessingDocument))
  22. /// {
  23. /// [Your code using the strongly typed classes]
  24. /// }
  25. ///
  26. /// [Your code using the PowerTools]
  27. /// </code>
  28. /// <para>
  29. /// Upon creation, instances of this class will invoke the
  30. /// <see cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/> method on the package
  31. /// to begin the block. Upon disposal, instances of this class will call the
  32. /// <see cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/> method on the package
  33. /// to end the block.
  34. /// </para>
  35. /// </remarks>
  36. /// <seealso cref="PowerToolsBlock"/>
  37. /// <seealso cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/>
  38. /// <seealso cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/>
  39. public class StronglyTypedBlock : IDisposable
  40. {
  41. private OpenXmlPackage _package;
  42. public StronglyTypedBlock(OpenXmlPackage package)
  43. {
  44. if (package == null) throw new ArgumentNullException("package");
  45. _package = package;
  46. _package.EndPowerToolsBlock();
  47. }
  48. public void Dispose()
  49. {
  50. if (_package == null) return;
  51. _package.BeginPowerToolsBlock();
  52. _package = null;
  53. }
  54. }
  55. }