DataTplFixDuplicateDataSource.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 'data source with this name already exists' error.
    public class DataTplFixDuplicateDataSource
    {
        // Code demonstrating the problem:
        GcWordDocument Problem()
        {
            using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
            using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
            var doc = new GcWordDocument();
            doc.DataTemplate.DataSources.Add("ds", oceans);
            // Incorrect: data source with the name "ds" already exists, so this will throw:
            doc.DataTemplate.DataSources.Add("ds", oceans1);
            return doc;
        }

        // Code demonstrating the fix:
        GcWordDocument Fix()
        {
            using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
            using var oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
            var doc = new GcWordDocument();
            doc.DataTemplate.DataSources.Add("ds", oceans);
            // Correct: give each data source a unique name:
            doc.DataTemplate.DataSources.Add("ds1", oceans1);
            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 code tried to add two data sources with the same name. " +
                    $"The fix is to use a unique name for each data source added to the GcWordDocument.DataTemplate.DataSources collection.",
                    doc.Styles[BuiltInStyleId.BlockText],
                    InsertLocation.Start);
            }
            return doc;
        }
    }
}