''
'' 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 not found' error.
'' NOTE: the C# original (DataTplFixDataSourceNotFound.cs) has a typo in its SampleId
'' attribute value - "DataTplFixDataSourceNoFound" instead of "...NotFound". Preserved
'' here verbatim so this VB sample resolves correctly against that existing C# sample.
Public Class DataTplFixDataSourceNotFound
'' Code demonstrating the problem:
Private Function Problem() As GcWordDocument
Using oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"))
Dim doc = New GcWordDocument()
doc.DataTemplate.DataSources.Add("ds", oceans)
'' Incorrect: 'ds1' is used as data source name, but there is no data source with that name:
doc.Body.Paragraphs.Add("{{ds1.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"))
Dim doc = New GcWordDocument()
doc.DataTemplate.DataSources.Add("ds", oceans)
'' Correct: use the correct data source name 'ds':
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 in the template a non-existing data source name was used. " +
$"The fix is to ensure that data source names used in the template match names of data sources added to the DataSources collection.",
doc.Styles(BuiltInStyleId.BlockText),
InsertLocation.Start)
End Try
Return doc
End Function
End Class