DataTplFixSpecifyDataSource.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 DataTplFixSpecifyDataSource
  17. {
  18. // Code demonstrating the problem:
  19. GcWordDocument Problem()
  20. {
  21. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  22. using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  23. var doc = new GcWordDocument();
  24. doc.DataTemplate.DataSources.Add("ds", oceans);
  25. doc.DataTemplate.DataSources.Add("ds1", oceans1);
  26. // Incorrect: template tag is used without specifying the data source part.
  27. // It is allowed only if the template engine is able to resolve the tags.
  28. // But because in this case there are two data sources that both contain a field called 'name',
  29. // if causes an exception as the tag cannot be resolved:
  30. doc.Body.Paragraphs.Add("{{name}}");
  31. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  32. return doc;
  33. }
  34.  
  35. // Code demonstrating the fix:
  36. GcWordDocument Fix()
  37. {
  38. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  39. using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  40. var doc = new GcWordDocument();
  41. doc.DataTemplate.DataSources.Add("ds", oceans);
  42. doc.DataTemplate.DataSources.Add("ds1", oceans1);
  43. // Correct: use fully qualified data tags so there is no ambiguity:
  44. doc.Body.Paragraphs.Add("{{ds.name}}");
  45. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  46. return doc;
  47. }
  48.  
  49. public GcWordDocument CreateDocx()
  50. {
  51. GcWordDocument doc;
  52. try
  53. {
  54. // This fails:
  55. doc = Problem();
  56. }
  57. catch (Exception ex)
  58. {
  59. // This works:
  60. doc = Fix();
  61. // Insert a brief explanation of the problem and the fix into the generated document:
  62. doc.Body.Paragraphs.Insert(
  63. $"The error \"{ex.Message}\" occurred because the data template engine could not unambiguously resolve the data tag " +
  64. $"that was not fully qualified. " +
  65. $"The fix is to use fully qualified data tags.",
  66. doc.Styles[BuiltInStyleId.BlockText],
  67. InsertLocation.Start);
  68. }
  69. return doc;
  70. }
  71. }
  72. }
  73.