VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.ocx"
Begin VB.UserControl MetalCompare 
   ClientHeight    =   6675
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   9750
   ScaleHeight     =   6675
   ScaleWidth      =   9750
   Begin MSComctlLib.ProgressBar prg_progress 
      Height          =   240
      Left            =   210
      TabIndex        =   5
      Top             =   6390
      Width           =   9435
      _ExtentX        =   16642
      _ExtentY        =   423
      _Version        =   393216
      Appearance      =   1
   End
   Begin VB.TextBox txt_status 
      Appearance      =   0  'Flat
      BackColor       =   &H80000000&
      Height          =   240
      Left            =   1050
      Locked          =   -1  'True
      TabIndex        =   4
      Text            =   "Text1"
      Top             =   6135
      Width           =   8430
   End
   Begin Project1.ToolbarControl tlb_main 
      Height          =   690
      Left            =   -15
      TabIndex        =   1
      Top             =   30
      Width           =   9720
      _ExtentX        =   17145
      _ExtentY        =   1217
   End
   Begin VB.Frame frm_main 
      Caption         =   "frm_main"
      Height          =   5220
      Left            =   15
      TabIndex        =   0
      Tag             =   "frm_main"
      Top             =   855
      Width           =   9585
      Begin Project1.ArmGrid grd_main 
         Height          =   4755
         Left            =   195
         TabIndex        =   2
         Tag             =   "grd_main"
         Top             =   315
         Width           =   9240
         _ExtentX        =   16298
         _ExtentY        =   8387
      End
   End
   Begin VB.Label lbl_status 
      Caption         =   "#Status:"
      Height          =   225
      Left            =   75
      TabIndex        =   3
      Top             =   6135
      Width           =   885
   End
End
Attribute VB_Name = "MetalCompare"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK API FUNCTION DECLARES
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function GetSystemDefaultLCID Lib "kernel32" () As Long


#If ENV = LIVE Then
    Dim mo_Db As Object
#Else
    Dim mo_Db As ARMSYSCOMLib.ArmDb
#End If

#If ENV = LIVE Then
    Dim mo_Sys As Object
#Else
    Dim mo_Sys As ARMSYSCOMLib.ArmSYS
#End If


Dim mo_XMLDoc  As Object

Const C_GETASMATERIAL_URL As String = "http://10.68.16.36/TestService/Service1.asmx/SAPProductsList"
Const C_SAP_LOGIN As String = "NXT"
Const C_SAP_PASSW As String = "ous42pri"


Private ms_Language_Code    As String       'current user interface language
Private ml_U_Code           As Long         'U_Code (GEN_Systems_Users) of logged user
Private ms_LoginName        As String
Private mb_InternalInit     As Boolean      'framework is doing some own control manipulation, all events should handle
Private mb_Initialized      As Boolean      'framework is initialised or not

Private Const SEP = "®©"
Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const SCREEN_NAME       As String = "MetalCompare"
Private ms_DecimalSeparator     As String       'locale decimal separator
Private ms_ThousandSeparator    As String       'locale thousand separator
Dim ms_MsgInfo As Variant

Private Const SW_SHOWNORMAL = 1
Private Const LOCALE_USER_DEFAULT = &H400
Private Const LOCALE_SDECIMAL = &HE ' Decimal separator
Private Const LOCALE_STHOUSAND = &HF ' Thousand separator

Const C_ERRORRAISE As Long = 50000

Private Enum ArmErr
    DBCnxFailed = C_ERRORRAISE + 1             ' Unable to connect to the database
    CPTAlreadyInitialized = C_ERRORRAISE + 2   ' We try to initialize a component that is already initialized
    CPTNotInitialized = C_ERRORRAISE + 3       ' We try to use or free that is not initialized yet
    InvalidArgument = C_ERRORRAISE + 4
    PropertyNotSet = C_ERRORRAISE + 5
    SQLFailure = C_ERRORRAISE + 6               ' A SQL runtime error has occured : syntax wrong....
    SQLBadRowAffectedCount = C_ERRORRAISE + 7   ' A SQL request has not affected the expected rowcount (ex: one Update do nothing)
    SQLBadRowExpectedCount = C_ERRORRAISE + 8   ' A SQL request does not return the expected rowcount : select an item return nothing...
    DrivingError = C_ERRORRAISE + 9
    CompFncFailed = C_ERRORRAISE + 10           ' when component function fail
    GridLoadFailed = C_ERRORRAISE + 11          ' load function failed ... bad sql
    InvalidValue = C_ERRORRAISE + 12          ' load function failed ... bad sql
End Enum

Private Enum ArmCusErr
    DuplicityDetected = C_ERRORRAISE + 2301                ' detected row with same unique id
End Enum

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK EVENTS
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Public Event quit()

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK CUSTOM METHODS
' Change content of methods as you need, but do not add any new method or property here !
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Private Function Load_A_COM_Custom() As Boolean
On Error GoTo ErrHandler
    Load_A_COM_Custom = True
    Exit Function
ErrHandler:
    Call ErrorHandler("Load_A_COM_Custom")
End Function

Private Sub UnLoad_A_COM_Custom()
On Error GoTo ErrHandler
    Exit Sub
ErrHandler:
    Call ErrorHandler("UnLoad_A_COM_Custom")
End Sub

Private Sub Init_Custom()
On Error GoTo ErrHandler

    'Initialization of the component of the form

    ' toolbar init
    ' main grid
    Dim la_Columns(5) As String
    la_Columns(0) = "BI_SAP_code" & SEP & "800" & SEP & "1" & SEP & "BI_SAP_code" & SEP & "BI_SAP_code"
    la_Columns(1) = "BI_desc" & SEP & "4000" & SEP & "0" & SEP & "BI_desc" & SEP & "#BI_desc"
    la_Columns(2) = "BI_a_free1" & SEP & "800" & SEP & "0" & SEP & "BI_a_free1" & SEP & "#BI_a_free1 (Sifyb AS)"
    la_Columns(3) = "Z_Creation" & SEP & "1000" & SEP & "0" & SEP & "Z_Creation" & SEP & "#Creation date"
    la_Columns(4) = "MARA_EXTWG" & SEP & "1300" & SEP & "0" & SEP & "MARA-EXTWG" & SEP & "#MARA-EXTWG (SAP AS)"
    la_Columns(5) = "MARA_ERSDA" & SEP & "1000" & SEP & "0" & SEP & "MARA-ERSDA" & SEP & "#SAP Creation date"

    
    grd_main.ExportTitles = True
    grd_main.AllowExcelExport = True
    grd_main.FetchAll = True
    grd_main.AllowSort = False
    
    If Not grd_main.SetColumns(la_Columns) Then
        MsgBox "Set columns failed"
    End If
    
    grd_main.Title = "#AS Material compare grid"
    
    Dim ls_req As String
    Dim ll_Cursor As Long
    
    ls_req = "exec A_ToolbarDef_sel NULL,1,23,NULL"
    ll_Cursor = OpenSQLSafe(mo_Db, ls_req)
    
    If mo_Db.Find(ll_Cursor, "Id", 200) < 0 Then       ' 289EESFGIDRW®01763®QE/BAC®AFFCTT
'        Err.Raise ArmErr.InvalidValue, tlb_main.Name, "Toolbar not found in toolbars_definitions ID: 2934"
    End If
    
    Dim ls_ToolbarInfo  As String
    ls_ToolbarInfo = mo_Db.GetFields(ll_Cursor, "info")
    If ls_ToolbarInfo = "" Then ls_ToolbarInfo = "289EESFGIDRW®01763®QE/BAC®AFFCTT"
    If Not tlb_Main.SetToolbarInfoStringParameters(ls_ToolbarInfo, Left(ls_ToolbarInfo, 3)) Then
        Err.Raise ArmErr.InvalidValue, tlb_Main.Name, "SetToolbarInfoStringParameters failed for toolbar ID: 2934"
    End If
    Call tlb_Main.DisplayFace("0")

    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    txt_Status.Text = "OK"

    Exit Sub
ErrHandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    Call ErrorHandler("Init_Custom")
End Sub





'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK PROPERTIES
' please DO NOT change anything in this part of code
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Public Property Get Initialized() As Boolean
    Initialized = mb_Initialized
End Property


Property Let U_Code(al_Code As Long)
ml_U_Code = al_Code
End Property

Property Let LoginName(as_Login As String)
ms_LoginName = as_Login
End Property

Property Let Language_Code(AString As String)
ms_Language_Code = AString
End Property

Public Property Set ArmDb(ByRef local_connection As Object)
    If Not (local_connection Is Nothing) Then
        Set mo_Db = local_connection
    End If
End Property

Public Property Let Visible(ByVal aVisible As Boolean)
    UserControl.Extender.Visible = aVisible
End Property

Public Property Get Visible() As Boolean
    Visible = UserControl.Extender.Visible
End Property

'**********************************************************************************************************************************
'**********************************************************************************************************************************
' FRAMEWORK METHODS
' please DO NOT change anything in this part of code
'**********************************************************************************************************************************
'**********************************************************************************************************************************

Public Sub Move(ByVal aLeft As Single, ByVal aTop As Single, ByVal aWidth As Single, ByVal aHeight As Single)
On Error GoTo ErrHandler
    LockWindowUpdate UserControl.hwnd
    Call UserControl.Extender.Move(aLeft, aTop, aWidth, aHeight)
    Call Form_Resize
    LockWindowUpdate 0
    Exit Sub
ErrHandler:
    Call ErrorMessage("Move")
End Sub

Public Function Load_A_COM() As Boolean

Dim ll_Index As Long
Dim lo_Control As Object

On Error GoTo ErrHandler
    
    Load_A_COM = False
    
    If mb_Initialized Then
        Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    End If
    
    mb_InternalInit = False
    ms_DecimalSeparator = Format(0, ".")
    
    Dim sBuffer As String
    Dim nBufferLen As Long
    nBufferLen = 255
    sBuffer = String$(nBufferLen, vbNullChar)
    nBufferLen = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, sBuffer, nBufferLen)
    If nBufferLen > 0 Then
        ms_ThousandSeparator = Left$(sBuffer, nBufferLen - 1)
    End If
    
    For Each lo_Control In Controls
        Select Case UCase(TypeName(lo_Control))
        Case "ARMCOMBOBOX"
            Set lo_Control.ArmDb = mo_Db
            Call lo_Control.Load_A_COM
        Case "ARMPICKER"
            Set lo_Control.ArmDb = mo_Db
            Call lo_Control.Load_A_COM
        Case "TOOLBARCONTROL"
            lo_Control.Language = ms_Language_Code
            lo_Control.Load_A_COM
        Case "TOOLBR"
            Set lo_Control.ArmDb = mo_Db
            lo_Control.Language = ms_Language_Code
            Call lo_Control.Load_A_COM
        Case "ARMGRID"
            Set lo_Control.ArmDb = mo_Db
            Call lo_Control.Load_A_COM
        Case "ARMTREEVIEW"
            Set lo_Control.ArmDb = mo_Db
            lo_Control.Language = ms_Language_Code
            Call lo_Control.Load_A_COM
        Case "ARMCHECKVIEW"
            Set lo_Control.ArmDb = mo_Db
            Call lo_Control.Load_A_COM
        Case "A_CALOCX"
            lo_Control.Language = ms_Language_Code
            Call lo_Control.reinit_cal
        End Select
    Next
#If ENV = LIVE Then
    Set mo_Sys = CreateObject("ArmSYSCOM.ArmSys")
#Else
    Set mo_Sys = New ARMSYSCOMLib.ArmSYS
#End If

    Set mo_XMLDoc = CreateObject("MSXML2.DOMDocument")

    Call Form_Resize
    mb_Initialized = Load_A_COM_Custom
    Load_A_COM = mb_Initialized
    Exit Function
ErrHandler:
    Load_A_COM = False
    Call ErrorMessage("Load_A_COM")
End Function

Public Function Unload_A_COM() As Boolean
    
On Error GoTo ErrHandler
    
    Dim lo_Control As Object
    Dim ll_Index As Long
    
    Call UnLoad_A_COM_Custom
    
    For Each lo_Control In Controls
        Select Case UCase(TypeName(lo_Control))
        Case "ARMCOMBOBOX", "TOOLBARCONTROL", "ARMGRID", "ARMTREEVIEW", "ARMCHECKVIEW", "ARMPICKER"
            Call lo_Control.Unload_A_COM
        End Select
    Next
    
    Set mo_Db = Nothing
    Set mo_Sys = Nothing
    mb_Initialized = False
    Unload_A_COM = True
    Exit Function
ErrHandler:
    Unload_A_COM = False
    Call ErrorMessage("Unload_A_Com")
End Function

Public Sub Resize()
On Error GoTo ErrHandler
    LockWindowUpdate UserControl.hwnd
    Call Form_Resize
    LockWindowUpdate 0
    Exit Sub
ErrHandler:
    Call ErrorMessage("Resize")
End Sub

Public Function Init_control() As Boolean
Dim ll_Index As Long

On Error GoTo ErrHandler

    Init_control = False
    If Not CheckRights Then
        Exit Function
    End If
    
    Call Init_Custom
    
    Call ChangeCharset(Controls, GetCodePageFromLanguage(mo_Db, ms_Language_Code))
    Call LoadLabels(mo_Db, Me, SCREEN_NAME, ms_Language_Code)
    
    Init_control = True
    Exit Function
ErrHandler:
    Init_control = False
    Call ErrorMessage("Init_control")
End Function

Private Function CheckRights() As Boolean
Const CREQ As String = "SELECT CFG_Value FROM A_CONFIG WHERE CFG_key = 'METAL_COMP_ENABLED'"
On Error GoTo ErrHandler
    CheckRights = False
    Dim ll_Cursor As Long
    ll_Cursor = OpenSQLSafe(mo_Db, CREQ)
    Dim lsa_login() As String
    lsa_login = Split(mo_Db.GetFields(ll_Cursor, "CFG_Value"), ",", , vbTextCompare)
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    
    Dim ll_i As Long
    For ll_i = LBound(lsa_login) To UBound(lsa_login)
        If ms_LoginName Like lsa_login(ll_i) Then
            CheckRights = True
            Exit For
        End If
    Next
    Exit Function
ErrHandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    Call ErrorHandler("CheckRights")
End Function

Private Function HasContainer(ByVal lo_Control As Control, ByRef lo_Container As Object) As Boolean
    Dim ll_Index As Long
    Dim lo_Object As Object

    On Error GoTo CleanUp   'not all controls support Container property
    HasContainer = False
    While Not (lo_Control Is Nothing)
        If lo_Control.Container Is lo_Container Then
            HasContainer = True
            Exit Function
        End If
        Set lo_Control = lo_Control.Container
    Wend

CleanUp:

End Function

Private Sub ResetFrameControls(ByRef ao_Frame As Frame)
On Error GoTo ErrHandler

Dim lo_Control As Control

    mb_InternalInit = True
    For Each lo_Control In Controls
    
        If HasContainer(lo_Control, ao_Frame) Then
            Select Case UCase(TypeName(lo_Control))
                Case "ARMCOMBOBOX"
                    Call lo_Control.Clear
                    lo_Control.Tag = ""
                    lo_Control.Request = ""
                    lo_Control.Visible = False
                Case "ARMPICKER"
                    Call lo_Control.Clear
                    lo_Control.Tag = ""
                    lo_Control.Visible = False
                Case "CHECKBOX"
                    lo_Control.Value = Unchecked
                    lo_Control.Tag = ""
                    lo_Control.Caption = ""
                    lo_Control.Visible = False
                Case "TEXTBOX"
                    lo_Control.Tag = ""
                    lo_Control.Text = ""
                    lo_Control.Visible = False
                Case "A_CALOCX"
                    Call lo_Control.reinit_cal
                    lo_Control.Tag = ""
                    lo_Control.Visible = False
                Case "LABEL"
                    lo_Control.Tag = ""
                    lo_Control.Caption = ""
                    lo_Control.FontBold = False
                    lo_Control.Visible = False
            End Select
        End If
    Next
    mb_InternalInit = False
    Exit Sub
ErrHandler:
    mb_InternalInit = False
    Call ErrorHandler("ResetFrameControls")
End Sub

' ************************************************************************************
' FRAMEWORK DB-ACCESS FUNCTIONS
' please do not change this code
' ************************************************************************************

' Return the result of a SQL request
' Convert SQL runtime errors and process errors to VB Error
#If ENV = LIVE Then
Private Function OpenSQLSafe(ByVal ao_Db As Object, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#End If

On Error GoTo ErrHandler

    Dim lc_Data As Long
    lc_Data = ao_Db.OpenSQL(as_Request)
    
    If lc_Data = 0 Then
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_Db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_Db.SQLErrorMessages, SEP2)
    End If
    
    If al_RowExpectedCount <> -1 Then
        ' Then check the rowcount
        If ao_Db.RowCount(lc_Data) <> al_RowExpectedCount Then
            Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_Db.RowCount(lc_Data)
        End If
    End If

    OpenSQLSafe = lc_Data

    Exit Function

ErrHandler:

    Call ErrorHandler("OpenSQLSafe")

End Function


' Execute a SQL request returning no data
' Convert SQL runtime errors and process errors to VB Error
' Params:
' ao_Db (Object)
' as_Request (String)
' al_RowAffectedCount (String)
#If ENV = LIVE Then
Private Sub ExecuteSQLSafe(ByVal ao_Db As Object, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#End If
On Error GoTo ErrHandler

    ' First execute the request
    If Not ao_Db.ExecuteSQL(as_Request) Then
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_Db.SQLErrorCodes, SEP2) & SEP1 & Join(ao_Db.SQLErrorMessages, SEP2)
    End If

    If al_RowAffectedCount <> -1 Then
        ' Then check the rowcount
        If ao_Db.SQLRowsAffected <> al_RowAffectedCount Then
            
            If ab_DuplicityCheck Then
                Err.Raise ArmCusErr.DuplicityDetected, "SQL : " & as_Request, al_RowAffectedCount & "<>" & ao_Db.SQLRowsAffected
            Else
                Err.Raise ArmErr.SQLBadRowAffectedCount, "SQL : " & as_Request, al_RowAffectedCount & "<>" & ao_Db.SQLRowsAffected
            End If
        End If
    End If

    Exit Sub

ErrHandler:
    Call ErrorHandler("ExecuteSQLSafe")
End Sub

Private Function GetDbError(ByVal lo_Db As ARMSYSCOMLib.ArmDb) As String
On Error GoTo ErrHandler
    
    If IsArray(lo_Db.SQLErrorMessages) Then
        Debug.Assert (IsArray(mo_Db.SQLErrorCodes))
        ' Display errors msgBox
        GetDbError = Join(lo_Db.SQLErrorCodes, ",") & vbCrLf & Join(lo_Db.SQLErrorMessages, vbCrLf)
    Else
        ' ExecuteSQL failed but no error message?
        GetDbError = "Unknown error"
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetDbError()")
End Function
' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
  
    Call Err.Raise(Err.Number, as_Fct & SEP1 & Err.Source, Err.Description)
End Sub

' display standard error message
Private Sub ErrorMessage(ByVal as_Fct As String)
    Dim ls_ErrSource As String
    Dim ls_errDescription As String
    ls_ErrSource = as_Fct & SEP1 & Err.Source
    ls_errDescription = Err.Description
    
    Call LogMessage(SCREEN_NAME & " exception raised. Err.Number:" & Err.Number & ", Err.Source:" & ls_ErrSource & ", Err.Description " & ls_errDescription & ".", "E", False)
    Call MsgBox("Error occured, please contact IT. Application will now shutdown." & vbCrLf & ls_ErrSource & vbCrLf & "Description: " & ls_errDescription, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
End Sub

' logs message to database
Private Sub LogMessage(ByVal as_logMsg As String, Optional ByVal as_logType As String = "E", Optional ab_ExitOnException As Boolean = False)
    Dim ll_errNumber As Long
    Dim ls_errDescription As String, ls_ErrSource As String
    
    ll_errNumber = Err.Number
    ls_errDescription = Err.Description
    ls_ErrSource = Err.Source

On Error GoTo ErrHandler

Const LOG_REQUEST As String = "EXEC A_log_ins $UCODE$,$LOGTYPE$,$MSG$,$APP$"
    Dim ls_req As String
    Dim ll_Cursor As Long
    Dim ls_Source As String, ls_Msg As String
    
    ls_Source = SCREEN_NAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    ls_Msg = as_logMsg
    If ll_errNumber <> 0 Then
        ls_Msg = ls_Msg & SEP1 & ll_errNumber & " : " & ls_errDescription & " - " & ls_ErrSource
    End If
    
    ls_req = ReplacePlaceHolder(LOG_REQUEST, "$UCODE$", CStr(ml_U_Code))
    ls_req = ReplacePlaceHolder(ls_req, "$LOGTYPE$", SQLStr(as_logType))
    ls_req = ReplacePlaceHolder(ls_req, "$MSG$", Left(Trim(SQLStr(ls_Msg)), 4000))
    ls_req = ReplacePlaceHolder(ls_req, "$APP$", Left(Trim(SQLStr(ls_Source)), 50))
    
    Call ExecuteSQLSafe(mo_Db, ls_req)
    
    Err.Number = ll_errNumber
    Err.Description = ls_errDescription
    Err.Source = ls_ErrSource
    Exit Sub
    
ErrHandler:
    If ab_ExitOnException Then
        Call MsgBox("A fatal error occured. Unable to log error into database, the application will be close. Please report the following message to your IT support: " & vbCrLf & _
            "Number:" & Err.Number & vbCrLf & "Description:" & Err.Description, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
        End
    End If
    Err.Number = ll_errNumber
    Err.Description = ls_errDescription
    Err.Source = ls_ErrSource
End Sub

Private Function SQLStr(ByVal as_Data As String) As String
On Error GoTo ErrHandler

    SQLStr = "'" & Replace(as_Data, "'", "''") & "'"
    Exit Function
ErrHandler:
    Call ErrorHandler("SqlStr")
End Function

Private Function ReplacePlaceHolder(ByVal as_Request As String, ByVal as_PlaceHolder As String, ByVal as_DefaultValue As String) As String
On Error GoTo ErrHandler
    
    as_Request = Replace(as_Request, as_PlaceHolder, as_DefaultValue, , , vbTextCompare)
    
    ReplacePlaceHolder = as_Request
    Exit Function
ErrHandler:
    Call ErrorHandler("ReplacePlaceholder")
End Function

' procedure save/restore err object
Private Sub UpdateError(Optional ab_saveError As Boolean = False)
Static ls_ErrDesc As String
Static ls_ErrSource As String
Static ll_errnum As Long
    
    If ab_saveError Then
        ls_ErrDesc = Err.Description
        ls_ErrSource = Err.Source
        ll_errnum = Err.Number
    Else
        Err.Description = ls_ErrDesc
        Err.Source = ls_ErrSource
        Err.Number = ll_errnum
    End If
End Sub

Private Sub LockScreen(ByVal ab_lock As Boolean)

    Dim ll_errNumber As Long, ls_ErrSrc As String, ls_ErrDesc As String
    ll_errNumber = Err.Number
    ls_ErrSrc = Err.Source
    ls_ErrDesc = Err.Description

On Error GoTo ErrHandler
    Static ll_Count As Long
    Static ll_Mousepointer As Long
    Static lb_Locked As Boolean
      
      
    ll_Count = ll_Count + IIf(ab_lock, 1, -1)
    Debug.Assert (ll_Count >= 0)
    
    ' First lock
    If Not lb_Locked And ab_lock Then
        ll_Mousepointer = Screen.MousePointer
        Screen.MousePointer = vbHourglass
        UserControl.Enabled = False
        LockWindowUpdate UserControl.hwnd
        lb_Locked = True
    End If
    
    ' Unlock
    If ll_Count = 0 Then
        DoEvents ' Flush events
        LockWindowUpdate 0
        UserControl.Enabled = True
        UserControl.Refresh ' Repaint immediately
        Screen.MousePointer = ll_Mousepointer
        lb_Locked = False
    End If
    
    Err.Number = ll_errNumber
    Err.Source = ls_ErrSrc
    Err.Description = ls_ErrDesc
    Exit Sub
ErrHandler:
    Call ErrorHandler("LockScreen")
End Sub


' ************************************************************************************
' *************************** INTERNATIONAL FUNCTIONS ********************************
' ************************************************************************************

Private Function GetCodePageFromLanguage(ByRef ao_Armdb As Object, ByVal as_Language As String) As Long
On Error GoTo ErrHandler
Const C_REQ As String = "SELECT Code_Page FROM Language WHERE Language_Code = '$Language_Code$'"
    Dim ls_req As String
    Dim ll_Cursor As Long
    Dim ll_codePage As Long
    
    ls_req = ReplacePlaceHolder(C_REQ, "$Language_Code$", as_Language)

    ll_Cursor = OpenSQLSafe(ao_Armdb, ls_req)
    Debug.Assert (ll_Cursor <> 0)
    
    ll_codePage = CLng(ao_Armdb.GetFields(ll_Cursor, "Code_Page"))
    Call ao_Armdb.Close(ll_Cursor)
    GetCodePageFromLanguage = ll_codePage
    Exit Function
    
ErrHandler:
    If ll_Cursor <> 0 Then Call ao_Armdb.Close(ll_Cursor)
    Call ErrorHandler("GetCodePageFromLanguage()")
End Function

'convert code page into charset integer
Private Function GetCharSetFromCodePage(ByVal al_CodePage As Long) As Long

On Error GoTo ErrHandler

    Select Case CStr(al_CodePage)
        Case 932 ' Japanese
            GetCharSetFromCodePage = 128
        Case 936 ' Simplified Chinese
            GetCharSetFromCodePage = 134
        Case 949 ' Korean
            GetCharSetFromCodePage = 129
        Case 950 ' Traditional Chinese
            GetCharSetFromCodePage = 136
        Case 1250 ' Eastern Europe
            GetCharSetFromCodePage = 238
        Case 1251 ' Russian
            GetCharSetFromCodePage = 204
        Case 1252 ' Western European Languages
            GetCharSetFromCodePage = 0
        Case 1253 ' Greek
            GetCharSetFromCodePage = 161
        Case 1254 ' Turkish
            GetCharSetFromCodePage = 162
        Case 1255 ' Hebrew
            GetCharSetFromCodePage = 177
        Case 1256 ' Arabic
            GetCharSetFromCodePage = 178
        Case 1257 ' Baltic
            GetCharSetFromCodePage = 186
        Case Else
            GetCharSetFromCodePage = 0
    End Select
    
    Exit Function
    
ErrHandler:
    Call ErrorHandler("GetCharSetFromCodePage()")
End Function

Private Sub ChangeCharset(ByRef ao_Container As Object, Optional ByVal aCodePage As Long)

On Error GoTo ErrHandler
   
    Dim lc_Control As Control
    Dim ll_Charset As Long
    
    On Error Resume Next
    ll_Charset = GetCharSetFromCodePage(aCodePage)
    
    For Each lc_Control In ao_Container
        Select Case UCase(TypeName(lc_Control))
        Case "TABSTRIP", "TEXTBOX", "LABEL", "FRAME", "COMMANDBUTTON", _
              "LISTVIEW", "CHECKBOX", "OPTIONBUTTON", _
              "ARMCHECKVIEW", "ARMTREEVIEW", "ARMGRID", "ARMCOMBOBOX", "ARMCHECKVIEW0", "ARMPICKER"
            lc_Control.Font.Name = "Arial"
            lc_Control.Font.Charset = ll_Charset
        Case "A_SEEK", "A_SRCHTXT"
            lc_Control.Charset = ll_Charset
        End Select
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("ChangeCharset")
End Sub

' Load the labels of a containers
Private Sub LoadLabels(ByRef ao_Armdb As ArmDb, ByRef ao_Container As Object, ByVal as_ScreenName As String, ByVal as_Language As String)
Dim lo_Control As Control   ' A control of the container
Dim li_Idx As Integer, li_Count As Integer
Dim li_Label As Integer      ' A label idx
Dim ls_Request As String
Dim lc_Labels As Long
Dim lsa_ControlTag() As String
    
    On Error GoTo Trace_Err

    ls_Request = "exec screen_csts '" & as_ScreenName & "','" & as_Language & "'"
    lc_Labels = OpenSQLSafe(ao_Armdb, ls_Request)
    
    If lc_Labels = 0 Then
        Exit Sub
    End If
    
    On Error GoTo WithoutTag
    If ao_Container.Tag <> "" Then
        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", ao_Container.Tag, , 1)
        If li_Label >= 0 Then
            ao_Container.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
        End If
    End If
WithoutTag:
    
    On Error GoTo Trace_Err
    
    ' Iterate the container for loading the label of each element which has defined a tag
    For Each lo_Control In UserControl.Controls
        If HasContainer(lo_Control, ao_Container) Then
            Select Case UCase(TypeName(lo_Control))
                Case UCase("TabStrip") ' Component is a tabstrip, we load the caption of each tab defined
                    Dim lo_Tbs
                    Set lo_Tbs = lo_Control ' Cast for use of intellisense
                    li_Count = lo_Tbs.Tabs.Count
                    For li_Idx = 1 To li_Count
                        If lo_Tbs.Tabs(li_Idx).Tag <> "" Then
                            li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Tbs.Tabs(li_Idx).Tag, , 1)
                            If li_Label >= 0 Then
                                lo_Tbs.Tabs(li_Idx).Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                            End If
                        End If
                    Next
                    Set lo_Tbs = Nothing
                
                Case UCase("ListView") ' Component is a listview, we load the caption of each columns
                    Dim lo_ListView As ListView
                    Set lo_ListView = lo_Control
                    li_Count = lo_ListView.ColumnHeaders.Count
                    For li_Idx = 1 To li_Count
                        If lo_ListView.ColumnHeaders(li_Idx).Tag <> "" Then
                            li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_ListView.ColumnHeaders(li_Idx).Tag, , 1)
                            If li_Label >= 0 Then
                                lo_ListView.ColumnHeaders(li_Idx).Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                            End If
                        End If
                    Next
                    Set lo_ListView = Nothing
            
                Case UCase("TextBox")  ' Component is a textbox
                    Dim lo_TextBox As TextBox
                    Set lo_TextBox = lo_Control
                    If lo_TextBox.Tag <> "" Then
                        lsa_ControlTag = Split(lo_Control.Tag, SEP)
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lsa_ControlTag(0), , 1)
                        If li_Label >= 0 Then
                            lo_TextBox.Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                    Set lo_TextBox = Nothing
                
                Case UCase("Label"), UCase("Frame"), UCase("CommandButton"), UCase("CheckBox"), UCase("OptionButton")
                    If lo_Control.Tag <> "" Then
                        lsa_ControlTag = Split(lo_Control.Tag, SEP)
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lsa_ControlTag(0), , 1)
                        If li_Label >= 0 Then
                            lo_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Case UCase("ArmGrid")
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Control.Tag, , 1)
                    If li_Label >= 0 Then
                      Call lo_Control.LoadConstants(ptStatic, ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT"), ctColumns)
                    End If
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Control.Tag & "_Title", , 1)
                    If li_Label >= 0 Then
                      lo_Control.Title = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                Case UCase("Menu")
                    If lo_Control.Name <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Control.Name, , 1)
                        If li_Label >= 0 Then
                            lo_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
            End Select
        End If
    Next
    
    Call ao_Armdb.Close(lc_Labels)
    Exit Sub
    
Trace_Err:
    Call ao_Armdb.Close(lc_Labels)
End Sub

Function MsgText(ByVal aID As Long, ByVal aLang As String, ByVal aDefault As String, Optional ByVal aInfo As Variant) As String
On Error GoTo ErrHandler

Const DB_REQ As String = "SELECT message_text FROM error_message WHERE msgid = $id$ AND Language_code = '$lang$'"

    MsgText = ""
    
    Dim lRequest As String
    lRequest = ReplacePlaceHolder(DB_REQ, "$id$", aID)
    lRequest = ReplacePlaceHolder(lRequest, "$lang$", aLang)
    Dim lData As Long
    
    lData = OpenSQLSafe(mo_Db, lRequest)
    
    Dim lBuffer As String
    lBuffer = mo_Db.GetFields(lData, "message_text")
    mo_Db.Close (lData)
    If lBuffer = "" Then lBuffer = aDefault
    
    Dim li_Idx As Integer
    If Not IsMissing(aInfo) Then
        For li_Idx = 0 To UBound(aInfo)
            lBuffer = Replace(lBuffer, aInfo(li_Idx, 0), aInfo(li_Idx, 1), , , vbTextCompare)
        Next li_Idx
    End If
    
    
    MsgText = lBuffer
    Exit Function
ErrHandler:
    mo_Db.Close (lData)
    Call MsgBox("Connection failure accessing message information.", vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
    MsgText = aDefault
End Function


Private Sub Form_Resize()
    Dim ll_height As Long
    Dim ll_Width As Long
    ll_height = UserControl.Height
    ll_Width = UserControl.Width
    
    If ll_height < 6735 Then ll_height = 6735
    If ll_Width < 9390 Then ll_Width = 9390
    
    Call prg_progress.Move(0, ll_height - 270, ll_Width - 120)
    
    Call lbl_Status.Move(60, prg_progress.Top - lbl_Status.Height - 60)
    Call txt_Status.Move(lbl_Status.Left + lbl_Status.Width, lbl_Status.Top - 60)
    txt_Status.Width = ll_Width - txt_Status.Left - 130
    
    ll_height = ll_height - txt_Status.Height - prg_progress.Height - 60
    Call tlb_Main.Move(0, 0, ll_Width - 120)
    Call frm_Main.Move(0, tlb_Main.Top + tlb_Main.Height + 60)
    frm_Main.Width = tlb_Main.Width
    frm_Main.Height = ll_height - frm_Main.Top - 40
    
    Call grd_main.Move(60, 240, frm_Main.Width - 120, frm_Main.Height - 300)
    
End Sub

Private Function tlb_Main_CustomAction(ByVal as_Role As String, as_Language As String) As Boolean
On Error GoTo ErrHandler
    tlb_Main_CustomAction = False
    Exit Function
ErrHandler:
    Call ErrorHandler("tlb_Main_CustomAction")
End Function

Private Sub tlb_main_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Dim ll_Cursor As Long
    If Not tlb_Main.Enabled Then Exit Sub
    
    Call LockScreen(True)
    
    If Not tlb_Main_CustomAction(as_Role, as_Language) Then
        Select Case as_Role
            Case "F"
                ' Refresh grid
                If Not mo_XMLDoc.hasChildNodes Then
                    LoadASProductsSAP
                End If
                If mo_XMLDoc.hasChildNodes Then
                    ll_Cursor = LoadASProductsSIFYB
                    Call ShowDifferences(ll_Cursor, mo_XMLDoc)
                    mo_Db.Close (ll_Cursor)
                    ll_Cursor = 0
                End If
            Case "T"
                RaiseEvent quit
            Case Else
                Err.Raise ArmErr.InvalidArgument, "tlb_Main_action", "Unknown main toolbar role as_Role=" & as_Role
        End Select
    End If
    Call LockScreen(False)
    
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If

    Select Case Err.Number
    Case 202
        MsgBox MsgText(666, ms_Language_Code, "#The item you have added/updated couldn't be displayed with the current criteria set."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    Case ArmErr.SQLBadRowExpectedCount
        MsgBox MsgText(666, ms_Language_Code, "#The record you try to open has been deleted by an other user. Please refresh the grid."), vbInformation, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    Case ArmErr.SQLBadRowAffectedCount
        MsgBox MsgText(666, ms_Language_Code, "#This record has been, modified by an other.Please exit from this screen and refresh the grid."), vbInformation, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    Case Else
        Call ErrorMessage("tlb_mai_action")
    End Select
End Sub

Private Sub ProgressStatus(ByVal as_Text As String, Optional ByVal al_progressValue As Long = -1)
    Dim ll_oldHandle As Long
    ll_oldHandle = LockWindowUpdate(0)
    txt_Status.Text = as_Text
    txt_Status.Refresh
    If al_progressValue <> -1 Then prg_progress.Value = al_progressValue
    LockWindowUpdate ll_oldHandle
End Sub

Private Sub ProgressBar(ByVal al_progressValue As Long)
    Dim ll_oldHandle As Long
    ll_oldHandle = LockWindowUpdate(0)
    prg_progress.Value = al_progressValue
    LockWindowUpdate ll_oldHandle
End Sub


Private Function LoadASProductsSAP() As Boolean
On Error GoTo ErrHandler
    Dim ls_retContent   As String
    Dim ls_retHeader    As String
    Dim lo_XMLParam     As SvcXMLParam
    
    Set lo_XMLParam = New SvcXMLParam
    
    prg_progress.Max = 5
    Call ProgressStatus("Calling webservice to get SAP materials ...", 1)
    LoadASProductsSAP = False
'    If Not mo_Sys.CallWebservice(C_GETASMATERIAL_URL, C_SAP_LOGIN, C_SAP_PASSW, "", "application/x-www-form-urlencoded", "", ls_retContent, ls_retHeader) Then
    If Not mo_Sys.CallWebservice(C_GETASMATERIAL_URL, "", "", "aaa=1", "application/x-www-form-urlencoded", "", ls_retContent, ls_retHeader) Then
        Exit Function
    End If

    Call ProgressStatus("Checking response ...", 2)
    If Not lo_XMLParam.CheckHTTPResponse(ls_retHeader) Then
        Set lo_XMLParam = Nothing
         ' no 200 response
         ReDim ms_MsgInfo(0, 1)
         ms_MsgInfo(0, 0) = "$ErrorMsg$"
         ms_MsgInfo(0, 1) = "No response"
         Call MsgBox(MsgText(666, ms_Language_Code, "#SAP AS material service call failed with error: $ErrorMsg$", ms_MsgInfo))
         Exit Function
     End If
    Call ProgressStatus("Testing content ...", 3)
    If Not lo_XMLParam.TestContentType(ls_retHeader, "text/xml") Then
        Set lo_XMLParam = Nothing
        ' unexpected return type
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Unexpected content type"
        Call MsgBox(MsgText(666, ms_Language_Code, "#SAP AS material service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    Call ProgressStatus("Loading XML document ...", 4)
    Set mo_XMLDoc = CreateObject("MSXML2.DOMDocument")
    If Not mo_XMLDoc.loadXML(ls_retContent) Then
        Set lo_XMLParam = Nothing
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Error in reading XML"
        Call MsgBox(MsgText(666, ms_Language_Code, "#SAP AS material service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    Call ProgressStatus("Loading XML document ... done.", 5)
    
    Set lo_XMLParam = Nothing

    LoadASProductsSAP = True
    Exit Function
ErrHandler:
    Call ErrorHandler("LoadASProductsSAP")
End Function

Private Function LoadASProductsSIFYB() As Long
On Error GoTo ErrHandler
Const C_REQ As String = "select BI.BI_SAP_code, BID.BI_Desc, BI.BI_a_free1, BI.Z_Creation, BI.drop_date_ind from base_item BI INNER JOIN base_item_Desc BID ON BID.BI_SAP_Code=BI.BI_SAP_Code AND BID.Language_code='E' where BI.BI_a_free1 = 'X'"
    LoadASProductsSIFYB = 0
    
    Dim ll_Cursor As Long
    prg_progress.Max = 2

    Call ProgressStatus("Loading materials from SIFYB ...", 1)
    ll_Cursor = OpenSQLSafe(mo_Db, C_REQ)
    Call ProgressStatus("Loading materials from SIFYB ... done.", 2)
    
    LoadASProductsSIFYB = ll_Cursor
    Exit Function
ErrHandler:
    Call ErrorHandler("LoadASProductsSIFYB")
End Function


Private Sub ShowDifferences(ByVal al_cursor As Long, ByRef ao_XMLDoc As Object)
On Error GoTo ErrHandler
Const C_REQ As String = "select BI.BI_SAP_code, BID.BI_Desc, BI.BI_a_free1, BI.Z_Creation, BI.drop_date_ind from base_item BI INNER JOIN base_item_Desc BID ON BID.BI_SAP_Code=BI.BI_SAP_Code AND BID.Language_code='E' where BI.BI_SAP_Code IN ('$items$')"
    Dim lo_XMLItem As MSXML2.IXMLDOMNode
    
    Call grd_main.ClearGrid
    grd_main.Redraw = False

    prg_progress.Max = mo_Db.RowCount(al_cursor)
    Call ProgressStatus("Comparing from SIFYB to SAP ...", 1)
    ' 1.. itterate Sifyb AS items and check against SAP
    Call mo_Db.First(al_cursor)
    
    While Not mo_Db.EOF(al_cursor)
    
        Set lo_XMLItem = ao_XMLDoc.selectSingleNode("/MATERIALS/ROW[ZVMATL-MATNR='" & mo_Db.GetFields(al_cursor, "BI_SAP_Code") & "']/ZVMATL-MATNR")
        If lo_XMLItem Is Nothing Then
            If mo_Db.GetFields(al_cursor, "drop_date_ind") <> "Y" Then
                ' item is missing in SAP
                grd_main.AddLine (Array(mo_Db.GetFields(al_cursor, "BI_SAP_Code"), _
                                        mo_Db.GetFields(al_cursor, "BI_Desc"), _
                                        mo_Db.GetFields(al_cursor, "BI_a_free1"), _
                                        mo_Db.GetFields(al_cursor, "Z_Creation"), _
                                        "", _
                                        ""))
            End If
        End If
        
        Call mo_Db.Next(al_cursor)
        Call ProgressBar(mo_Db.Position(al_cursor))
    Wend
    
    ' 2.. itterate SAP AS items and check against Sifyb
    Dim lo_XMLParam As New SvcXMLParam
    Dim ls_SAPItems As String
    Dim ls_Material As String
    Dim ll_curRow As Long
    
    
    Set lo_XMLItem = ao_XMLDoc.selectSingleNode("/MATERIALS")
    Set lo_XMLItem = lo_XMLItem.Attributes.getNamedItem("RowCount")
    prg_progress.Max = CLng(lo_XMLItem.nodeValue) + 1
    Call ProgressStatus("Comparing from SAP to SIFYB ...", 1)
    
    Set lo_XMLItem = ao_XMLDoc.selectSingleNode("/MATERIALS/ROW")
    ll_curRow = 1
    While Not lo_XMLItem Is Nothing
        'Debug.Print (lo_XMLItem.xml)
        ls_Material = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "ZVMATL-MATNR")
        If mo_Db.Find(al_cursor, "BI_SAP_Code", ls_Material) < 0 Then
            grd_main.AddLine (Array(ls_Material, _
                                    "Missing in SIFYB!", _
                                    "", _
                                    "", _
                                    lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "MARA-EXTWG"), _
                                    lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "MARA-ERSDA")))
            ls_SAPItems = ls_SAPItems & IIf(ls_SAPItems = "", "", "','") & ls_Material
        End If
        
        Set lo_XMLItem = lo_XMLItem.nextSibling
        ll_curRow = ll_curRow + 1
        Call ProgressBar(ll_curRow)
    Wend

    ' 3. load SIFYB data for missing SAP items
    prg_progress.Max = 2
    Call ProgressStatus("Updating SAP lines with SIFYB data.", 1)
    Dim ll_Cursor As Long
    ll_Cursor = OpenSQLSafe(mo_Db, Replace(C_REQ, "$items$", ls_SAPItems))
    If mo_Db.RowCount(ll_Cursor) > 0 Then
        prg_progress.Max = mo_Db.RowCount(ll_Cursor)
        
        While Not mo_Db.EOF(ll_Cursor)
            If grd_main.SearchKey(True, mo_Db.GetFields(ll_Cursor, "BI_SAP_Code")) Then
                grd_main.SelectedLine(0, "BI_Desc") = mo_Db.GetFields(ll_Cursor, "BI_Desc")
                grd_main.SelectedLine(0, "BI_a_free1") = mo_Db.GetFields(ll_Cursor, "BI_a_free1")
                grd_main.SelectedLine(0, "Z_Creation") = mo_Db.GetFields(ll_Cursor, "Z_Creation")
            Else
                Debug.Assert (False)
            End If
            
            Call mo_Db.Next(ll_Cursor)
            Call ProgressBar(mo_Db.Position(ll_Cursor))
        Wend
    End If
    Call mo_Db.Close(ll_Cursor)
    ll_Cursor = 0
    Call ProgressStatus("done.", 0)

    grd_main.Redraw = True
    Exit Sub
ErrHandler:
    If ll_Cursor > 0 Then
        Call mo_Db.Close(ll_Cursor)
        ll_Cursor = 0
    End If
    grd_main.Redraw = True
    Call ErrorHandler("ShowDifferences")
End Sub

Private Sub LoadFromXML(ByRef ao_XMLDoc As Object)
On Error GoTo ErrHandler
    Call grd_main.ClearGrid
    
    Dim lo_XMLItem As MSXML2.IXMLDOMNode
    Dim lo_XMLParam     As New SvcXMLParam
    grd_main.Redraw = False
    ' update item prices
    Set lo_XMLItem = ao_XMLDoc.selectSingleNode("/MATERIALS/ROW")
    
    While Not lo_XMLItem Is Nothing
        'Debug.Print (lo_XMLItem.xml)
        grd_main.AddLine (Array(lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "ZVMATL-MATNR"), _
                                "", _
                                "", _
                                "", _
                                lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "MARA-EXTWG"), _
                                lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "MARA-ERSDA")))
        Set lo_XMLItem = lo_XMLItem.nextSibling
    Wend

    grd_main.Redraw = True
    Exit Sub
ErrHandler:
    grd_main.Redraw = True
    Call ErrorHandler("LoadASProductsSAP")
End Sub

