DataTplFixFormatterConflict.cs
  1. //
  2. // This code is part of Document Solutions for Word demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Globalization;
  11. using GrapeCity.Documents.Word;
  12.  
  13. namespace DsWordWeb.Demos
  14. {
  15. // This example shows how to deal with the template formatter
  16. // conflicting with another formatter error.
  17. public class DataTplFixFormatterConflict
  18. {
  19. // Code demonstrating the problem:
  20. GcWordDocument Problem()
  21. {
  22. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  23. var doc = new GcWordDocument();
  24. doc.DataTemplate.DataSources.Add("ds", oceans);
  25. // Incorrect: pbb (paragraph-block-behavior) and rbb (run-block-behavior) formatters
  26. // were both applied to the same range template tag:
  27. doc.Body.Paragraphs.Add("{{#ds.seas}:pbb():rbb()}{{ds.seas.name}} {{/ds.seas}}");
  28. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  29. return doc;
  30. }
  31.  
  32. // Code demonstrating the fix:
  33. GcWordDocument Fix()
  34. {
  35. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  36. var doc = new GcWordDocument();
  37. doc.DataTemplate.DataSources.Add("ds", oceans);
  38. // Correct: pbb and rbb are block-modifier formatters, so only one of them can be used on a single range template tag:
  39. doc.Body.Paragraphs.Add("{{#ds.seas}:rbb()}{{ds.seas.name}} {{/ds.seas}}");
  40. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  41. return doc;
  42. }
  43.  
  44. public GcWordDocument CreateDocx()
  45. {
  46. GcWordDocument doc;
  47. try
  48. {
  49. // This fails:
  50. doc = Problem();
  51. }
  52. catch (Exception ex)
  53. {
  54. // This works:
  55. doc = Fix();
  56. // Insert a brief explanation of the problem and the fix into the generated document:
  57. doc.Body.Paragraphs.Insert(
  58. $"The error \"{ex.Message}\" occurred because a pbb (paragraph-block-behavior) and a rbb (run-block-behavior) " +
  59. $"formatters were both applied to the same range template tag. pbb and rbb are block-modifier formatters, " +
  60. $"so only one of them can be used on a single range template tag.",
  61. doc.Styles[BuiltInStyleId.BlockText],
  62. InsertLocation.Start);
  63. }
  64. return doc;
  65. }
  66. }
  67. }
  68.