DataTplAltFixDataMemberNotFound.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. // by ignoring non-existent data members.
  17. public class DataTplAltFixDataMemberNotFound
  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: our data source does not have a member 'wrong_name':
  26. doc.Body.Paragraphs.Add("{{ds.wrong_name}}");
  27. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  28. return doc;
  29. }
  30.  
  31. // Code demonstrating the fix:
  32. GcWordDocument Fix()
  33. {
  34. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  35. var doc = new GcWordDocument();
  36. doc.DataTemplate.DataSources.Add("ds", oceans);
  37. // Still incorrect: our data source does not have a member 'wrong_name':
  38. doc.Body.Paragraphs.Add("{{ds.wrong_name}}");
  39. // An alternative fix is to specify relaxed handling of missing fields,
  40. // this will ignore such template tags bug will not throw exceptions:
  41. doc.DataTemplate.Options.MissingFieldsHandling = DataTemplateMissingFieldsHandling.Relaxed;
  42. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  43. return doc;
  44. }
  45.  
  46. public GcWordDocument CreateDocx()
  47. {
  48. GcWordDocument doc;
  49. try
  50. {
  51. // This fails:
  52. doc = Problem();
  53. }
  54. catch (Exception ex)
  55. {
  56. // This works:
  57. doc = Fix();
  58. // Insert a brief explanation of the problem and the fix into the generated document:
  59. doc.Body.Paragraphs.Insert(
  60. $"The error \"{ex.Message}\" occurred because in the template a non-existing path to a data member was used. " +
  61. $"To avoid exceptions in such cases, DataTemplate.Options.MissingFieldsHandling property can be set to " +
  62. $"DataTemplateMissingFieldsHandling.Relaxed. This will cause the template engine to ignore missing fields " +
  63. $"without throwing exceptions.",
  64. doc.Styles[BuiltInStyleId.BlockText],
  65. InsertLocation.Start);
  66. }
  67. return doc;
  68. }
  69. }
  70. }
  71.