Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.ExpressApp.CloneObject
Imports DevExpress.Persistent.BaseImpl
Imports System.IO
Imports DevExpress.ExpressApp.Reports
Imports DevExpress.Data.Filtering
Imports DevExpress.Xpo
Imports DevExpress.ExpressApp.Utils
Imports DevExpress.XtraEditors


Public Class APCSheetVC
    Inherits DevExpress.ExpressApp.ViewController

    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event DoWork()
    Public Event FinalWork()

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        Frame.GetController(Of APCSheetVC).aAPCSheetByProducts_New.Active.SetItemValue("", False)
        Frame.GetController(Of APCSheetVC).aAPCSheetHeader_CreateReviewSheet.Active.SetItemValue("", False)
        Frame.GetController(Of APCSheetVC).aCloneAPCSheet.Active.SetItemValue("", False)
        If View.Id = "APCSheetHeader_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_APCSheetByProducts_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_APCSheetByTerritorial_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_APCSheetByTerritorial_ListView_No" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_APCSheetPresentation_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            AddHandler Frame.GetController(Of DeleteObjectsViewController).DeleteAction.Executed, AddressOf APCSheetHeader_APCSheetPresentation_ListView_DeleteAction_Executed
        End If
        If View.Id = "APCSheetHeader_APCSheetCreditClassificationFinancialRows_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeader_APCSheetCreditClassificationAnimalRows_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If

        If View.Id = "APCSheetByProductsOrderInRows_ListView" Then
            AddHandler Frame.GetController(Of RefreshController).RefreshAction.Execute, AddressOf APCSheetByProductsOrderInRows_ListView_RefreshAction_Execute
        End If
        If View.Id = "APCSheetByProductsSalesPolicyH_APCSheetByProductsSalesPolicyR_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetByProductsSalesPolicyH_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "APCSheetHeaderSetAPCParameters_PopUp_DetailView" Then
            AddHandler Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DialogController)().AcceptAction.Executing, AddressOf APCSheetHeaderSetAPCParameters_PopUp_AcceptAction_Executing
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "APCSheetHeader_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetByProducts_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetByTerritorial_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetByTerritorial_ListView_No" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetPresentation_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetCreditClassificationFinancialRows_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetHeader_APCSheetCreditClassificationAnimalRows_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetByProductsOrderInRows_ListView" Then
            RemoveHandler Frame.GetController(Of RefreshController).RefreshAction.Execute, AddressOf APCSheetByProductsOrderInRows_ListView_RefreshAction_Execute
        End If
        If View.Id = "APCSheetByProductsSalesPolicyH_APCSheetByProductsSalesPolicyR_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "APCSheetByProductsSalesPolicyH_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
    End Sub
    Private Sub aCloneAPCSheet_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCloneAPCSheet.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetHeader_NEW As New APCSheetHeader(_onew.Session)
            Create_APCSheetHeader_NEW(_onew, _APCSheetHeader_NEW, _APCSheetHeader)

            If _APCSheetHeader.APCSheetByProducts.Count > 0 Then
                For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetHeader.APCSheetByProducts
                    _APCSheetHeader_NEW.APCSheetByProducts.Add(_onew.GetObjectByKey(Of APCSheetByProducts)(_APCSheetByProducts.Oid))
                Next
            End If
            If _APCSheetHeader.APCSheetPresentation.Count > 0 Then
                For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetHeader.APCSheetPresentation
                    _APCSheetHeader_NEW.APCSheetPresentation.Add(_onew.GetObjectByKey(Of APCSheetPresentation)(_APCSheetPresentation.Oid))
                Next
            End If
            If _APCSheetHeader.APCSheetByTerritorial.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetHeader.APCSheetByTerritorial
                    _APCSheetHeader_NEW.APCSheetByTerritorial.Add(_onew.GetObjectByKey(Of APCSheetByTerritorial)(_APCSheetByTerritorial.Oid))
                Next
            End If
            If _APCSheetHeader.APCSheetCreditClassificationAnimalRows.Count > 0 Then
                For Each _APCSheetCreditClassificationAnimalRows As APCSheetCreditClassificationAnimalRows In _APCSheetHeader.APCSheetCreditClassificationAnimalRows
                    _APCSheetHeader_NEW.APCSheetCreditClassificationAnimalRows.Add(_onew.GetObjectByKey(Of APCSheetCreditClassificationAnimalRows)(_APCSheetCreditClassificationAnimalRows.Oid))
                Next
            End If

            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "APCSheetHeader_DetailView", True, _APCSheetHeader_NEW)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aPrintAPCSheet_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aPrintAPCSheet.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _ReportData As ReportData = _APCSheetHeader.APCParameters.ReportData
            If _ReportData Is Nothing Then Throw New Exception("*Nincs beállítva nyomtatvány!" + vbNewLine + "A folyamat megszakadt!")

            Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("Oid=?", _APCSheetHeader.Oid), True)

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheet_GeneratePDFOriginal_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheet_GeneratePDFOriginal.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _ReportData As ReportData = _APCSheetHeader.APCParameters.ReportData
            If _ReportData Is Nothing Then Throw New Exception("*Nincs beállítva nyomtatvány!" + vbNewLine + "A folyamat megszakadt!")

            Dim _XafReport As XafReport = _ReportData.LoadReport(_ocur)

            Dim _FilterString As String = "[Oid]='" & _APCSheetHeader.Oid.ToString & "'"
            _XafReport.FilterString = _FilterString
            Dim _FileName As String = System.IO.Path.GetTempPath & _APCSheetHeader.DocumentNumber & " szerződés.pdf"
            Dim _StreamFile As New System.IO.FileStream(_FileName, FileMode.Create)

            _XafReport.ExportToPdf(_StreamFile)
            _StreamFile.Close()

            Dim _StreamFile2 As New FileStream(_FileName, FileMode.Open)

            _APCSheetHeader.PDFOriginal = New FileData(_ocur.Session)
            _APCSheetHeader.PDFOriginal.LoadFromStream(_APCSheetHeader.DocumentNumber + " szerződés.pdf", _StreamFile2)
            _StreamFile2.Close()

            _ocur.CommitChanges()

            If File.Exists(_FileName) Then File.Delete(_FileName)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByProducts_New_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByProducts_New.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace()
            Dim _ProductsFunding_CollectionSource As New CollectionSource(_onew, GetType(ProductsFunding))

            e.View = Application.CreateListView("ProductsFunding_ListView", _ProductsFunding_CollectionSource, False)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByProducts_New_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByProducts_New.Execute
        Try
            If e.PopupWindow.View.SelectedObjects.Count = 0 Then Throw New Exception("*Nem került kiválasztásra egyetlen sor sem!")
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace

            Dim _ListView As ListView = TryCast(View, ListView)
            Dim _PropertyCollectionSource As PropertyCollectionSource = TryCast(_ListView.CollectionSource, PropertyCollectionSource)
            Dim _APCSheetHeader As APCSheetHeader = TryCast(_PropertyCollectionSource.MasterObject, APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            For Each _ProductsFunding As ProductsFunding In e.PopupWindow.View.SelectedObjects
                Dim _APCSheetByProducts As New APCSheetByProducts(_onew.Session)
                With (_APCSheetByProducts)
                    .APCSheetHeader = _onew.GetObject(_APCSheetHeader)
                    .Products = _onew.GetObject(_ProductsFunding.Products)
                    .MaxContractQuantity = _ProductsFunding.MaxContractQuantity
                    .FundingHatoHUF = _ProductsFunding.FundingHatoHUF
                    .RowIndex = _APCSheetHeader.APCSheetByProducts.Count
                    .ColleteralHatoHUF = _ProductsFunding.CollateralhatoHUF
                    Dim _ActYear As Int32 = GetSQLTime(_onew.Session).Year
                    Dim _ActMonth As Int32 = 0
                    Select Case _ProductsFunding.ProductExpirationDate
                        Case eMonths.eJanuary
                            _ActMonth = 1
                        Case eMonths.eFebruary
                            _ActMonth = 2
                        Case eMonths.eMarch
                            _ActMonth = 3
                        Case eMonths.eApril
                            _ActMonth = 4
                        Case eMonths.eMay
                            _ActMonth = 5
                        Case eMonths.eJune
                            _ActMonth = 6
                        Case eMonths.eJuly
                            _ActMonth = 7
                        Case eMonths.eAugust
                            _ActMonth = 8
                        Case eMonths.eSeptember
                            _ActMonth = 9
                        Case eMonths.eOctober
                            _ActMonth = 10
                        Case eMonths.eNovember
                            _ActMonth = 11
                        Case eMonths.eDecember
                            _ActMonth = 12
                    End Select
                    If GetSQLTime(_onew.Session).Month < 8 Then
                        .ProductExpirationDate = New Date(_ActYear, _ActMonth + 1, 1).AddDays(-1)
                    Else
                        .ProductExpirationDate = New Date(_ActYear + 1, _ActMonth + 1, 1).AddDays(-1)
                    End If

                End With
            Next
            _onew.CommitChanges()

            Dim nestedFrame As NestedFrame = TryCast(Frame, NestedFrame)
            If nestedFrame IsNot Nothing Then
                Dim parentView As View = nestedFrame.View
                If parentView IsNot Nothing Then parentView.ObjectSpace.Refresh()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub Create_APCSheetHeader_NEW(onew As Xpo.XPObjectSpace, APCSheetHeader_NEW As APCSheetHeader, APCSheetHeader As APCSheetHeader)
        On Error GoTo CheckError
        With (APCSheetHeader_NEW)
            .APCParameters = onew.GetObjectByKey(Of APCParameters)(APCSheetHeader.APCParameters.Oid)
            .HRPerson = onew.GetObjectByKey(Of HRPerson)(APCSheetHeader.HRPerson.Oid)
            .ContactsWithFullRight = onew.GetObjectByKey(Of Contacts)(APCSheetHeader.ContactsWithFullRight.Oid)
            .CustomersFrom = onew.GetObjectByKey(Of CustomersFrom)(APCSheetHeader.CustomersFrom.Oid)
            .CropProtectionSpecialist = onew.GetObjectByKey(Of Contacts)(APCSheetHeader.CropProtectionSpecialist.Oid)
            .ShortName = APCSheetHeader.ShortName
            .APCStatus = eAPCStatus.eRegistered

            .IsNewContact = False
            .PaymentDiscipline = APCSheetHeader.PaymentDiscipline
            .CleanerDryerMachinetype = APCSheetHeader.CleanerDryerMachinetype
            .CleanerDryerMachineCapacity = APCSheetHeader.CleanerDryerMachineCapacity
            .ShipmentCapacityMachine = APCSheetHeader.ShipmentCapacityMachine
            .ShipmentCapacityAmount = APCSheetHeader.ShipmentCapacityAmount
            .StorageCapacitybyFlat = APCSheetHeader.StorageCapacitybyFlat
            .StorageCapacitybySilo = APCSheetHeader.StorageCapacitybySilo

            .MachineryTractors = APCSheetHeader.MachineryTractors
            .MachineryTillage = APCSheetHeader.MachineryTillage
            .MachineryHarvesting = APCSheetHeader.MachineryHarvesting
            .MachineryFighting = APCSheetHeader.MachineryFighting
            .MachinerySeedDrill = APCSheetHeader.MachinerySeedDrill
            .MachinerySpecial = APCSheetHeader.MachinerySpecial

            .EconomyArea = APCSheetHeader.EconomyArea
            .EconomyMajorCropsGrown = APCSheetHeader.EconomyMajorCropsGrown
            .EconomyAreaOwner = APCSheetHeader.EconomyAreaOwner
            .EconomyAreaRent = APCSheetHeader.EconomyAreaRent

            .MainCustomers = APCSheetHeader.MainCustomers
            .Description = APCSheetHeader.Description

            .TerritorialArea = APCSheetHeader.TerritorialArea
            .DeferredPaymentDay = APCSheetHeader.DeferredPaymentDay
            .DeferredPaymentHUF = APCSheetHeader.DeferredPaymentHUF

            '.BankPreQualificationState
            '.ManagementQualificationState
            '.ManagementDeferredPaymentDay
            '.ManagementDeferredPaymentHUF
            '.ManagementTerritorialArea

            .Activity = APCSheetHeader.Activity
            .ActivityStartDate = APCSheetHeader.ActivityStartDate
            .IsPrivateCredit = APCSheetHeader.IsPrivateCredit
            .IsPrivateCreditAmountHUF = APCSheetHeader.IsPrivateCreditAmountHUF
            .OtherCompanyInfo = APCSheetHeader.OtherCompanyInfo


        End With

CheckError:
        If Err.Number = 91 Then Resume Next
        If Err.Number = 13 Then Resume Next
    End Sub
    Private Sub APCSheetByProductsOrderInRows_ListView_RefreshAction_Execute(sender As Object, e As SimpleActionExecuteEventArgs)

    End Sub
    Private Sub aAPCSheetHeaderSetAPCStatus_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetHeaderSetAPCStatus.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeaderSetAPCStatus_PopUp As New APCSheetHeaderSetAPCStatus_PopUp(_onew.Session)
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            _APCSheetHeaderSetAPCStatus_PopUp.APCStatus = _APCSheetHeader.APCStatus

            e.View = Application.CreateDetailView(_onew, "APCSheetHeaderSetAPCStatus_PopUp_DetailView", True, _APCSheetHeaderSetAPCStatus_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeaderSetAPCStatus_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetHeaderSetAPCStatus.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetHeaderSetAPCStatus_PopUp As APCSheetHeaderSetAPCStatus_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetHeaderSetAPCStatus_PopUp))
            If _APCSheetHeaderSetAPCStatus_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Select Case _APCSheetHeaderSetAPCStatus_PopUp.APCStatus
                Case eAPCStatus.eRegistered
                    _APCSheetHeader.APCStatus = eAPCStatus.eRegistered
                Case eAPCStatus.eReject
                    _APCSheetHeader.APCStatus = eAPCStatus.eReject
                Case eAPCStatus.eSigned
                    If _APCSheetHeader.APCStatus <> eAPCStatus.eRegistered Then Throw New Exception("*A termeltetési szerződés nem iktatási állapotban van!")
                    If _APCSheetHeader.PDFOriginal Is Nothing Then Throw New Exception("*Nincs becsatolva az eredeti dokumentum!")
                    If _APCSheetHeader.PDFSigned Is Nothing Then Throw New Exception("*Nincs becsatolva az aláírt dokumentum!")
                    If _APCSheetHeader.SalespersonsProposal <> eSalespersonsProposal.eSuggest Then Throw New Exception("*Az üzletkötőnek javasolnia kell a szerződéskötést!")

                    Dim _APCSheetByTerritorial_Area As Double = 0
                    Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=True", _APCSheetHeader))

                    For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                        _APCSheetByTerritorial_Area += _APCSheetByTerritorial.Area
                    Next

                    Dim _APCSheetByTerritorialNo_Area As Double = 0
                    Dim _APCSheetByTerritorialNo_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=False", _APCSheetHeader))

                    For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialNo_Collection
                        _APCSheetByTerritorialNo_Area += _APCSheetByTerritorial.Area
                    Next

                    Dim _APCSheetPresentation_Area As Double = 0
                    Dim _APCSheetPresentation_Collection As New XPCollection(Of APCSheetPresentation)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=?", _APCSheetHeader))

                    For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetPresentation_Collection
                        _APCSheetPresentation_Area += _APCSheetPresentation.Area
                    Next

                    _APCSheetByTerritorial_Area = Math.Round(_APCSheetByTerritorial_Area, 4, MidpointRounding.AwayFromZero)
                    _APCSheetByTerritorialNo_Area = Math.Round(_APCSheetByTerritorialNo_Area, 4, MidpointRounding.AwayFromZero)
                    _APCSheetPresentation_Area = Math.Round(_APCSheetPresentation_Area, 4, MidpointRounding.AwayFromZero)
                    If Math.Round(_APCSheetByTerritorial_Area + _APCSheetByTerritorialNo_Area, 2, MidpointRounding.AwayFromZero) <> Math.Round(_APCSheetPresentation_Area, 2, MidpointRounding.AwayFromZero) Then _
                        Throw New Exception(String.Format("Nem egyezik meg a termelésbe bevont és termelésbe nem bevont területek összege a " + vbNewLine + _
                            "bemutatkozás rovatban szereplő területek összegével! Kérem, ellenőrizze! {0} {1}", Math.Round(_APCSheetByTerritorial_Area + _APCSheetByTerritorialNo_Area, 2, MidpointRounding.AwayFromZero), Math.Round(_APCSheetPresentation_Area, 2, MidpointRounding.AwayFromZero)))

                    _APCSheetHeader.APCStatus = eAPCStatus.eSigned
                Case eAPCStatus.eSendToBank
                    If _APCSheetHeader.APCStatus <> eAPCStatus.eSigned Then Throw New Exception("*A termeltetési szerződés nem aláírt állapotban van!")

                    _APCSheetHeader.APCStatus = eAPCStatus.eSendToBank
                Case eAPCStatus.eSendToInsurrance
                    If _APCSheetHeader.APCStatus <> eAPCStatus.eSendToBank Then Throw New Exception("*A termeltetési szerződés nem bankba küldés állapotban van!")
                    If _APCSheetHeader.ManagementQualificationState <> eBankPreQualificationState.eAccept Then Throw New Exception("*Csak engedélyezett státuszú szerződés küldhető biztosítóhoz!")
                    If _APCSheetHeader.SendToBankDate.Year < GetSQLTime(_onew.Session).Year - 10 Then Throw New Exception("*Nincs beállítva a banki döntés dátuma!")

                    _APCSheetHeader.APCStatus = eAPCStatus.eSendToInsurrance
                Case eAPCStatus.eAccepted
                    If _APCSheetHeader.APCStatus <> eAPCStatus.eSendToInsurrance Then Throw New Exception("*A termeltetési szerződés nem biztosítóhoz küldés állapotban van!")
                    If _APCSheetHeader.ManagementAcceptDocument Is Nothing Then Throw New Exception("*Nincs becsatolva az engedélyezési okirat!")
                    If _APCSheetHeader.ManagementQualificationState <> eBankPreQualificationState.eAccept Then Throw New Exception("*Csak a bank által jóváhagyott szerződés lehet elfogadott státuszban!")
                    If _APCSheetHeader.ManagementDeferredPaymentDay = 0 Then Throw New Exception("*A halaszott fizetési napok száma nem lehet nulla!")
                    If _APCSheetHeader.ManagementDeferredPaymentHUF = 0 Then Throw New Exception("*A jóváhagyott összeg értéke nem lehet nulla!")
                    If Math.Round(_APCSheetHeader.ManagementDeferredPaymentHUF, 1, MidpointRounding.AwayFromZero) < Math.Round(_APCSheetHeader.DeferredPaymentHUF, 1, MidpointRounding.AwayFromZero) Then Throw New Exception("*A biztosító által enegdélyezett összeg kisebb, mint az üzletkötő által javasolt összeg!")
                    If _APCSheetHeader.ManagementTerritorialArea = 0 Then Throw New Exception("*A jóváhagyott terület értéke nem lehet nulla!")

                    _APCSheetHeader.APCStatus = eAPCStatus.eAccepted
            End Select

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_New_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByTerritorial_New.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetByTerritorial_New_PopUp As New APCSheetByTerritorial_New_PopUp(_onew.Session)

            e.View = Application.CreateDetailView(_onew, "APCSheetByTerritorial_New_PopUp_DetailView", True, _APCSheetByTerritorial_New_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_New_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByTerritorial_New.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace

            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_New_PopUp As APCSheetByTerritorial_New_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByTerritorial_New_PopUp))
            If _APCSheetByTerritorial_New_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=True", _APCSheetHeader))

            Dim _APCSheetByTerritorial As New APCSheetByTerritorial(_onew.Session)
            With _APCSheetByTerritorial
                .APCSheetHeader = _APCSheetHeader
                .RowIndex = _APCSheetByTerritorial_Collection.Count + 1
                .Involved = True
                .City = _APCSheetByTerritorial_New_PopUp.City
                .LotNumber = _APCSheetByTerritorial_New_PopUp.LotNumber
                .BlockNumber = _APCSheetByTerritorial_New_PopUp.BlockNumber
                .Area = _APCSheetByTerritorial_New_PopUp.Area
                .Products = _onew.GetObject(_APCSheetByTerritorial_New_PopUp.Products.Products)
                .OwnerState = _APCSheetByTerritorial_New_PopUp.OwnerState
                .DueDateRent = _APCSheetByTerritorial_New_PopUp.DueDateRent
            End With

            Dim _APCSheetByProducts As APCSheetByProducts = _onew.FindObject(Of APCSheetByProducts)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _APCSheetByTerritorial.Products))

            If _APCSheetByProducts IsNot Nothing Then
                _APCSheetByProducts.ContractQuantity += _APCSheetByTerritorial.Area
            Else
                _APCSheetByProducts = New APCSheetByProducts(_onew.Session)
                With _APCSheetByProducts
                    .APCSheetHeader = _APCSheetHeader
                    .Products = _APCSheetByTerritorial.Products
                    .MaxContractQuantity = _APCSheetByTerritorial_New_PopUp.Products.MaxContractQuantity
                    .FundingHatoHUF = _APCSheetByTerritorial_New_PopUp.Products.FundingHatoHUF
                    .RowIndex = _APCSheetHeader.APCSheetByProducts.Count
                    .ColleteralHatoHUF = _APCSheetByTerritorial_New_PopUp.Products.CollateralhatoHUF
                    .ContractQuantity = _APCSheetByTerritorial_New_PopUp.Area
                    Dim _ActYear As Int32 = GetSQLTime(_onew.Session).Year
                    Dim _ActMonth As Int32 = 0
                    Select Case _APCSheetByTerritorial_New_PopUp.Products.ProductExpirationDate
                        Case eMonths.eJanuary
                            _ActMonth = 1
                        Case eMonths.eFebruary
                            _ActMonth = 2
                        Case eMonths.eMarch
                            _ActMonth = 3
                        Case eMonths.eApril
                            _ActMonth = 4
                        Case eMonths.eMay
                            _ActMonth = 5
                        Case eMonths.eJune
                            _ActMonth = 6
                        Case eMonths.eJuly
                            _ActMonth = 7
                        Case eMonths.eAugust
                            _ActMonth = 8
                        Case eMonths.eSeptember
                            _ActMonth = 9
                        Case eMonths.eOctober
                            _ActMonth = 10
                        Case eMonths.eNovember
                            _ActMonth = 11
                        Case eMonths.eDecember
                            _ActMonth = 12
                    End Select
                    If GetSQLTime(_onew.Session).Month < 9 Then
                        .ProductExpirationDate = New Date(_ActYear, _ActMonth + 1, 1).AddDays(-1)
                    Else
                        .ProductExpirationDate = New Date(_ActYear + 1, _ActMonth + 1, 1).AddDays(-1)
                    End If
                End With
            End If

            'Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _APCSheetByTerritorial.Products))
            'If _APCSheetPresentation IsNot Nothing Then
            '    _APCSheetPresentation.Area += _APCSheetByTerritorial_New_PopUp.Area
            'Else
            '    _APCSheetPresentation = New APCSheetPresentation(_onew.Session)
            '    With _APCSheetPresentation
            '        .APCSheetHeader = _APCSheetHeader
            '        .RowIndex = _APCSheetHeader.APCSheetPresentation.Count
            '        .Products = _APCSheetByTerritorial.Products
            '        .PresentationYear = _APCSheetByProducts.ProductExpirationDate.Year
            '        .Area = _APCSheetByTerritorial.Area
            '    End With
            'End If

            _APCSheetHeader.ManagementTerritorialArea += _APCSheetByProducts.ContractQuantity
            _APCSheetHeader.TerritorialArea += _APCSheetByProducts.ContractQuantity


            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByProducts_Delete_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetByProducts_Delete.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetByProducts_DEL_Collection As New ArrayList
            Dim _APCSheetPresentation_DEL_Collection As New ArrayList
            Dim _APCSheetByTerritorial_DEL_Collection As New ArrayList

            For Each _APCSheetByProduct As APCSheetByProducts In View.SelectedObjects
                _APCSheetByProducts_DEL_Collection.Add(_onew.GetObject(_APCSheetByProduct))
                Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _onew.GetObject(_APCSheetByProduct.Products)))
                If _APCSheetPresentation IsNot Nothing Then _APCSheetPresentation_DEL_Collection.Add(_onew.GetObject(_APCSheetPresentation))
                Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _onew.GetObject(_APCSheetByProduct.Products)))
                If _APCSheetByTerritorial_Collection.Count > 0 Then
                    For Each _APCSheetByTerritorial_DEL As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                        _APCSheetByTerritorial_DEL_Collection.Add(_onew.GetObject(_APCSheetByTerritorial_DEL))
                    Next
                End If
            Next

            _onew.Delete(_APCSheetByProducts_DEL_Collection)
            _onew.Delete(_APCSheetByTerritorial_DEL_Collection)
            _onew.Delete(_APCSheetPresentation_DEL_Collection)

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_Delete_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetByTerritorial_Delete.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetPresentation_DEL_Collection As New ArrayList

            For Each _APCSheetByTerritorial As APCSheetByTerritorial In View.SelectedObjects
                _APCSheetPresentation_DEL_Collection.Add(_onew.GetObject(_APCSheetByTerritorial))
                Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _onew.GetObject(_APCSheetByTerritorial.Products)))
                If _APCSheetPresentation IsNot Nothing Then
                    If _APCSheetPresentation.Area - _APCSheetByTerritorial.Area = 0 Then
                        _APCSheetPresentation_DEL_Collection.Add(_APCSheetPresentation)
                    Else
                        _APCSheetPresentation.Area -= _APCSheetByTerritorial.Area
                    End If
                End If

                Dim _APCSheetByProducts As APCSheetByProducts = _onew.FindObject(Of APCSheetByProducts)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _onew.GetObject(_APCSheetByTerritorial.Products)))
                If _APCSheetByProducts IsNot Nothing Then
                    If _APCSheetByProducts.ContractQuantity - _APCSheetByTerritorial.Area = 0 Then
                        _APCSheetPresentation_DEL_Collection.Add(_APCSheetByProducts)
                    Else
                        _APCSheetByProducts.ContractQuantity -= _APCSheetByTerritorial.Area
                    End If
                End If
            Next

            _onew.Delete(_APCSheetPresentation_DEL_Collection)

            _onew.CommitChanges()

            Dim _RowNum As Long = 1
            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=True", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
            If _APCSheetByTerritorial_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                    _APCSheetByTerritorial.RowIndex = _RowNum
                    _RowNum += 1
                Next
            End If

            Dim _APCSheetByProducts_Collection As New XPCollection(Of APCSheetByProducts)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=?", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
            _RowNum = 1
            If _APCSheetByProducts_Collection.Count > 0 Then
                For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetByProducts_Collection
                    _APCSheetByProducts.RowIndex = _RowNum
                    _RowNum += 1
                Next
            End If
            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetPresentation_New_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetPresentation_New.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace()
            Dim _APCSheetPresentation_New_PopUp As New APCSheetPresentation_New_PopUp(_onew.Session)

            e.View = Application.CreateDetailView(_onew, "APCSheetPresentation_New_PopUp_DetailView", True, _APCSheetPresentation_New_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetPresentation_New_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetPresentation_New.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetPresentation_New_PopUp As APCSheetPresentation_New_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetPresentation_New_PopUp))
            If _APCSheetPresentation_New_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetPresentation As New APCSheetPresentation(_onew.Session)
            With _APCSheetPresentation
                .APCSheetHeader = _APCSheetHeader
                .RowIndex = _APCSheetHeader.APCSheetPresentation.Count
                .Products = _onew.GetObject(_APCSheetPresentation_New_PopUp.Products)
                .Area = _APCSheetPresentation_New_PopUp.Area
                .PresentationYear = _APCSheetPresentation_New_PopUp.PresentationYear
            End With

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorialNo_New_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByTerritorialNo_New.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetByTerritorial_New_PopUp As New APCSheetByTerritorial_New_PopUp(_onew.Session)
            _APCSheetByTerritorial_New_PopUp.NeedProducts = False
            e.View = Application.CreateDetailView(_onew, "APCSheetByTerritorial_New_PopUp_DetailView", True, _APCSheetByTerritorial_New_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorialNo_New_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByTerritorialNo_New.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace

            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_New_PopUp As APCSheetByTerritorial_New_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByTerritorial_New_PopUp))
            If _APCSheetByTerritorial_New_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=False", _APCSheetHeader))

            Dim _APCSheetByTerritorial As New APCSheetByTerritorial(_onew.Session)
            With _APCSheetByTerritorial
                .APCSheetHeader = _APCSheetHeader
                .RowIndex = _APCSheetByTerritorial_Collection.Count + 1
                .Involved = False
                .City = _APCSheetByTerritorial_New_PopUp.City
                .LotNumber = _APCSheetByTerritorial_New_PopUp.LotNumber
                .BlockNumber = _APCSheetByTerritorial_New_PopUp.BlockNumber
                .Area = _APCSheetByTerritorial_New_PopUp.Area
                .Products = Nothing
                .OwnerState = _APCSheetByTerritorial_New_PopUp.OwnerState
                .DueDateRent = _APCSheetByTerritorial_New_PopUp.DueDateRent
            End With

            'Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND IsNull(Products)=True AND PresentationYear=?", _
            '                                                                                                                     _APCSheetHeader, GetSQLTime(_onew.Session).Year + 1))
            'If _APCSheetPresentation IsNot Nothing Then
            '    _APCSheetPresentation.Area += _APCSheetByTerritorial.Area
            'Else
            '    _APCSheetPresentation = New APCSheetPresentation(_onew.Session)
            '    With _APCSheetPresentation
            '        .APCSheetHeader = _APCSheetHeader
            '        .RowIndex = _APCSheetHeader.APCSheetPresentation.Count
            '        .Products = _APCSheetByTerritorial.Products
            '        .PresentationYear = GetSQLTime(_onew.Session).Year + 1
            '        .Area = _APCSheetByTerritorial.Area
            '    End With
            'End If

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorialNo_Delete_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetByTerritorialNo_Delete.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetPresentation_DEL_Collection As New ArrayList
            ' Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND IsNull(Products)=True", _APCSheetHeader))

            For Each _APCSheetByTerritorial As APCSheetByTerritorial In View.SelectedObjects
                _APCSheetPresentation_DEL_Collection.Add(_onew.GetObject(_APCSheetByTerritorial))
                ' If _APCSheetPresentation IsNot Nothing Then _APCSheetPresentation.Area -= _APCSheetByTerritorial.Area
            Next

            'If _APCSheetPresentation.Area = 0 Then _APCSheetPresentation_DEL_Collection.Add(_APCSheetPresentation)

            _onew.Delete(_APCSheetPresentation_DEL_Collection)

            _onew.CommitChanges()

            Dim _RowNum As Long = 1
            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=False", _APCSheetHeader))
            If _APCSheetByTerritorial_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                    _APCSheetByTerritorial.RowIndex = _RowNum
                    _RowNum += 1
                Next
                _onew.CommitChanges()
            End If

            OriginalObjectSpaceRefresh()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeaderCreate_Contracts_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetHeaderCreate_Contracts.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            If _APCSheetHeader.APCStatus <> eAPCStatus.eAccepted Then Throw New Exception("*Csak elfogatott státuszú adatlapról lehet szerződést készítnei!")
            If _APCSheetHeader.APCSheetByProducts.Count = 0 Then Throw New Exception("*Az adatlapnak nincs egyetlen olyan sora sem, melyről szerződést lehetne készíteni!")
            Dim _APCSheetByProductsViewItem As DevExpress.ExpressApp.Editors.ListPropertyEditor = TryCast(View, DetailView).FindItem("APCSheetByProducts")
            Dim _ContractNumber As Long = 0

            For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetByProductsViewItem.ListView.SelectedObjects
                If _APCSheetByProducts.Contracts Is Nothing Then
                    _ContractNumber += 1
                    Dim _ProductsFunding As ProductsFunding = _ocur.FindObject(Of ProductsFunding)(CriteriaOperator.Parse("Products=?", _APCSheetByProducts.Products))
                    Dim _CurrencyName As CurrencyName = _ocur.FindObject(Of CurrencyName)(CriteriaOperator.Parse("ShortName='HUF'"))

                    Dim _Contracts As New Contracts(_ocur.Session)
                    With _Contracts
                        .CustomersFrom = _APCSheetHeader.CustomersFrom
                        .Customers = _APCSheetHeader.Customers
                        .DateCreated = _APCSheetByProducts.ContractsSignatureDate
                        .ContractTemplate = _ProductsFunding.ContractTemplate
                        .CurrencyName = _CurrencyName
                        .CurrencyName_Invoice = _CurrencyName
                        .DocumentBody = .ContractTemplate.DocumentBody
                        .ShortName = _APCSheetHeader.ShortName
                    End With

                    _APCSheetByProducts.Contracts = _Contracts
                End If
            Next

            If _ContractNumber = 0 Then Throw New Exception("*A kijelölt sorok mindegyikéhez tartozik szerződés!")

            _ocur.CommitChanges()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_Change_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByTerritorial_Change.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial As APCSheetByTerritorial = TryCast(View.SelectedObjects(0), APCSheetByTerritorial)
            If _APCSheetByTerritorial Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetByTerritorial_Change_PopUp As New APCSheetByTerritorial_Change_PopUp(_onew.Session)
            With _APCSheetByTerritorial_Change_PopUp
                .APCSheetHeader = _APCSheetHeader
                .City = _APCSheetByTerritorial.City
                .LotNumber = _APCSheetByTerritorial.LotNumber
                .BlockNumber = _APCSheetByTerritorial.BlockNumber
                .OwnerState = _APCSheetByTerritorial.OwnerState
                .DueDateRent = _APCSheetByTerritorial.DueDateRent
            End With

            e.View = Application.CreateDetailView(_onew, "APCSheetByTerritorial_Change_PopUp_DetailView", True, _APCSheetByTerritorial_Change_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_Change_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByTerritorial_Change.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial As APCSheetByTerritorial = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetByTerritorial))
            If _APCSheetByTerritorial Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Change_PopUp As APCSheetByTerritorial_Change_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByTerritorial_Change_PopUp))
            If _APCSheetByTerritorial_Change_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            With _APCSheetByTerritorial
                .City = _APCSheetByTerritorial_Change_PopUp.City
                .LotNumber = _APCSheetByTerritorial_Change_PopUp.LotNumber
                .BlockNumber = _APCSheetByTerritorial_Change_PopUp.BlockNumber
                .OwnerState = _APCSheetByTerritorial_Change_PopUp.OwnerState
                .DueDateRent = _APCSheetByTerritorial_Change_PopUp.DueDateRent
            End With

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_ChangeNo_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByTerritorial_ChangeNo.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial As APCSheetByTerritorial = TryCast(View.SelectedObjects(0), APCSheetByTerritorial)
            If _APCSheetByTerritorial Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetByTerritorial_Change_PopUp As New APCSheetByTerritorial_Change_PopUp(_onew.Session)
            With _APCSheetByTerritorial_Change_PopUp
                .APCSheetHeader = _APCSheetHeader
                .City = _APCSheetByTerritorial.City
                .LotNumber = _APCSheetByTerritorial.LotNumber
                .BlockNumber = _APCSheetByTerritorial.BlockNumber
                .OwnerState = _APCSheetByTerritorial.OwnerState
                .DueDateRent = _APCSheetByTerritorial.DueDateRent
            End With

            e.View = Application.CreateDetailView(_onew, "APCSheetByTerritorial_Change_PopUp_DetailView", True, _APCSheetByTerritorial_Change_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_ChangeNo_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByTerritorial_ChangeNo.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial As APCSheetByTerritorial = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetByTerritorial))
            If _APCSheetByTerritorial Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Change_PopUp As APCSheetByTerritorial_Change_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByTerritorial_Change_PopUp))
            If _APCSheetByTerritorial_Change_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            With _APCSheetByTerritorial
                .City = _APCSheetByTerritorial_Change_PopUp.City
                .LotNumber = _APCSheetByTerritorial_Change_PopUp.LotNumber
                .BlockNumber = _APCSheetByTerritorial_Change_PopUp.BlockNumber
                .OwnerState = _APCSheetByTerritorial_Change_PopUp.OwnerState
                .DueDateRent = _APCSheetByTerritorial_Change_PopUp.DueDateRent
            End With

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_InvolvedOUT_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetByTerritorial_InvolvedOUT.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Orig As APCSheetByTerritorial = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetByTerritorial))
            If _APCSheetByTerritorial_Orig Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _APCSheetByProductsReNumbering As Boolean = False
            Dim _APCSheetPresentationReNumbering As Boolean = False
            Dim _RowIndex As Long = 1

            Dim _APCSheetByProducts As APCSheetByProducts = _onew.FindObject(Of APCSheetByProducts)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _APCSheetByTerritorial_Orig.Products))
            If _APCSheetByProducts IsNot Nothing Then
                If _APCSheetByProducts.ContractQuantity - _APCSheetByTerritorial_Orig.Area = 0 Then
                    _onew.Delete(_APCSheetByProducts)
                    _APCSheetByProductsReNumbering = True
                Else
                    _APCSheetByProducts.ContractQuantity -= _APCSheetByTerritorial_Orig.Area
                End If
            End If

            Dim _APCSheetPresentationProducts As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _APCSheetByTerritorial_Orig.Products))
            If _APCSheetPresentationProducts IsNot Nothing Then
                If _APCSheetPresentationProducts.Area - _APCSheetByTerritorial_Orig.Area = 0 Then
                    _onew.Delete(_APCSheetPresentationProducts)
                    _APCSheetPresentationReNumbering = True
                Else
                    _APCSheetPresentationProducts.Area -= _APCSheetByTerritorial_Orig.Area
                End If
            End If

            Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND IsNull(Products)=True", _APCSheetHeader))
            If _APCSheetPresentation IsNot Nothing Then
                _APCSheetPresentation.Area += _APCSheetByTerritorial_Orig.Area
            Else
                _APCSheetPresentation = New APCSheetPresentation(_onew.Session)
                With _APCSheetPresentation
                    .APCSheetHeader = _APCSheetHeader
                    .RowIndex = _APCSheetHeader.APCSheetPresentation.Count + 1
                    .Products = Nothing
                    .PresentationYear = GetSQLTime(_onew.Session).Year + 1
                    .Area = _APCSheetByTerritorial_Orig.Area
                End With
                _APCSheetPresentationReNumbering = True
            End If

            _APCSheetByTerritorial_Orig.Products = Nothing
            _APCSheetByTerritorial_Orig.Involved = False

            _onew.CommitChanges()


            If _APCSheetByProductsReNumbering Then
                _RowIndex = 1
                Dim _APCSheetByProducts_Collection As New XPCollection(Of APCSheetByProducts)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=?", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
                If _APCSheetByProducts_Collection.Count > 0 Then
                    For Each _APCSheetByProductsNumbering As APCSheetByProducts In _APCSheetByProducts_Collection
                        _APCSheetByProductsNumbering.RowIndex = _RowIndex
                        _RowIndex += 1
                    Next
                End If
            End If

            If _APCSheetPresentationReNumbering Then
                _RowIndex = 1
                Dim _APCSheetPresentation_Collection As New XPCollection(Of APCSheetPresentation)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=?", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
                If _APCSheetPresentation_Collection.Count > 0 Then
                    For Each _APCSheetPresentationNumbering As APCSheetPresentation In _APCSheetPresentation_Collection
                        _APCSheetPresentationNumbering.RowIndex = _RowIndex
                        _RowIndex += 1
                    Next
                End If
            End If

            _RowIndex = 1
            Dim _APCSheetByTerritorialInvolved_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=True", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
            If _APCSheetByTerritorialInvolved_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialInvolved_Collection
                    _APCSheetByTerritorial.RowIndex = _RowIndex
                    _RowIndex += 1
                Next
            End If

            _RowIndex = 1
            Dim _APCSheetByTerritorialNoInvolved_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=False", _APCSheetHeader), New SortProperty("RowIndex", DB.SortingDirection.Ascending))
            If _APCSheetByTerritorialNoInvolved_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialNoInvolved_Collection
                    _APCSheetByTerritorial.RowIndex = _RowIndex
                    _RowIndex += 1
                Next
            End If

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_InvolvedIN_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetByTerritorial_InvolvedIN.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetByTerritorial_InvolvedIN_PopUp As New APCSheetByTerritorial_InvolvedIN_PopUp(_onew.Session)

            e.View = Application.CreateDetailView(_onew, "APCSheetByTerritorial_InvolvedIN_PopUp_DetailView", True, _APCSheetByTerritorial_InvolvedIN_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetByTerritorial_InvolvedIN_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetByTerritorial_InvolvedIN.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            Dim _APCSheetByTerritorial_Orig As APCSheetByTerritorial = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetByTerritorial))
            If _APCSheetByTerritorial_Orig Is Nothing Then Throw New Exception("*Nincs kijelölve egyetlen sor sem!")
            Dim _APCSheetByTerritorial_InvolvedIN_PopUp As APCSheetByTerritorial_InvolvedIN_PopUp = _onew.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByTerritorial_InvolvedIN_PopUp))
            If _APCSheetByTerritorial_InvolvedIN_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            If _APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding Is Nothing Then Throw New Exception("*Nem lett kiválasztva egyetlen termék sem a finanszírozáshoz!" + _
                                        vbNewLine + "A folyamat megszakadt!")

            Dim _APCSheetByTerritorialInvolved_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=True", _APCSheetHeader))
            _APCSheetByTerritorial_Orig.Involved = True
            _APCSheetByTerritorial_Orig.Products = _onew.GetObject(_APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.Products)
            _APCSheetByTerritorial_Orig.RowIndex = _APCSheetByTerritorialInvolved_Collection.Count + 1

            Dim _APCSheetPresentation_Products As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _onew.GetObject(_APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.Products)))
            If _APCSheetPresentation_Products IsNot Nothing Then
                _APCSheetPresentation_Products.Area += _APCSheetByTerritorial_Orig.Area
            Else
                _APCSheetPresentation_Products = New APCSheetPresentation(_onew.Session)
                With _APCSheetPresentation_Products
                    .APCSheetHeader = _APCSheetHeader
                    .RowIndex = _APCSheetHeader.APCSheetPresentation.Count
                    .Area = _APCSheetByTerritorial_Orig.Area
                    .PresentationYear = GetSQLTime(_onew.Session).Year + 1
                    .Products = _onew.GetObject(_APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.Products)
                End With
            End If

            Dim _APCSheetPresentation As APCSheetPresentation = _onew.FindObject(Of APCSheetPresentation)(CriteriaOperator.Parse("APCSheetHeader=? AND IsNull(Products)=True", _APCSheetHeader))
            If _APCSheetPresentation IsNot Nothing Then
                If _APCSheetPresentation.Area - _APCSheetByTerritorial_Orig.Area = 0 Then
                    _onew.Delete(_APCSheetPresentation)
                Else
                    _APCSheetPresentation.Area -= _APCSheetByTerritorial_Orig.Area
                End If
            End If

            Dim _APCSheetByProducts As APCSheetByProducts = _onew.FindObject(Of APCSheetByProducts)(CriteriaOperator.Parse("APCSheetHeader=? AND Products=?", _APCSheetHeader, _APCSheetByTerritorial_Orig.Products))
            If _APCSheetByProducts IsNot Nothing Then
                _APCSheetByProducts.ContractQuantity += _APCSheetByTerritorial_Orig.Area
            Else
                _APCSheetByProducts = New APCSheetByProducts(_onew.Session)
                With _APCSheetByProducts
                    .APCSheetHeader = _APCSheetHeader
                    .Products = _APCSheetByTerritorial_Orig.Products
                    .MaxContractQuantity = _APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.MaxContractQuantity
                    .FundingHatoHUF = _APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.FundingHatoHUF
                    .RowIndex = _APCSheetHeader.APCSheetByProducts.Count
                    .ColleteralHatoHUF = _APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.CollateralhatoHUF
                    .ContractQuantity = _APCSheetByTerritorial_Orig.Area
                    Dim _ActYear As Int32 = GetSQLTime(_onew.Session).Year
                    Dim _ActMonth As Int32 = 0
                    Select Case _APCSheetByTerritorial_InvolvedIN_PopUp.ProductsFunding.ProductExpirationDate
                        Case eMonths.eJanuary
                            _ActMonth = 1
                        Case eMonths.eFebruary
                            _ActMonth = 2
                        Case eMonths.eMarch
                            _ActMonth = 3
                        Case eMonths.eApril
                            _ActMonth = 4
                        Case eMonths.eMay
                            _ActMonth = 5
                        Case eMonths.eJune
                            _ActMonth = 6
                        Case eMonths.eJuly
                            _ActMonth = 7
                        Case eMonths.eAugust
                            _ActMonth = 8
                        Case eMonths.eSeptember
                            _ActMonth = 9
                        Case eMonths.eOctober
                            _ActMonth = 10
                        Case eMonths.eNovember
                            _ActMonth = 11
                        Case eMonths.eDecember
                            _ActMonth = 12
                    End Select
                    If GetSQLTime(_onew.Session).Month < 9 Then
                        .ProductExpirationDate = New Date(_ActYear, _ActMonth + 1, 1).AddDays(-1)
                    Else
                        .ProductExpirationDate = New Date(_ActYear + 1, _ActMonth + 1, 1).AddDays(-1)
                    End If
                End With
            End If

            _onew.CommitChanges()

            '<---===Kollekciók rendezése===--->
            Dim _APCSheetPresentation_Collection As New XPCollection(Of APCSheetPresentation)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=?", _APCSheetHeader))
            Dim _RowIndex As Long = 1
            For Each _APCSheetPresentationCount As APCSheetPresentation In _APCSheetPresentation_Collection
                _APCSheetPresentationCount.RowIndex = _RowIndex
                _RowIndex += 1
            Next

            Dim _APCSheetByTerritorialNotInvolved_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Involved=False", _APCSheetHeader))
            _RowIndex = 1
            For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialNotInvolved_Collection
                _APCSheetByTerritorial.RowIndex = _RowIndex
                _RowIndex += 1
            Next

            _onew.CommitChanges()

            OriginalObjectSpaceRefresh()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub OriginalObjectSpaceRefresh()
        Dim nestedFrame As NestedFrame = TryCast(Frame, NestedFrame)
        If nestedFrame IsNot Nothing Then
            Dim parentView As View = nestedFrame.View
            If parentView IsNot Nothing Then parentView.ObjectSpace.Refresh()
        End If
    End Sub
    Private Sub APCSheetHeader_APCSheetPresentation_ListView_DeleteAction_Executed(sender As Object, e As ActionBaseEventArgs)
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _APCSheetHeader As APCSheetHeader = TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader)
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
            _APCSheetHeader.APCSheetPresentation.Sorting.Add(New SortProperty("RowIndex", DB.SortingDirection.Ascending))
            Dim _RowIndex As Long = 1
            For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetHeader.APCSheetPresentation
                _APCSheetPresentation.RowIndex = _RowIndex
                _RowIndex += 1
            Next

            _ocur.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_ReCalculate_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetHeader_ReCalculate.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetHeader))
            If _APCSheetHeader Is Nothing Then Throw New Exception("*Váratlan hiba történt a folyamat megszakadt!")

            _APCSheetHeader.DeferredPaymentHUF = 0
            _APCSheetHeader.TerritorialArea = 0
            _APCSheetHeader.ManagementTerritorialArea = 0
            For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetHeader.APCSheetByProducts
                _APCSheetHeader.DeferredPaymentHUF += _APCSheetByProducts.FundingAmountHUF
                _APCSheetHeader.TerritorialArea += _APCSheetByProducts.ContractQuantity
                _APCSheetHeader.ManagementTerritorialArea += _APCSheetByProducts.ContractQuantity
                If _APCSheetByProducts.FundingDate = Date.MinValue Then
                    _APCSheetByProducts.FundingDate = _APCSheetByProducts.ProductExpirationDate
                End If
            Next

            _APCSheetHeader.SalesDeferredPaymentHUF = _APCSheetHeader.DeferredPaymentHUF

            _APCSheetHeader.EconomyArea = 0
            For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetHeader.APCSheetPresentation
                _APCSheetHeader.EconomyArea += _APCSheetPresentation.Area
            Next

            _APCSheetHeader.EconomyAreaOwner = 0
            Dim _APCSheetByTerritorialOwner_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND OwnerState=0", _APCSheetHeader))
            If _APCSheetByTerritorialOwner_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialOwner_Collection
                    _APCSheetHeader.EconomyAreaOwner += _APCSheetByTerritorial.Area
                Next
            End If

            _APCSheetHeader.EconomyAreaRent = 0
            Dim _APCSheetByTerritorialRent_Collection As New XPCollection(Of APCSheetByTerritorial)(_onew.Session, CriteriaOperator.Parse("APCSheetHeader=? AND (OwnerState=1 OR OwnerState=2)", _APCSheetHeader))
            If _APCSheetByTerritorialRent_Collection.Count > 0 Then
                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialRent_Collection
                    _APCSheetHeader.EconomyAreaRent += _APCSheetByTerritorial.Area
                Next
            End If

            If _APCSheetHeader.DateSigned.Year > 1 Then
                _APCSheetHeader.APCSheetByProducts.Sorting.Add(New SortProperty("ProductExpirationDate", DB.SortingDirection.Descending))
                If _APCSheetHeader.APCSheetByProducts.Count > 0 Then
                    Dim _MaxDate As Date = _APCSheetHeader.APCSheetByProducts(0).ProductExpirationDate
                    _APCSheetHeader.DeferredPaymentDay = CType((_MaxDate - _APCSheetHeader.DateSigned).Days, Long)
                Else
                    _APCSheetHeader.DeferredPaymentDay = 0
                End If
            Else
                _APCSheetHeader.DeferredPaymentDay = 0
            End If
            _APCSheetHeader.ManagementDeferredPaymentDay = _APCSheetHeader.DeferredPaymentDay
            If _APCSheetHeader.APCSheetByProducts.Count > 0 Then
                _APCSheetHeader.MaxExpirationDate = _APCSheetHeader.APCSheetByProducts(0).ProductExpirationDate
            End If


            _onew.CommitChanges()

            If Frame.GetController(Of RefreshController).RefreshAction.Enabled Then
                Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_CreateReviewSheet_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetHeader_CreateReviewSheet.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            Dim _APCSheetByProducts_CollectionSource As New CollectionSource(_onew, GetType(APCSheetByProducts))

            _APCSheetByProducts_CollectionSource.BeginUpdateCriteria()
            _APCSheetByProducts_CollectionSource.Criteria.Add("Criteria", CriteriaOperator.Parse("APCSheetHeader=?", _onew.GetObject(_APCSheetHeader)))
            _APCSheetByProducts_CollectionSource.EndUpdateCriteria()

            e.View = Application.CreateListView("ProductsFunding_ListView", _APCSheetByProducts_CollectionSource, False)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_CreateReviewSheet_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetHeader_CreateReviewSheet.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            Dim _APCSheetByProducts_Select As APCSheetByProducts = TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetByProducts)


            Dim _ReportData As ReportData = _APCSheetHeader.APCParameters.ReportDataReviewSheet
            If _ReportData Is Nothing Then Throw New Exception("*Nincs beállítva nyomtatvány!" + vbNewLine + "A folyamat megszakadt!")

            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Products=? AND Involved=True", _
                                                                                                                                      _APCSheetHeader, _ocur.GetObject(_APCSheetByProducts_Select.Products)))
            Dim _OidArray As New ArrayList

            For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                _OidArray.Add(_APCSheetByTerritorial.Oid)
            Next

            Dim _InOperator As New InOperator("Oid", _OidArray)

            Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, _InOperator, True)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_OpenContract_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetHeader_OpenContract.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

            Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
            Dim _APCSheetByProductsViewItem As DevExpress.ExpressApp.Editors.ListPropertyEditor = TryCast(View, DetailView).FindItem("APCSheetByProducts")
            Dim _APCSheetByProducts As APCSheetByProducts = _APCSheetByProductsViewItem.ListView.SelectedObjects(0)

            If _APCSheetByProducts.Contracts IsNot Nothing Then
                Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
                Dim _ShowViewParameters As New ShowViewParameters
                Dim _ShowViewSource As New ShowViewSource(Frame, Nothing)

                _ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "Contracts_DetailView", True, _onew.GetObject(_APCSheetByProducts.Contracts))
                _ShowViewParameters.NewWindowTarget = NewWindowTarget.MdiChild
                _ShowViewParameters.TargetWindow = TargetWindow.NewWindow
                Application.ShowViewStrategy.ShowView(_ShowViewParameters, _ShowViewSource)
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_CreateAPCSheetreviewHeader_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetHeader_CreateAPCSheetreviewHeader.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _APCSheetHeader As APCSheetHeader = TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, APCSheetHeader)
        Dim _APCSheetByProducts As APCSheetByProducts = TryCast(View.SelectedObjects(0), APCSheetByProducts)
        If _APCSheetHeader IsNot Nothing Then
            Dim _APCSheetByTerritorial_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND Products=? AND Involved=True", _APCSheetHeader, _APCSheetByProducts.Products))
            If _APCSheetByTerritorial_Collection.Count > 0 Then
                Dim _APCSheetReviewHeader As New APCSheetReviewHeader(_ocur.Session)
                With _APCSheetReviewHeader
                    .APCSheetByProducts = TryCast(View.SelectedObjects(0), APCSheetByProducts)
                    .Description = _APCSheetHeader.DocumentNumber + " - " + .APCSheetByProducts.Products.ShortName
                End With

                For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorial_Collection
                    Dim _APCSheetReviewRows As New APCSheetReviewRows(_ocur.Session)
                    With _APCSheetReviewRows
                        .APCSheetReviewHeader = _APCSheetReviewHeader
                        .APCSheetByTerritorial = _APCSheetByTerritorial
                    End With
                Next

                _ocur.CommitChanges()
            End If
        End If
    End Sub
    Private Sub aAPCSheetHeader_OpenAPCSheetReviewHeader_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheetHeader_OpenAPCSheetReviewHeader.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _APCSheetReviewHeader As APCSheetReviewHeader = _onew.GetObject(TryCast(View.SelectedObjects(0), APCSheetReviewHeader))

        If _APCSheetReviewHeader IsNot Nothing Then
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "APCSheetReviewHeader_DetailView", True, _APCSheetReviewHeader)
        End If

    End Sub
    'Private Sub aAPCSheetHeader_Clone_Execute(sender As Object, e As SimpleActionExecuteEventArgs)
    '    Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
    '    Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
    '    Dim _YearString As String = Now.Year.ToString
    '    RaiseEvent InitWork(1, 1, _APCSheetHeader.APCSheetByTerritorial.Count)

    '    If _APCSheetHeader IsNot Nothing Then
    '        Dim _APCSheetHeader_NEW As New APCSheetHeader(_ocur.Session)

    '        With _APCSheetHeader_NEW
    '            .APCParameters = Nothing '_APCSheetHeader.APCParameters Laci kérése 2013.09.17
    '            .HRPerson = _APCSheetHeader.HRPerson
    '            .Customers = _APCSheetHeader.Customers
    '            .Contacts = _APCSheetHeader.Contacts
    '            .ContactsWithFullRight = _APCSheetHeader.ContactsWithFullRight
    '            .CustomersFrom = _APCSheetHeader.CustomersFrom
    '            .CropProtectionSpecialist = _APCSheetHeader.CropProtectionSpecialist
    '            .ShortName = _APCSheetHeader.ShortName
    '            .APCStatus = eAPCStatus.eRegistered
    '            .PDFOriginal = Nothing
    '            .PDFSigned = Nothing
    '            .IsNewContact = True
    '            .PaymentDiscipline = _APCSheetHeader.PaymentDiscipline
    '            .CleanerDryerMachinetype = _APCSheetHeader.CleanerDryerMachinetype
    '            .CleanerDryerMachineCapacity = _APCSheetHeader.CleanerDryerMachineCapacity
    '            .ShipmentCapacityMachine = _APCSheetHeader.ShipmentCapacityMachine
    '            .ShipmentCapacityAmount = _APCSheetHeader.ShipmentCapacityAmount
    '            .StorageCapacitybyFlat = _APCSheetHeader.StorageCapacitybyFlat
    '            .StorageCapacitybySilo = _APCSheetHeader.StorageCapacitybySilo
    '            .MachineryTractors = _APCSheetHeader.MachineryTractors
    '            .MachineryTillage = _APCSheetHeader.MachineryTillage
    '            .MachineryHarvesting = _APCSheetHeader.MachineryHarvesting
    '            .MachineryFighting = _APCSheetHeader.MachineryFighting
    '            .MachinerySeedDrill = _APCSheetHeader.MachinerySeedDrill
    '            .MachinerySpecial = _APCSheetHeader.MachinerySpecial
    '            .EconomyMajorCropsGrown = _APCSheetHeader.EconomyMajorCropsGrown
    '            .MainCustomers = _APCSheetHeader.MainCustomers
    '            .Description = _APCSheetHeader.Description
    '            .TerritorialArea = 0
    '            .DeferredPaymentDay = 0
    '            .DeferredPaymentHUF = 0
    '            .SalespersonsProposal = eSalespersonsProposal.eNotRecommended
    '            .SalesDeferredPaymentHUF = 0
    '            .BankPreQualificationState = eBankPreQualificationState.eNotSet
    '            .ManagementQualificationState = eManagementQualificationState.eNotSet
    '            .ManagementDeferredPaymentDay = 0
    '            .ManagementDeferredPaymentHUF = 0
    '            .ManagementTerritorialArea = 0
    '            .ManagementAcceptType = eManagementAcceptType.eNotSet
    '            .ManagementAcceptDocument = Nothing
    '            .ManagementAcceptPerson = Nothing
    '            .Activity = _APCSheetHeader.Activity
    '            .ActivityStartDate = _APCSheetHeader.ActivityStartDate
    '            .IsPrivateCredit = _APCSheetHeader.IsPrivateCredit
    '            .IsPrivateCreditAmountHUF = _APCSheetHeader.IsPrivateCreditAmountHUF
    '            .OtherCompanyInfo = _APCSheetHeader.OtherCompanyInfo
    '            .APCSheetAdministrator = _APCSheetHeader.APCSheetAdministrator
    '            .APCSheetContractHandlingPlace = _APCSheetHeader.APCSheetContractHandlingPlace

    '            'Sorszám 08.31 után a következő év !
    '            'If GetSQLTime(_ocur.Session).Month > 8 Then
    '            '    _YearString = (GetSQLTime(_ocur.Session).Year + 1).ToString
    '            '    .DocumentNumber = .APCParameters.NumberGenerator.GetNewNumber(.APCParameters.NumberGenerator, _YearString)
    '            'End If

    '            For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetHeader.APCSheetByTerritorial
    '                Dim _APCSheetByTerritorial_NEW As New APCSheetByTerritorial(_ocur.Session)
    '                With _APCSheetByTerritorial_NEW
    '                    .APCSheetHeader = _APCSheetHeader_NEW
    '                    .RowIndex = _APCSheetByTerritorial.RowIndex
    '                    .Involved = False
    '                    .City = _APCSheetByTerritorial.City
    '                    .LotNumber = _APCSheetByTerritorial.LotNumber
    '                    .BlockNumber = _APCSheetByTerritorial.BlockNumber
    '                    .Area = _APCSheetByTerritorial.Area
    '                    .Products = _APCSheetByTerritorial.Products
    '                    .OwnerState = _APCSheetByTerritorial.OwnerState
    '                    .DueDateRent = _APCSheetByTerritorial.DueDateRent
    '                End With
    '                RaiseEvent DoWork()
    '            Next

    '        End With

    '        _ocur.CommitChanges()

    '        'Recalculate
    '        _APCSheetHeader_NEW.DeferredPaymentHUF = 0
    '        _APCSheetHeader_NEW.TerritorialArea = 0
    '        _APCSheetHeader_NEW.ManagementTerritorialArea = 0
    '        For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetHeader_NEW.APCSheetByProducts
    '            _APCSheetHeader_NEW.DeferredPaymentHUF += _APCSheetByProducts.FundingAmountHUF
    '            _APCSheetHeader_NEW.TerritorialArea += _APCSheetByProducts.ContractQuantity
    '            _APCSheetHeader_NEW.ManagementTerritorialArea += _APCSheetByProducts.ContractQuantity
    '        Next

    '        _APCSheetHeader_NEW.SalesDeferredPaymentHUF = _APCSheetHeader_NEW.DeferredPaymentHUF

    '        _APCSheetHeader_NEW.EconomyArea = 0
    '        For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetHeader_NEW.APCSheetPresentation
    '            _APCSheetHeader_NEW.EconomyArea += _APCSheetPresentation.Area
    '        Next

    '        _APCSheetHeader_NEW.EconomyAreaOwner = 0
    '        Dim _APCSheetByTerritorialOwner_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND OwnerState=0", _APCSheetHeader_NEW))
    '        If _APCSheetByTerritorialOwner_Collection.Count > 0 Then
    '            For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialOwner_Collection
    '                _APCSheetHeader_NEW.EconomyAreaOwner += _APCSheetByTerritorial.Area
    '            Next
    '        End If

    '        _APCSheetHeader_NEW.EconomyAreaRent = 0
    '        Dim _APCSheetByTerritorialRent_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND (OwnerState=1 OR OwnerState=2)", _APCSheetHeader_NEW))
    '        If _APCSheetByTerritorialRent_Collection.Count > 0 Then
    '            For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialRent_Collection
    '                _APCSheetHeader_NEW.EconomyAreaRent += _APCSheetByTerritorial.Area
    '            Next
    '        End If

    '        If _APCSheetHeader_NEW.DateSigned.Year > 1 Then
    '            _APCSheetHeader_NEW.APCSheetByProducts.Sorting.Add(New SortProperty("ProductExpirationDate", DB.SortingDirection.Descending))
    '            If _APCSheetHeader_NEW.APCSheetByProducts.Count > 0 Then
    '                Dim _MaxDate As Date = _APCSheetHeader_NEW.APCSheetByProducts(0).ProductExpirationDate
    '                _APCSheetHeader_NEW.DeferredPaymentDay = CType((_MaxDate - _APCSheetHeader_NEW.DateSigned).Days, Long)
    '            Else
    '                _APCSheetHeader_NEW.DeferredPaymentDay = 0
    '            End If
    '        Else
    '            _APCSheetHeader_NEW.DeferredPaymentDay = 0
    '        End If
    '        _APCSheetHeader_NEW.ManagementDeferredPaymentDay = _APCSheetHeader_NEW.DeferredPaymentDay
    '        If _APCSheetHeader.APCSheetByProducts.Count > 0 Then
    '            _APCSheetHeader.MaxExpirationDate = _APCSheetHeader.APCSheetByProducts(0).ProductExpirationDate
    '        End If

    '        _ocur.CommitChanges()

    '        RaiseEvent FinalWork

    '        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace

    '        e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "APCSheetHeader_DetailView", True, _onew.GetObject(_APCSheetHeader_NEW))
    '    End If

    'End Sub
    Private Sub aAPCSheet_PSPH_Print_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheet_PSPH_Print.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _APCSheetByProductsSalesPolicyH As APCSheetByProductsSalesPolicyH = TryCast(View.SelectedObjects(0), APCSheetByProductsSalesPolicyH)
        If _APCSheetByProductsSalesPolicyH IsNot Nothing Then
            Dim _APCParameters As APCParameters = _ocur.FindObject(Of APCParameters)(CriteriaOperator.Parse("CustomersFrom=?", _APCSheetByProductsSalesPolicyH.CustomersFrom))
            If _APCParameters IsNot Nothing Then
                Dim _ReportData As ReportData = _APCParameters.ReportDataSalesPolicy
                If _ReportData IsNot Nothing Then
                    Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("APCSheetByProductsSalesPolicyH.Oid=?", _APCSheetByProductsSalesPolicyH.Oid), True)
                End If
            End If

        End If
    End Sub
    Private Sub aAPCSheet_PSPH_GeneratePDFFile_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAPCSheet_PSPH_GeneratePDFFile.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _APCSheetByProductsSalesPolicyH As APCSheetByProductsSalesPolicyH = TryCast(View.SelectedObjects(0), APCSheetByProductsSalesPolicyH)
        If _APCSheetByProductsSalesPolicyH IsNot Nothing Then
            Dim _APCParameters As APCParameters = _ocur.FindObject(Of APCParameters)(CriteriaOperator.Parse("CustomersFrom=?", _APCSheetByProductsSalesPolicyH.CustomersFrom))
            If _APCParameters IsNot Nothing Then
                Dim _ReportData As ReportData = _APCParameters.ReportDataSalesPolicy
                If _ReportData IsNot Nothing Then


                    Dim _XafReport As XafReport = _ReportData.LoadReport(_ocur)

                    Dim _FilterString As String = "[APCSheetByProductsSalesPolicyH.Oid]='" & _APCSheetByProductsSalesPolicyH.Oid.ToString & "'"
                    _XafReport.FilterString = _FilterString
                    Dim _FileName As String = System.IO.Path.GetTempPath & _APCSheetByProductsSalesPolicyH.DocumentNumber & " nyilatkozat.pdf"
                    Dim _StreamFile As New System.IO.FileStream(_FileName, FileMode.Create)

                    _XafReport.ExportToPdf(_StreamFile)
                    _StreamFile.Close()

                    Dim _StreamFile2 As New FileStream(_FileName, FileMode.Open)

                    _APCSheetByProductsSalesPolicyH.FileData = New FileData(_ocur.Session)
                    _APCSheetByProductsSalesPolicyH.FileData.LoadFromStream(_APCSheetByProductsSalesPolicyH.DocumentNumber & " nyilatkozat.pdf", _StreamFile2)
                    _StreamFile2.Close()

                    _ocur.CommitChanges()

                    If File.Exists(_FileName) Then File.Delete(_FileName)
                End If
            End If
        End If
    End Sub
    Private Sub aAPCSheetHeader_Clones_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAPCSheetHeader_Clones.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _APCSheetHeaderSetAPCParameters_PopUp As New APCSheetHeaderSetAPCParameters_PopUp(_onew.Session)

            e.View = Application.CreateDetailView(_onew, "APCSheetHeaderSetAPCParameters_PopUp_DetailView", True, _APCSheetHeaderSetAPCParameters_PopUp)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aAPCSheetHeader_Clones_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAPCSheetHeader_Clones.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _APCSheetHeader As APCSheetHeader = TryCast(View.SelectedObjects(0), APCSheetHeader)
        Dim _YearString As String = Now.Year.ToString
        Dim _APCSheetHeaderSetAPCParameters_PopUp As APCSheetHeaderSetAPCParameters_PopUp = _ocur.GetObject(TryCast(e.PopupWindow.View.SelectedObjects(0), APCSheetHeaderSetAPCParameters_PopUp))

        'If _APCSheetHeaderSetAPCParameters_PopUp Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")
        'If _APCSheetHeaderSetAPCParameters_PopUp.APCParameter Is Nothing Then Throw New Exception("*Nem lett kiválasztva egyetlen paraméter sem a termeltetési adatlaphoz!" + _
        '                            vbNewLine + "A folyamat megszakadt!")

        Try
            RaiseEvent InitWork(1, 1, _APCSheetHeader.APCSheetByTerritorial.Count)

            If _APCSheetHeader IsNot Nothing Then
                Dim _APCSheetHeader_NEW As New APCSheetHeader(_ocur.Session)

                With _APCSheetHeader_NEW
                    .APCParameters = _ocur.GetObject(_APCSheetHeaderSetAPCParameters_PopUp.APCParameter) '_APCSheetHeader.APCParameters Laci kérése 2013.09.17
                    .HRPerson = _APCSheetHeader.HRPerson
                    .Customers = _APCSheetHeader.Customers
                    .Contacts = _APCSheetHeader.Contacts
                    .ContactsWithFullRight = _APCSheetHeader.ContactsWithFullRight
                    .CustomersFrom = _APCSheetHeader.CustomersFrom
                    .CropProtectionSpecialist = _APCSheetHeader.CropProtectionSpecialist
                    .ShortName = _APCSheetHeader.ShortName
                    .APCStatus = eAPCStatus.eRegistered
                    .PDFOriginal = Nothing
                    .PDFSigned = Nothing
                    .IsNewContact = True
                    .PaymentDiscipline = _APCSheetHeader.PaymentDiscipline
                    .CleanerDryerMachinetype = _APCSheetHeader.CleanerDryerMachinetype
                    .CleanerDryerMachineCapacity = _APCSheetHeader.CleanerDryerMachineCapacity
                    .ShipmentCapacityMachine = _APCSheetHeader.ShipmentCapacityMachine
                    .ShipmentCapacityAmount = _APCSheetHeader.ShipmentCapacityAmount
                    .StorageCapacitybyFlat = _APCSheetHeader.StorageCapacitybyFlat
                    .StorageCapacitybySilo = _APCSheetHeader.StorageCapacitybySilo
                    .MachineryTractors = _APCSheetHeader.MachineryTractors
                    .MachineryTillage = _APCSheetHeader.MachineryTillage
                    .MachineryHarvesting = _APCSheetHeader.MachineryHarvesting
                    .MachineryFighting = _APCSheetHeader.MachineryFighting
                    .MachinerySeedDrill = _APCSheetHeader.MachinerySeedDrill
                    .MachinerySpecial = _APCSheetHeader.MachinerySpecial
                    .EconomyMajorCropsGrown = _APCSheetHeader.EconomyMajorCropsGrown
                    .MainCustomers = _APCSheetHeader.MainCustomers
                    .Description = _APCSheetHeader.Description
                    .TerritorialArea = 0
                    .DeferredPaymentDay = 0
                    .DeferredPaymentHUF = 0
                    .SalespersonsProposal = eSalespersonsProposal.eNotRecommended
                    .SalesDeferredPaymentHUF = 0
                    .BankPreQualificationState = eBankPreQualificationState.eNotSet
                    .ManagementQualificationState = eManagementQualificationState.eNotSet
                    .ManagementDeferredPaymentDay = 0
                    .ManagementDeferredPaymentHUF = 0
                    .ManagementTerritorialArea = 0
                    .ManagementAcceptType = eManagementAcceptType.eNotSet
                    .ManagementAcceptDocument = Nothing
                    .ManagementAcceptPerson = Nothing
                    .Activity = _APCSheetHeader.Activity
                    .ActivityStartDate = _APCSheetHeader.ActivityStartDate
                    .IsPrivateCredit = _APCSheetHeader.IsPrivateCredit
                    .IsPrivateCreditAmountHUF = _APCSheetHeader.IsPrivateCreditAmountHUF
                    .OtherCompanyInfo = _APCSheetHeader.OtherCompanyInfo
                    .APCSheetAdministrator = _APCSheetHeader.APCSheetAdministrator
                    .APCSheetContractHandlingPlace = _APCSheetHeader.APCSheetContractHandlingPlace

                    'Sorszám 08.31 után a következő év !
                    'If GetSQLTime(_ocur.Session).Month > 8 Then
                    '    _YearString = (GetSQLTime(_ocur.Session).Year + 1).ToString
                    '    .DocumentNumber = .APCParameters.NumberGenerator.GetNewNumber(.APCParameters.NumberGenerator, _YearString)
                    'End If

                    For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetHeader.APCSheetByTerritorial
                        Dim _APCSheetByTerritorial_NEW As New APCSheetByTerritorial(_ocur.Session)
                        With _APCSheetByTerritorial_NEW
                            .APCSheetHeader = _APCSheetHeader_NEW
                            .RowIndex = _APCSheetByTerritorial.RowIndex
                            .Involved = False
                            .City = _APCSheetByTerritorial.City
                            .LotNumber = _APCSheetByTerritorial.LotNumber
                            .BlockNumber = _APCSheetByTerritorial.BlockNumber
                            .Area = _APCSheetByTerritorial.Area
                            .Products = _APCSheetByTerritorial.Products
                            .OwnerState = _APCSheetByTerritorial.OwnerState
                            .DueDateRent = _APCSheetByTerritorial.DueDateRent
                        End With
                        RaiseEvent DoWork()
                    Next

                End With

                _ocur.CommitChanges()

                'Recalculate
                _APCSheetHeader_NEW.DeferredPaymentHUF = 0
                _APCSheetHeader_NEW.TerritorialArea = 0
                _APCSheetHeader_NEW.ManagementTerritorialArea = 0
                For Each _APCSheetByProducts As APCSheetByProducts In _APCSheetHeader_NEW.APCSheetByProducts
                    _APCSheetHeader_NEW.DeferredPaymentHUF += _APCSheetByProducts.FundingAmountHUF
                    _APCSheetHeader_NEW.TerritorialArea += _APCSheetByProducts.ContractQuantity
                    _APCSheetHeader_NEW.ManagementTerritorialArea += _APCSheetByProducts.ContractQuantity
                Next

                _APCSheetHeader_NEW.SalesDeferredPaymentHUF = _APCSheetHeader_NEW.DeferredPaymentHUF

                _APCSheetHeader_NEW.EconomyArea = 0
                For Each _APCSheetPresentation As APCSheetPresentation In _APCSheetHeader_NEW.APCSheetPresentation
                    _APCSheetHeader_NEW.EconomyArea += _APCSheetPresentation.Area
                Next

                _APCSheetHeader_NEW.EconomyAreaOwner = 0
                Dim _APCSheetByTerritorialOwner_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND OwnerState=0", _APCSheetHeader_NEW))
                If _APCSheetByTerritorialOwner_Collection.Count > 0 Then
                    For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialOwner_Collection
                        _APCSheetHeader_NEW.EconomyAreaOwner += _APCSheetByTerritorial.Area
                    Next
                End If

                _APCSheetHeader_NEW.EconomyAreaRent = 0
                Dim _APCSheetByTerritorialRent_Collection As New XPCollection(Of APCSheetByTerritorial)(_ocur.Session, CriteriaOperator.Parse("APCSheetHeader=? AND (OwnerState=1 OR OwnerState=2)", _APCSheetHeader_NEW))
                If _APCSheetByTerritorialRent_Collection.Count > 0 Then
                    For Each _APCSheetByTerritorial As APCSheetByTerritorial In _APCSheetByTerritorialRent_Collection
                        _APCSheetHeader_NEW.EconomyAreaRent += _APCSheetByTerritorial.Area
                    Next
                End If

                If _APCSheetHeader_NEW.DateSigned.Year > 1 Then
                    _APCSheetHeader_NEW.APCSheetByProducts.Sorting.Add(New SortProperty("ProductExpirationDate", DB.SortingDirection.Descending))
                    If _APCSheetHeader_NEW.APCSheetByProducts.Count > 0 Then
                        Dim _MaxDate As Date = _APCSheetHeader_NEW.APCSheetByProducts(0).ProductExpirationDate
                        _APCSheetHeader_NEW.DeferredPaymentDay = CType((_MaxDate - _APCSheetHeader_NEW.DateSigned).Days, Long)
                    Else
                        _APCSheetHeader_NEW.DeferredPaymentDay = 0
                    End If
                Else
                    _APCSheetHeader_NEW.DeferredPaymentDay = 0
                End If
                _APCSheetHeader_NEW.ManagementDeferredPaymentDay = _APCSheetHeader_NEW.DeferredPaymentDay
                If _APCSheetHeader.APCSheetByProducts.Count > 0 Then
                    _APCSheetHeader.MaxExpirationDate = _APCSheetHeader.APCSheetByProducts(0).ProductExpirationDate
                End If

                _ocur.CommitChanges()



                'Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace

                'e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "APCSheetHeader_DetailView", True, _onew.GetObject(_APCSheetHeader_NEW))
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        Finally
            RaiseEvent FinalWork()
        End Try

    End Sub

    Private Sub APCSheetHeaderSetAPCParameters_PopUp_AcceptAction_Executing(sender As Object, e As CancelEventArgs)
        Dim _APCSheetHeaderSetAPCParameters_PopUp As APCSheetHeaderSetAPCParameters_PopUp = TryCast(View.SelectedObjects(0), APCSheetHeaderSetAPCParameters_PopUp)
        If _APCSheetHeaderSetAPCParameters_PopUp.APCParameter Is Nothing Then
            e.Cancel = True
            MsgBox("A paraméreteket kötelező megadni!", MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End If
    End Sub

End Class
