DataTplFixBatchActionNeeded.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 GrapeCity.Documents.Word;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // This example shows how to deal with the 'item processed action is required' error.
  15. public class DataTplFixBatchActionNeeded
  16. {
  17. // Code demonstrating the problem:
  18. GcWordDocument Problem()
  19. {
  20. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  21. var doc = new GcWordDocument();
  22. doc.DataTemplate.DataSources.Add("ds", oceans);
  23. doc.Body.Paragraphs.Add("{{ds.name}}");
  24. // Incorrect: batch processing requires to specify an action that would be invoked
  25. // after each root data item is processed. Such action could for example save the
  26. // processed document instance containing the current record's data.
  27. // Not specifying an action causes an exception:
  28. doc.DataTemplate.BatchProcess(null);
  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. doc.Body.Paragraphs.Add("{{ds.name}}");
  39. // Correct: any (even empty) action except null is good enough for the BatchProcess call:
  40. doc.DataTemplate.BatchProcess(() => { });
  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 the BatchProcess() method requires a non-null " +
  59. $"action to be specified that would be called as each root data item is processed. " +
  60. $"The fix is to specify an action (even an action that does nothing would do). " +
  61. $"Note that when the BatchProcess() method returns, the original template document " +
  62. $"with data tags rather than actual data is restored.",
  63. doc.Styles[BuiltInStyleId.BlockText],
  64. InsertLocation.Start);
  65. }
  66. return doc;
  67. }
  68. }
  69. }
  70.