DataTplFixBatchActionNeeded.cs
- //
- // This code is part of Document Solutions for Word demos.
- // Copyright (c) MESCIUS inc. All rights reserved.
- //
- using System;
- using System.IO;
- using System.Drawing;
- using System.Collections.Generic;
- using System.Linq;
- using GrapeCity.Documents.Word;
-
- namespace DsWordWeb.Demos
- {
- // This example shows how to deal with the 'item processed action is required' error.
- public class DataTplFixBatchActionNeeded
- {
- // Code demonstrating the problem:
- GcWordDocument Problem()
- {
- using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
- var doc = new GcWordDocument();
- doc.DataTemplate.DataSources.Add("ds", oceans);
- doc.Body.Paragraphs.Add("{{ds.name}}");
- // Incorrect: batch processing requires to specify an action that would be invoked
- // after each root data item is processed. Such action could for example save the
- // processed document instance containing the current record's data.
- // Not specifying an action causes an exception:
- doc.DataTemplate.BatchProcess(null);
- return doc;
- }
-
- // Code demonstrating the fix:
- GcWordDocument Fix()
- {
- using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
- var doc = new GcWordDocument();
- doc.DataTemplate.DataSources.Add("ds", oceans);
- doc.Body.Paragraphs.Add("{{ds.name}}");
- // Correct: any (even empty) action except null is good enough for the BatchProcess call:
- doc.DataTemplate.BatchProcess(() => { });
- return doc;
- }
-
- public GcWordDocument CreateDocx()
- {
- GcWordDocument doc;
- try
- {
- // This fails:
- doc = Problem();
- }
- catch (Exception ex)
- {
- // This works:
- doc = Fix();
- // Insert a brief explanation of the problem and the fix into the generated document:
- doc.Body.Paragraphs.Insert(
- $"The error \"{ex.Message}\" occurred because the BatchProcess() method requires a non-null " +
- $"action to be specified that would be called as each root data item is processed. " +
- $"The fix is to specify an action (even an action that does nothing would do). " +
- $"Note that when the BatchProcess() method returns, the original template document " +
- $"with data tags rather than actual data is restored.",
- doc.Styles[BuiltInStyleId.BlockText],
- InsertLocation.Start);
- }
- return doc;
- }
- }
- }
-