''
'' This code is part of Document Solutions for Word demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.IO
Imports System.Globalization
Imports GrapeCity.Documents.Word
'' This example shows how to deal with the 'data source with this name already exists' error.
Public Class DataTplFixSpecifyDataSource
'' Code demonstrating the problem:
Private Function Problem() As GcWordDocument
Using oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")),
oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"))
Dim doc = New GcWordDocument()
doc.DataTemplate.DataSources.Add("ds", oceans)
doc.DataTemplate.DataSources.Add("ds1", oceans1)
'' Incorrect: template tag is used without specifying the data source part.
'' It is allowed only if the template engine is able to resolve the tags.
'' But because in this case there are two data sources that both contain a field called 'name',
'' if causes an exception as the tag cannot be resolved:
doc.Body.Paragraphs.Add("{{name}}")
doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"))
Return doc
End Using
End Function
'' Code demonstrating the fix:
Private Function Fix() As GcWordDocument
Using oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")),
oceans1 = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"))
Dim doc = New GcWordDocument()
doc.DataTemplate.DataSources.Add("ds", oceans)
doc.DataTemplate.DataSources.Add("ds1", oceans1)
'' Correct: use fully qualified data tags so there is no ambiguity:
doc.Body.Paragraphs.Add("{{ds.name}}")
doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"))
Return doc
End Using
End Function
Function CreateDocx() As GcWordDocument
Dim doc As GcWordDocument
Try
'' This fails:
doc = Problem()
Catch ex As Exception
'' 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 data template engine could not unambiguously resolve the data tag " +
$"that was not fully qualified. " +
$"The fix is to use fully qualified data tags.",
doc.Styles(BuiltInStyleId.BlockText),
InsertLocation.Start)
End Try
Return doc
End Function
End Class