DataTplFixDataMemberNotFound.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 not found' error.
  16. public class DataTplFixDataMemberNotFound
  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.DataTemplate.DataSources.Add("ds", oceans);
  24. // Incorrect: our data source does not have a member 'wrong_name':
  25. doc.Body.Paragraphs.Add("{{ds.wrong_name}}");
  26. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  27. return doc;
  28. }
  29.  
  30. // Code demonstrating the fix:
  31. GcWordDocument Fix()
  32. {
  33. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  34. var doc = new GcWordDocument();
  35. doc.DataTemplate.DataSources.Add("ds", oceans);
  36. // Correct: use the correct data member name:
  37. doc.Body.Paragraphs.Add("{{ds.name}}");
  38. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  39. return doc;
  40. }
  41.  
  42. public GcWordDocument CreateDocx()
  43. {
  44. GcWordDocument doc;
  45. try
  46. {
  47. // This fails:
  48. doc = Problem();
  49. }
  50. catch (Exception ex)
  51. {
  52. // This works:
  53. doc = Fix();
  54. // Insert a brief explanation of the problem and the fix into the generated document:
  55. doc.Body.Paragraphs.Insert(
  56. $"The error \"{ex.Message}\" occurred because in the template a non-existing path to a data member was used. " +
  57. $"The fix is to ensure that data member names used in the template match names of data members in the data source.",
  58. doc.Styles[BuiltInStyleId.BlockText],
  59. InsertLocation.Start);
  60. }
  61. return doc;
  62. }
  63. }
  64. }
  65.