DataTplFixNoDataSources.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 'data source with this name already exists' error.
  16. public class DataTplFixNoDataSources
  17. {
  18. // Code demonstrating the problem:
  19. GcWordDocument Problem()
  20. {
  21. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  22. var doc = new GcWordDocument();
  23. doc.Body.Paragraphs.Add("{{ds.name}}");
  24. // Incorrect: no data sources have been added when the DataTemplate.Process() method is called:
  25. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  26. return doc;
  27. }
  28.  
  29. // Code demonstrating the fix:
  30. GcWordDocument Fix()
  31. {
  32. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  33. var doc = new GcWordDocument();
  34. doc.Body.Paragraphs.Add("{{ds.name}}");
  35. doc.DataTemplate.DataSources.Add("ds", oceans);
  36. // Correct: the data source have been added prior to calling the DataTemplate.Process() method:
  37. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  38. return doc;
  39. }
  40.  
  41. public GcWordDocument CreateDocx()
  42. {
  43. GcWordDocument doc;
  44. try
  45. {
  46. // This fails:
  47. doc = Problem();
  48. }
  49. catch (Exception ex)
  50. {
  51. // This works:
  52. doc = Fix();
  53. // Insert a brief explanation of the problem and the fix into the generated document:
  54. doc.Body.Paragraphs.Insert(
  55. $"The error \"{ex.Message}\" occurred because the DataTemplate.Process() method was called before adding the data source. " +
  56. $"The fix is to add the data sources prior to calling the DataTemplate.Process() method.",
  57. doc.Styles[BuiltInStyleId.BlockText],
  58. InsertLocation.Start);
  59. }
  60. return doc;
  61. }
  62. }
  63. }
  64.