Imports Telerik.OpenAccess
Imports System.Collections.Generic


Public Class ContainerHelper
    Private _container As New ObjectContainer()

    Public Delegate Function SynchronizeDelegate( _
        ByVal changeSet As ObjectContainer.ChangeSet) _
        As ObjectContainer.ChangeSet

    Public Function Load(Of T)( _
            ByVal changeSet As ObjectContainer.ChangeSet) As IList(Of T)
        ' ChangeSet contstructor morphs 
        ' webservice changeset to application changeset type
        Dim tempChangeSet As New ObjectContainer.ChangeSet(changeSet)

        ' transaction must not be active before call to Apply()
        If _container.Transaction.IsActive Then
            _container.Transaction.Commit()
        End If

        ' apply service changeset to local container
        ' transaction must not be active
        _container.Apply(tempChangeSet)

        ' start transaction for new add/edit/delete in the bound controls
        _container.Transaction.Begin()

        Return _container.Extent(Of T)()
    End Function

    Public Sub Save(ByVal synchronize As SynchronizeDelegate)
        ' transactions cannot be active for GetChanges() or Apply()
        If _container.Transaction.IsActive Then
            _container.Transaction.Commit()
        End If

        ' get the changes from the client
        Dim localChangeSet As ObjectContainer.ChangeSet = _
      _container.GetChanges(ObjectContainer.Verify.Changed)

        ' send changes to the service, apply and return new
        ' changeset
        Dim serviceChangeSet As ObjectContainer.ChangeSet = _
      synchronize(localChangeSet)

        ' apply synchronized changeset
        If serviceChangeSet IsNot Nothing Then
            _container.Apply(serviceChangeSet)
        End If

        ' start transaction for new add/edit/delete in the bound controls
        _container.Transaction.Begin()
    End Sub

    Public Sub Add(ByVal obj As Object)
        _container.Add(obj)
    End Sub

    Public Sub Remove(ByVal obj As Object)
        _container.Remove(obj)
    End Sub

    ' Remove 'new' objects of type T
    Public Sub Reset(Of T)()
        _container.Transaction.Begin()
        Dim list As IList(Of T) = _container.Extent(Of T)()
        For Each obj As Object In list
            If _container.IsNew(obj) Then
                _container.Remove(obj)
            End If
        Next obj
    End Sub

End Class
