DataTplFixBatchActionNeeded.vb
''
'' This code is part of Document Solutions for Word demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.IO
Imports GrapeCity.Documents.Word

'' This example shows how to deal with the 'item processed action is required' error.
Public Class DataTplFixBatchActionNeeded
    '' 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)
            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(Nothing)
            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)
            doc.Body.Paragraphs.Add("{{ds.name}}")
            '' Correct: any (even empty) action except null is good enough for the BatchProcess call:
            doc.DataTemplate.BatchProcess(Sub()
                                           End Sub)
            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 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)
        End Try
        Return doc
    End Function
End Class