DataTplFixDataMemberNotFound.cs
//
// This code is part of GrapeCity Documents for Word samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Word;

namespace GcWordWeb.Samples
{
    // This example shows how to deal with the 'data source not found' error.
    public class DataTplFixDataMemberNotFound
    {
        // 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);
            // Incorrect: our data source does not have a member 'wrong_name':
            doc.Body.Paragraphs.Add("{{ds.wrong_name}}");
            doc.DataTemplate.Process();
            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);
            // Correct: use the correct data member name:
            doc.Body.Paragraphs.Add("{{ds.name}}");
            doc.DataTemplate.Process();
            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 in the template a non-existing path to a data member was used. " +
                    $"The fix is to ensure that data member names used in the template match names of data members in the data source.",
                    doc.Styles[BuiltInStyleId.BlockText],
                    InsertLocation.Start);
            }
            return doc;
        }
    }
}