DataTplFixDuplicateDataSource.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 'data source with this name already exists' error.
  15. public class DataTplFixDuplicateDataSource
  16. {
  17. // Code demonstrating the problem:
  18. GcWordDocument Problem()
  19. {
  20. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  21. using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  22. var doc = new GcWordDocument();
  23. doc.DataTemplate.DataSources.Add("ds", oceans);
  24. // Incorrect: data source with the name "ds" already exists, so this will throw:
  25. doc.DataTemplate.DataSources.Add("ds", oceans1);
  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. using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  34. var doc = new GcWordDocument();
  35. doc.DataTemplate.DataSources.Add("ds", oceans);
  36. // Correct: give each data source a unique name:
  37. doc.DataTemplate.DataSources.Add("ds1", oceans1);
  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 code tried to add two data sources with the same name. " +
  56. $"The fix is to use a unique name for each data source added to the GcWordDocument.DataTemplate.DataSources collection.",
  57. doc.Styles[BuiltInStyleId.BlockText],
  58. InsertLocation.Start);
  59. }
  60. return doc;
  61. }
  62. }
  63. }
  64.