Sign in to follow this  
Followers 0
lbsl

Problem with SQLite queries bleeding into other function its local variables.

12 posts in this topic

#1 ·  Posted (edited)

Heya dear folks,

I have a strange issue with SQLite returning content of a query i did not send initially in the same function (As a matter of fact, it doesn't get send in that function at all).

I have added a sanity check to also check the column header names that SQLite fetches, so i'm sure that i am getting the correct value inside the matches that i receive.
 

Here is a small snippet from function B()

Local $OutputQuery = "SELECT OutputNo From ArticleDelivery WHERE substr(ArticleCode,1," & $ITBarcodeSize & ") = '" & StringLeft($Barcode, $ITBarcodeSize) & "' And OrderNo='" & Number($OrderNumber) & "';"

    Local $QueryResult = Query2D($QueueHandle, $OutputQuery)
    If UBound($QueryResult, 2) > 1 And UBound($QueryResult) > 1 Then
        If $QueryResult[0][0] == "OutputNo" Then
            $OutputNumber = $QueryResult[1][0] ;OutputNumber
        Else
;In rare occasions, this condition is met:
            $QueryResult = Query2D($QueueHandle, $OutputQuery)
            ConsoleWrite("SQL retrieve failure, second attempt"& @CRLF)
            If $QueryResult[0][0] == "OutputNo" Then
                $OutputNumber = $QueryResult[1][0] ;OutputNumber
            Else ;So far i never had the routine getting here.
                $QueryResult = Query2D($QueueHandle, $OutputQuery)
                ConsoleWrite("SQL retrieve failure, third attempt"& @CRLF)
                If $QueryResult[0][0] == "OutputNo" Then
                    $OutputNumber = $QueryResult[1][0] ;OutputNumber
                Else
                    ConsoleWrite("Failed to get the outputnumber:" & $OutputQuery & @CRLF)
                    ConsoleWrite($OutputNumber & @CRLF)
                    _ArrayDisplay($Parameters)
                    _ArrayDisplay($QueryResult)
                    Exit
                EndIf
            EndIf
        EndIf
    EndIf

Notice that in the output query i ask for just one value which usually never raises above 25 and on rare occasions i got a complete different value in the billions.

When i decided to make it print the result that SQLite returned (Using _ArrayDisplay), i noticed the result in the array was generated from a query that was submitted to SQLite in a complete different function. Let's call this function A()

Just a very small snippet to show the query:

;else add the status of the order into the delivery queue
            Local $LDeliveryQueue = Query2D($QueueHandle, "SELECT ArticleCode, PacksRequested, PacksDelivered, Pillsrequested,PillsDelivered, PillsInFullPack, DeliveryAttempts, OrderState FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "';")

            If UBound($LDeliveryQueue, 2) == 8 And UBound($LDeliveryQueue) > 1 Then

It may sound odd and impossible, i doubt this is an error in Autoit3 regarding variable and array scopes. The next part of this explanation may make it sound a little less weird:
Now function A, B, C etc get called by my network message interpreter that is receiving network message dialogues that run asynchronous. It scans the message for an identifier and calls the function according to the identifier it found.

What may happen is that it may receive two different messages within 3msecs from eachother and thus more or less multiple queues are send to SQlite by both function A and B. (Both function A and B do send a select query to SQLite, but the result from function A is send back to the array in function B, likely because B was quickly called after A transmitted its query). I know Sqlite is fast, but it seems to need a bare minimum of 3 milliseconds to process these queries.

Is this really a limitation of SQLite (Do i need to use sanity checks on the column names to make sure i get results from the proper query?)?

I have an idea something here is not right.  I am using 3.3.10.2 currently, I tried to see if something similar got solved in one of the newer beta's but i could not trace fixes regarding SQLite calls.
Btw:The adjusted TCP  functions got more broken than fixed in 3.3.10.2:I had to set TCPTimeout to 0 milliseconds in order to get the processflow going uninterrupted again.

The whole TCPTimeout on @error -1 is stalling my complete loop-cycle (and thus my complete application) just because of the batchload of empty buffers that my routine is constantly polling .

Edited by lbsl

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Post source of your Query2D() function ...

Also check if there is no problem with global variables rewriting, for example: $QueueHandle

Also try to use only native SQLite functions instead of your wrappers of other non-standard UDFs which can contain bugs.

EDIT:

Eliminating method is good one for such type of problems.

Try to eliminate (remove) unnecessary parts of code until problem dissapear.

In that moment you will know what you removed lastly so it was source of problem

if problem dissapeared after its removing from whole code.

EDIT2:

Small reproducing script is always the best way to get the best support ;-)

Edited by Zedna

Share this post


Link to post
Share on other sites

SQLite is an embedded SQL engine, so it doesn't have a client/server architecture.

Furthermore, SQLite extensively uses file locks to guarantee DB integrity, BUT none of the currently available remote file locking protocols can offer such guarantee over a network (whatever OS you use).

The moral is: never ever use bare SQLite to access a remote DB or expect surprises like those you describe, up to unrecoverable DB corruption.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

The Sqlite database are locally accessed on disk.
The network connection involves a connection between a server and a client (my program is running as a sort of proxy and altering messages that it captures).

To keep track of certain things, specific values in the message are stored into the database for read out by other functions as well.

The Sqlite wrappers i created are all written by myself. They don't do much outside the original handling besides the fact that i want to have its error output to a logfile and during loop cycles, i want the network buffer being polled for messages. All in the sake of preventing copy and pasting 100 times the same code snippet.

Asking to post the whole function code means a lot of data, including adding the important side functions to also make the side quest processes clear.
 

InitialiseDB()

While 1
    CycleNetworkMessages()
WEnd



Func InitialiseDB()
    _SQLite_SafeMode(True)
    GetQueuePrefix()
        ;$DBaseQueue is a local .sqlite file, it is accessed in locked mode by this app only.
        ;$ArticleDB is a local .sqlite file, this database is accessed by a GUI process as well, hence the WAL mode.
        
    $QueueHandle = OpenDb($DbaseQueue)
    Wait(30)
    $ArticlesHandle = OpenDb($ArticleDB)
    Wait(30)
    Exec($ArticlesHandle, "PRAGMA journal_mode=WAL;")

    Exec($ArticlesHandle, "PRAGMA encoding='UTF-16';")
    Exec($QueueHandle, "CREATE TABLE IF NOT EXISTS ArticleDelivery (OrderNo not null,RequesterRowa, RequesterIT,Orderstate, OrderDate,OutputNo,ArticleElement, LabelEnumeration, ArticleCode, PacksRequested, PacksDelivered Default '0', PillsRequested, PillsDelivered Default '0', PillsInFullPack, PillsInTransitPack, DeliveryAttempts Default '0', RecipeNumber, PatientCode, EmployeeCode, PatientInsuranceID, Price, NeighbourhoodCode, UNIQUE(OrderNo,ArticleCode) ON CONFLICT REPLACE);")
Exec($ArticlesHandle, "CREATE TABLE IF NOT EXISTS TableData (TableVersion, VersionDate);")
    Wait(30)

    Local $resultlist = Query($ArticlesHandle, "SELECT TableVersion FROM TableData;")

    If $resultlist[0] <= 0 Then
        Exec($ArticlesHandle, "INSERT OR REPLACE INTO TableData(TableVersion, VersionDate) VALUES ('1.2','2014-04-14');")
    EndIf

    $resultlist = Query($ArticlesHandle, "SELECT * FROM InstructionTable;")

    If $resultlist[0] <= 0 Then
        ;StdOut($resultlist[0] & "," & @error & @CRLF)
        Exec($ArticlesHandle, "CREATE TABLE IF NOT EXISTS InstructionTable (InstructionID INTEGER PRIMARY KEY,InstructionText UNIQUE );")
        Wait(30)
    EndIf


EndFunc   ;==>InitialiseDB



Func StartSQL()
    _SQLite_Startup()

    If @error Then
        MsgBox(16, "SQLite Error:" & @error, "SQLite3.dll kan niet opgestart worden!")
        Exit -1
    Else
        _SQLite_SafeMode(True)
    EndIf

    StdOut("_SQLite_LibVersion=" & _SQLite_LibVersion() & @CRLF)
EndFunc   ;==>StartSQL

Func OpenDb($DBFile)
    Local $szDrive, $szDir, $szFName, $szExt
    Local $TestPath = _PathSplit($DBFile, $szDrive, $szDir, $szFName, $szExt)

    If Not FileExists($szDrive & $szDir) Then
        Local $text = "Database folder created: [" & $szDrive & $szDir & "]"
        LogLine($text)
        DirCreate($szDrive & $szDir)
    EndIf

    Local $DBHandle = _SQLite_Open($DBFile) ; Open a permanent disk database

    If @error Then
        MsgBox(16, "SQLite Error", $szFName & $szExt & " kan niet worden geopend of gemaakt!")
        CheckError(@extended, $DBHandle, $DBFile)
        $DBHandle = -1
        ;Exit -1
    EndIf

    Return $DBHandle
EndFunc   ;==>OpenDb

Func CloseDb($DBHandle)
    _SQLite_Close($DBHandle)
EndFunc   ;==>CloseDb

Func ClearDb($DBFile)
    FileDelete($DBFile)
EndFunc   ;==>ClearDb


Func StopSQL()
    _SQLite_Shutdown()
EndFunc   ;==>StopSQL

Func Exec($DBHandle, $DBCommand)
    Local $result = _SQLite_Exec($DBHandle, $DBCommand)
    Local $RetryTimer = TimerInit()
    While @error ; Check if the Database is locked:retry (WAL mode is enabled, but somehow XP file-locking doesn't give a shit about that)
        If _SQLite_ErrCode($DBHandle) == 5 Or _SQLite_ErrCode($DBHandle) == 6 Then
            If TimerDiff($RetryTimer) > 5000 Then;Escape when retry fails within 5 seconds
                CheckError($result, $DBHandle, $DBCommand)
                ExitLoop
            EndIf
            $result = _SQLite_Exec($DBHandle, $DBCommand)
        Else
            ;   If @error Then
            CheckError($result, $DBHandle, $DBCommand)
            ;   EndIf
            ExitLoop
        EndIf
    WEnd
EndFunc   ;==>Exec

Func Query($DBHandle, $DBCommand)
    Local $hQuery, $aRow
    Dim $QueryList[1]
    $QueryList[0] = 0

    _SQLite_Query($DBHandle, $DBCommand, $hQuery) ; the query

    While _SQLite_FetchData($hQuery, $aRow) = $SQLITE_OK
        CycleNetworkMessages()
        ReDim $QueryList[UBound($QueryList) + 1]
        $QueryList[0] = UBound($QueryList) - 1
        For $x = 0 To UBound($aRow) - 1
            $QueryList[$QueryList[0]] &= $aRow[$x]
            If $x < UBound($aRow) - 1 Then
                $QueryList[$QueryList[0]] &= "\*"
            EndIf
        Next
    WEnd

    _SQLite_QueryFinalize($hQuery)
    Return $QueryList
EndFunc   ;==>Query



Func Query2D($DBHandle, $DBCommand)
    Local $iRows, $iColumns, $QueryResult
    If UBound($QueryList) > 0 Then
        ReDim $QueryList[1][1]
    Else
        Dim $QueryList[1][1]
    EndIf
    $QueryList[0][0] = 0

    $QueryResult = _SQLite_GetTable2d($DBHandle, $DBCommand, $QueryList, $iRows, $iColumns)
    CycleNetworkMessages()
    If $QueryResult = $SQLITE_OK Then
        Return $QueryList
    Else
        Dim $QueryList[1][1]
        $QueryList[0][0] = 0
        Return $QueryList
    EndIf
EndFunc   ;==>Query2D



Func CheckError($errorcode, $DBHandle, $DBCommand)
    Dim $CriticalErrors[17]
    $CriticalErrors[0] = 3 ;/* Access permission denied */
    $CriticalErrors[1] = 5 ;/* The database file is locked */
    $CriticalErrors[2] = 6 ;/* A table in the database is locked */
    $CriticalErrors[3] = 7 ;/* A malloc() failed */
    $CriticalErrors[4] = 8 ;/* Attempt to write a readonly database */
    $CriticalErrors[5] = 10 ; /* Some kind of disk I/O error occurred */
    $CriticalErrors[6] = 11 ; /* The database disk image is malformed */
    $CriticalErrors[7] = 13 ; /* Insertion failed because database is full */
    $CriticalErrors[8] = 14 ; /* Unable to open the database file */
    $CriticalErrors[9] = 15 ; /* Database lock protocol error */
    $CriticalErrors[10] = 17 ; /* The database schema changed */
    $CriticalErrors[11] = 18 ; /* Too much data for one row of a table */
    $CriticalErrors[12] = 19 ; /* Abort due to constraint violation */  Not unique etc.
    $CriticalErrors[13] = 20 ; /* Data type mismatch */
    $CriticalErrors[14] = 21 ; /* Library used incorrectly */
    $CriticalErrors[15] = 22 ; /* Uses OS features not supported on host */
    $CriticalErrors[16] = 23 ; /* Authorization denied */

    ;   Global Const $SQLITE_OK = 0 ; /* Successful result */
    ;Global Const $SQLITE_ERROR = 1 ; /* SQL error or missing database */  Table
    ;Global Const $SQLITE_INTERNAL = 2 ; /* An internal logic error in SQLite */
    ;Global Const $SQLITE_PERM = 3 ; /* Access permission denied */
    ;Global Const $SQLITE_ABORT = 4 ; /* Callback routine requested an abort */
    ;Global Const $SQLITE_BUSY = 5 ; /* The database file is locked */
    ;Global Const $SQLITE_LOCKED = 6 ; /* A table in the database is locked */
    ;Global Const $SQLITE_NOMEM = 7 ; /* A malloc() failed */
    ;Global Const $SQLITE_READONLY = 8 ; /* Attempt to write a readonly database */
    ;Global Const $SQLITE_INTERRUPT = 9 ; /* Operation terminated by sqlite_interrupt() */
    ;Global Const $SQLITE_IOERR = 10 ; /* Some kind of disk I/O error occurred */
    ;Global Const $SQLITE_CORRUPT = 11 ; /* The database disk image is malformed */
    ;Global Const $SQLITE_NOTFOUND = 12 ; /* (Internal Only) Table or record not found */
    ;Global Const $SQLITE_FULL = 13 ; /* Insertion failed because database is full */
    ;Global Const $SQLITE_CANTOPEN = 14 ; /* Unable to open the database file */
    ;Global Const $SQLITE_PROTOCOL = 15 ; /* Database lock protocol error */
    ;Global Const $SQLITE_EMPTY = 16 ; /* (Internal Only) Database table is empty */
    ;Global Const $SQLITE_SCHEMA = 17 ; /* The database schema changed */
    ;Global Const $SQLITE_TOOBIG = 18 ; /* Too much data for one row of a table */
    ;Global Const $SQLITE_CONSTRAINT = 19 ; /* Abort due to constraint violation */  Not unique etc.
    ;Global Const $SQLITE_MISMATCH = 20 ; /* Data type mismatch */
    ;Global Const $SQLITE_MISUSE = 21 ; /* Library used incorrectly */
    ;Global Const $SQLITE_NOLFS = 22 ; /* Uses OS features not supported on host */
    ;Global Const $SQLITE_AUTH = 23 ; /* Authorization denied */

    ;   For $x = 0 To UBound($CriticalErrors) -1
    If _SQLite_ErrCode($DBHandle) <> 0 Then
        Local $text = "SQL fout [" & _SQLite_ErrCode($DBHandle) & "]:" & _SQLite_ErrMsg($DBHandle) & " <- [" & $DBCommand & "]" & @CRLF
        LogLine($text)
        ;MsgBox(16,"SQL Error",$Text)
    EndIf
    ;   Next
EndFunc   ;==>CheckError




Func CycleNetworkMessages()

    ConnectSideA() ; Set side a to listen mode or connect if no socket exists.
    ConnectIT() ; Set IT side to listen mode or connect if no socket exists
    SnifSideA(0) ; Listen to Side A connection for messages
    SnifIT(0) ; Listen to IT for messages

EndFunc   ;==>CycleNetworkMessages

Func SnifSideA($close)
    If $SideAConnection == $CON_CONNECTED Then
        Local $RecvSideA = TCPRecv($ConnectedSideASocket, 2048)
        Local $neterr = @error

        If $RecvSideA <> "" Then
            If StringLeft($RecvSideA, 2) == "0x" Then
                LogLine("RcvSDA:[E]" & StringStripCR(SerializeMessage($RecvSideA, $DecodeVisual)) & @CRLF)
            Else
                LogLine("RcvSDA:[F]" & StringStripCR($RecvSideA) & @CRLF)
            EndIf

            ProcessMessage($RecvSideA, $TOITS)
            $RecvSideA = ""
        EndIf

        If $neterr > 0 Or $close Then
            LogLine("(SideA) Receive Error:" & $neterr & " on socket:" & $ConnectedSideASocket & " Socketno.:" & $RecvSideA & " Close:" & $close & @CRLF)

            If $IPSideA == "0.0.0.0" Then
                If @error Then
                    $SideAConnection = $CON_CLOSED
                EndIf
                $SideAConStat = "SideA connection:Closing port:" & $PortSideA
            Else
                $SideAConnection = $CON_CLOSED
            EndIf

            LogLine("Closing client-socket:" & $ConnectedSideASocket & @CRLF)
            TCPCloseSocket($ConnectedSideASocket)

            If $IPSideA == "0.0.0.0" Then
                LogLine("Closing return-socket:" & $SocketSideA & @CRLF)
                TCPCloseSocket($SocketSideA)
                $SocketSideA = $CON_CLOSED
                $ConnectedSideASocket = $CON_CLOSED
                $SideAConnection = $CON_CLOSED
            EndIf

        EndIf

        $RecvSideA = 0
    EndIf

    If $close Then
        $SocketSideA = $CON_CLOSED
        $SideACycle = TimerInit()
        $ConnectedSideASocket = $CON_CLOSED
        $SideAConnection = $CON_CLOSED
    EndIf

EndFunc   ;==>SnifSideA

Func SnifIT($close)
    If $ITConnection == $CON_CONNECTED Then
        Local $RecvIT = TCPRecv($ConnectedITSocket, 10000)
        Local $neterr = @error
        If $RecvIT <> "" Then

            If StringLeft($RecvIT, 2) == "0x" Then
                LogLine("RcvITS:[E]" & StringStripCR(SerializeMessage($RecvIT, $DecodeVisual)) & @CRLF)
            Else
                LogLine("RcvITS:[F]" & StringStripCR($RecvIT) & @CRLF)
            EndIf

            ProcessMessage($RecvIT, $TORWS)
            $RecvIT = ""
        EndIf

        If $neterr > 0 Or $close Then

            LogLine("(IT) Receive Error:" & $neterr & " on socket:" & $ConnectedITSocket & " Socketno.:" & $RecvIT & " Close:" & $close & @CRLF)

            If $IPIT == "0.0.0.0" Then
                Switch $neterr
                    Case 10038; An operation was attempted on something that is not a socket
                        $ITConnection = $CON_CLOSED
                        LogLine("(IT) Socket Error:Attempt to send/receive from non-socket" & @CRLF)

                    Case 10053 ;Connection reset by peer.
                        $ITConnection = $CON_CLOSED
                        LogLine("(IT) Socket Error:Connection reset by peer" & @CRLF)

                    Case 10054 ;WSAECONNABORTED (10053) Software caused connection abort.
                        $ITConnection = $CON_CLOSED
                        LogLine("(IT) Socket Error:Attempt to send/receive from non-socket" & @CRLF)

                EndSwitch

                $ITConStat = "IT-Sys connection:Closing port:" & $PortITSys
            Else
                $ITConnection = $CON_CLOSED
            EndIf

            LogLine("Closing client-socket:" & $ConnectedITSocket & @CRLF)
            TCPCloseSocket($ConnectedITSocket)

            If $IPIT == "0.0.0.0" Then
                If $ConnectedITSocket <> -1 Then
                    LogLine("Closing return-socket:" & $SocketITSys & @CRLF)
                    TCPCloseSocket($SocketITSys)
                    $ConnectedITSocket = $CON_CLOSED
                    $SocketITSys = $CON_CLOSED
                EndIf

                $ITConnection = $CON_CLOSED
            EndIf
        EndIf

        $RecvIT = 0
    EndIf

    If $close Then
        $SocketITSys = $CON_CLOSED
        $ITCycle = TimerInit()
        $ITConnection = $CON_CLOSED
        $ConnectedITSocket = $CON_CLOSED
    EndIf

EndFunc   ;==>SnifIT

Func ProcessMessage($message, $TargetSys) ;Split the message for further processing
    Local $printmessage = $message
    Local $orgmessage = $message
    Local $message_serialized = False
    Local $originalprotocol = $PROT_SYNC
    Dim $message_queue[2]
    $message_queue[0] = 0
    $Dialog_Format = $FORMAT_SideA

    ;StdOut(@CRLF& " incoming:"&$message&@CRLF)

    If StringLeft($message, 2) == "0x" Then
        $printmessage = SerializeMessage($printmessage, $DecodeVisual)
        $message = SerializeMessage($message, $Decode)
        $message = ReplaceNull($message)
        $message_serialized = True
    EndIf

    ;Try to detect which protocol is used and split multimessage lines during the process
    Switch True
        Case StringInStr($message, "~SYNC~") > 0 Or StringInStr($message, "~DATA~") > 0
            $message_queue = StringSplit($message, "~DATA~", 1)
            $originalprotocol = $PROT_SYNC

        Case StringInStr($message, Chr(3)) > 0
            $message_queue = StringSplit($message, Chr(3), 1)
            $originalprotocol = $PROT_SETX

    EndSwitch

    If $message_queue[0] = 0 Then
        ;StdOut("[m]:"&$message&@CRLF)
        $message_queue[0] = 1
        $message_queue[1] = $message
    EndIf

    For $i = 1 To $message_queue[0]
        $message = $message_queue[$i]
        $message = StringReplace($message, "~SYNC~", "")
        $message = StringReplace($message, "~DATA~", "")
        $message = StringReplace($message, Chr(3), "")
        $message = StringReplace($message, "<WaWi>", "")
        $message = StringReplace($message, "</WaWi>", "")
        $message_queue[$i] = $message
    Next

    For $i = 1 To $message_queue[0]
        Local $sendOrgmessage = True
        Local $TemplateValidation = False

        If StringStripWS($message_queue[$i], 8) <> "" Then
            $message = StringStripWS($message_queue[$i], 1)

            If StringLen($message) == 6 Then ;And $message_queue[0] < 3 Then
                $message = ""
            EndIf

            $dataonly = False

            Local $message_type = StringLeft($message, 1)
            Local $FunctionName = "Process" & $message_type
            Local $ParameterArray = ProduceParameterArray(StringMid($message, 2), $message_type)
            Call($FunctionName, $ParameterArray) 

            If @error = 0xDEAD And @extended = 0xBEEF Then
                LogLine("Function " & $FunctionName & " does not exist / wrong amount of arguments.")

                Return True ; Otherwise send the original message as received
            EndIf

    Next

    Return False

EndFunc   ;==>ProcessMessage


Func ProcessB($Parameters)
    Local $OrderNumber, $RequesterNumber, $CountryCode, $CodeType, $Barcode, $Element, $PrintStatus, $ItemTyp, $RecordQuantity, $TextRecords, $TargetSys, $MessageOffset = 0
    Local $OutputNumber
    Dim $QueryResult

    Enum $name, $select
    Dim $XsltSheetParameters[12][2]
    $XsltSheetParameters[0][$name] = "BarcodeMessage"
    $XsltSheetParameters[0][$select] = ""
    $XsltSheetParameters[1][$name] = "CurrentDateTime"
    $XsltSheetParameters[1][$select] = @MDAY & "-" & @MON & "-" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC
    $XsltSheetParameters[2][$name] = "UnitsInPackage"
    $XsltSheetParameters[2][$select] = "0"
    $XsltSheetParameters[3][$name] = "UnitsInCurrent"
    $XsltSheetParameters[3][$select] = "0"
    $XsltSheetParameters[4][$name] = "UnitsToDeliver"
    $XsltSheetParameters[4][$select] = "0"
    $XsltSheetParameters[5][$name] = "UnitsRemaining"
    $XsltSheetParameters[5][$select] = "0"
    $XsltSheetParameters[6][$name] = "UnitsPrescribed"
    $XsltSheetParameters[6][$select] = "0"
    $XsltSheetParameters[7][$name] = "UnitsShort"
    $XsltSheetParameters[7][$select] = "0"
    $XsltSheetParameters[8][$name] = "RequesterNumber"
    $XsltSheetParameters[8][$select] = $RequesterNumber
    $XsltSheetParameters[9][$name] = "QuantityCount"
    $XsltSheetParameters[9][$select] = "0"
    $XsltSheetParameters[10][$name] = "QuantityIndex"
    $XsltSheetParameters[10][$select] = "0"
    $XsltSheetParameters[11][$name] = "OutputNumber"
    $XsltSheetParameters[11][$select] = "0"



    $OrderNumber = GetMessageElement($Parameters, $FieldValue, "OrderNumber", $MessageOffset)
    $RequesterNumber = GetMessageElement($Parameters, $FieldValue, "RequesterNumber", $MessageOffset)
    $CountryCode = GetMessageElement($Parameters, $FieldValue, "Country", $MessageOffset)
    $CodeType = GetMessageElement($Parameters, $FieldValue, "Code", $MessageOffset)
    $Barcode = GetMessageElement($Parameters, $FieldValue, "BarCode", $MessageOffset)
    $Element = GetMessageElement($Parameters, $FieldValue, "Element", $MessageOffset)
    $PrintStatus = GetMessageElement($Parameters, $FieldValue, "StatusCode", $MessageOffset)
    $ItemTyp = GetMessageElement($Parameters, $FieldValue, "PackageUnits", $MessageOffset)
    $TargetSys = GetMessageElement($Parameters, $FieldValue, "TargetSys", $MessageOffset)



    Local $OutputQuery = "SELECT OutputNo From ArticleDelivery WHERE substr(ArticleCode,1," & $ITBarcodeSize & ") = '" & StringLeft($Barcode, $ITBarcodeSize) & "' And OrderNo='" & Number($OrderNumber) & "';"

    $QueryResult = Query2D($QueueHandle, $OutputQuery)
    ;Frankly the below sanity check is pretty much bull, this only happens during the logfile emulation attempt.
    ;I should simply allow a minimum of 15msecs for each message.
    If UBound($QueryResult, 2) > 1 And UBound($QueryResult) > 1 Then
        If $QueryResult[0][0] == "OutputNo" Then
            $OutputNumber = $QueryResult[1][0] ;OutputNumber
        Else
            $QueryResult = Query2D($QueueHandle, $OutputQuery)
            ConsoleWrite("SQL retrieve failure, second attempt"& @CRLF)
            If $QueryResult[0][0] == "OutputNo" Then
                $OutputNumber = $QueryResult[1][0] ;OutputNumber
            Else
                $QueryResult = Query2D($QueueHandle, $OutputQuery)
                ConsoleWrite("SQL retrieve failure, third attempt"& @CRLF)
                If $QueryResult[0][0] == "OutputNo" Then
                    $OutputNumber = $QueryResult[1][0] ;OutputNumber
                Else
                    ConsoleWrite("Failed to get the outputnumber:" & $OutputQuery & @CRLF)
                    ConsoleWrite($OutputNumber & @CRLF)
                    _ArrayDisplay($Parameters)
                    _ArrayDisplay($QueryResult)
                    Exit
                EndIf
            EndIf
        EndIf
    EndIf


    $MessageOffset = 0
    Local $PillsRequested = (Number(GetMessageElement($Parameters, $FieldValue, "DeliveryQuantity", $MessageOffset)) / 100)
    Local $PillsInFullPack = (Number(GetMessageElement($Parameters, $FieldValue, "PackageQuantity", $MessageOffset)) / 100)
    $XsltSheetParameters[6][$select] = $PillsRequested ; UnitsPrescribed

    If Number($PrintStatus) == 0 Then
        $MessageOffset = 5

        If StringLower(StringLeft($ItemTyp, 2)) <> "st" Then
            $PillsRequested = $ItemTyp
            $PillsInFullPack = $ItemTyp
        EndIf

        Local $QueueCmd = "UPDATE ArticleDelivery SET LabelEnumeration='1', PillsRequested='" & $PillsRequested & "', " & _
                "PillsInFullPack='" & $PillsInFullPack & "', " & _
                "RecipeNumber='" & GetMessageElement($Parameters, $FieldValue, "PresciptionNumber", $MessageOffset) & "', " & _
                "PatientCode='" & GetMessageElement($Parameters, $FieldValue, "PatientCode", $MessageOffset) & "', " & _
                "PatientInsuranceID='" & GetMessageElement($Parameters, $FieldValue, "IdofPatientInsurance", $MessageOffset) & "', " & _
                "EmployeeCode='" & GetMessageElement($Parameters, $FieldValue, "EmployeeCode", $MessageOffset) & "', " & _
                "Price='" & GetMessageElement($Parameters, $FieldValue, "Price", $MessageOffset) & "', " & _
                "NeighbourhoodCode='" & GetMessageElement($Parameters, $FieldValue, "NeighbourhoodCode", $MessageOffset) & "' " & _
                "WHERE OrderNo='" & Number($OrderNumber) & "' And SUBSTR(ArticleCode,1," & $ITBarcodeSize & ")='" & StringLeft($Barcode, $ITBarcodeSize) & "';"

        Exec($QueueHandle, $QueueCmd)
    EndIf

    $MessageOffset = 0
    $RecordQuantity = GetMessageElement($Parameters, $FieldValue, "Count", $MessageOffset)


    Local $requesterlist = Query($QueueHandle, "SELECT RequesterSideA FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "';")

    Dim $BTextRecords[1]

    If $requesterlist[0] > 0 Then
        $MessageOffset = 0
        $RequesterNumber = $requesterlist[1]
        SetMessageElement($Parameters, "RequesterNumber", $RequesterNumber, $MessageOffset)
    EndIf
    

    If $LMsgSendBrokenAsFull == True And StringLower(StringLeft($ItemTyp, 2)) == "st" And StringInStr($Barcode, "SideA") < 1 Then
        Local $articlecodelist = Query($QueueHandle, "SELECT PillsInTransitPack FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "' AND ArticleCode='" & StringLeft($Barcode, $ITBarcodeSize) & "';")

        If $articlecodelist[0] > 0 Then
            If Number($articlecodelist[1]) > 0 Then
                $MessageOffset = 0
                $Barcode = TrailField(StringLeft($Barcode, $ITBarcodeSize) & TrailField(Number($articlecodelist[1]), 5, $PAD_ZERO), 20, $SFX_SPACE)

                If Number($CodeType) > 0 And Number($CodeType) < 51 Then
                    $CodeType = Trailfield(Number($CodeType) + 50, 2, $PAD_ZERO)
                    SetMessageElement($Parameters, "Code", $CodeType, $MessageOffset)
                EndIf

                SetMessageElement($Parameters, "BarCode", $Barcode, $MessageOffset)
            Else ;We have a full pack to send, which also means we need to update our pillsdelivered
                Local $deliveredpills = Query($QueueHandle, "SELECT PillsDelivered FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "' AND ArticleCode='" & StringLeft($Barcode, $ITBarcodeSize) & "';")
                If UBound($deliveredpills) > 0 Then
                    Local $currentdeliveredpills = $deliveredpills[1] + $PillsInFullPack
                    Exec($QueueHandle, "UPDATE ArticleDelivery SET PillsDelivered='" & $currentdeliveredpills & "' WHERE OrderNo='" & Number($OrderNumber) & "' AND ArticleCode='" & StringLeft($Barcode, $ITBarcodeSize) & "';")
                EndIf
            EndIf
        EndIf
    EndIf

    ;Do we need to print a broken pack?

    If Number($RecordQuantity) > 0 And StringLower(StringLeft($ItemTyp, 2)) == "st" And StringInStr($Barcode, "SideA") < 1 Then
        Local $QuantityQuery = "SELECT PacksRequested, Sum(PacksDelivered) as PacksDelivered, sum(PillsDelivered) as PillsDelivered, PillsRequested, PillsInFullPack, PillsInTransitPack, OutputNo, OrderNo From ArticleDelivery WHERE substr(ArticleCode,1," & $ITBarcodeSize & ") = '" & StringLeft($Barcode, $ITBarcodeSize) & "' And OrderNo='" & Number($OrderNumber) & "';"
        Local $QueryResult = Query2D($QueueHandle, $QuantityQuery)
        Local $SendBrokenPackText = False
        Local $PillsInCurrentPack, $LPillsInFullPack, $PillsToRemove, $PillsToRemain

        If UBound($QueryResult, 2) > 1 And UBound($QueryResult) > 1 Then
            $XsltSheetParameters[9][$select] = $QueryResult[1][0] ;QuantityCount
            $XsltSheetParameters[10][$select] = $QueryResult[1][1] ;QuantityIndex
            $XsltSheetParameters[11][$select] = $QueryResult[1][6] ;OutputNumber

            If $QueryResult[1][0] == $QueryResult[1][1] Then ;PacksRequested = PacksDelivered?
                Local $TotalPillsDelivered = Number($QueryResult[1][2])
                Local $TotalPillsRequested = Number($QueryResult[1][3])
                Local $PillsInTransitPack = Number($QueryResult[1][5])

                If $TotalPillsDelivered > $TotalPillsRequested Then ;PillsDelivered > PillsRequested?
                    If StringLen(StringStripWS($Barcode, 2)) > $ITBarcodeSize Or $PillsInTransitPack > 0 Then
                        $PillsInCurrentPack = $PillsInTransitPack 
                    Else
                        $PillsInCurrentPack = $PillsInFullPack
                    EndIf
                    $PillsToRemain = ($TotalPillsDelivered - $TotalPillsRequested)
                    $PillsToRemove = $PillsInCurrentPack - $PillsToRemain
                    $SendBrokenPackText = True

                    If $PillsToRemain < 0 Then
                        StdOut("[    Complete] Order:[" & $OrderNumber & "], Article:[" & $Barcode & "], Pills in current pack[" & $PillsInCurrentPack & "] Pills subscribed [" & $TotalPillsRequested & "] Pills delivered [" & $TotalPillsDelivered & "] Pills required [" & Abs($PillsToRemain) & "]" & @CRLF)
                    Else
                        $XsltSheetParameters[2][$select] = $PillsInCurrentPack ;UnitsInPackage
                        $XsltSheetParameters[3][$select] = $PillsInCurrentPack ;UnitsInCurrent
                        $XsltSheetParameters[4][$select] = $PillsToRemove ;UnitsToDeliver
                        $XsltSheetParameters[5][$select] = $PillsToRemain ;UnitsRemaining

                        StdOut("[Overcomplete] Order:[" & $OrderNumber & "], Article:[" & $Barcode & "], Pills in current pack[" & $PillsInCurrentPack & "] Pills to remove [" & $PillsToRemove & "] Pills to remain [" & $PillsToRemain & "]" & " Pillsrequested:[" & $TotalPillsRequested & "]" & " Pillsdelivered:[" & $TotalPillsDelivered & "]" & " Pills in transitpack:[" & $PillsInTransitPack & "]" & @CRLF)
                    EndIf
                Else
                    If StringLen(StringStripWS($Barcode, 2)) > $ITBarcodeSize Or $PillsInTransitPack > 0 Then
                        $PillsInCurrentPack = $PillsInTransitPack ;-> The stringlen match mostly never occurs, the condition is placed just in case the ITSys is correcting the answer.
                    Else
                        $PillsInCurrentPack = $PillsInFullPack
                    EndIf
                    $PillsToRemain = ($TotalPillsDelivered - $TotalPillsRequested)
                    $XsltSheetParameters[2][$select] = $PillsInCurrentPack ;UnitsInPackage
                    $XsltSheetParameters[3][$select] = $PillsInCurrentPack ;UnitsInCurrent
                    $XsltSheetParameters[4][$select] = $PillsToRemove ;UnitsToDeliver
                    $XsltSheetParameters[5][$select] = $PillsToRemain ;UnitsRemaining

                    If $PillsToRemain < 0 Then
                        $SendBrokenPackText = True
                        $XsltSheetParameters[7][$select] = Abs($PillsToRemain) ;UnitsShort
                        StdOut("[  Incomplete] Order:[" & $OrderNumber & "], Article:[" & $Barcode & "], Pills in current pack[" & $PillsInCurrentPack & "] Pills subscribed [" & $TotalPillsRequested & "] Pills delivered [" & $TotalPillsDelivered & "] Pills required [" & Abs($PillsToRemain) & "]###" & @CRLF)
                    Else
                        If $QueryResult[1][5] == "" Then
                            StdOut("Order:[" & $OrderNumber & "], Article:[" & $Barcode & "], Outputnumber gets Labelmessages but is not defined in LPC!" & @CRLF)
                            $XsltSheetParameters[2][$select] = "0" ;UnitsInPackage
                            $XsltSheetParameters[3][$select] = "0" ;UnitsInCurrent
                            $XsltSheetParameters[4][$select] = "0" ;UnitsToDeliver
                            $XsltSheetParameters[5][$select] = "0" ;UnitsRemaining
                            $XsltSheetParameters[6][$select] = "0" ;UnitsPrescribed
                            $XsltSheetParameters[7][$select] = "0" ;UnitsShort

                        Else
                            StdOut("[    Complete] Order:[" & $OrderNumber & "], Article:[" & $Barcode & "], Pills in current pack[" & $PillsInCurrentPack & "] Pills subscribed [" & $TotalPillsRequested & "] Pills delivered [" & $TotalPillsDelivered & "] Pills required [" & Abs($PillsToRemain) & "]" & @CRLF)
                        EndIf
                    EndIf
                EndIf

            EndIf
        EndIf

        ReDim $BTextRecords[Number($RecordQuantity)]
        $MessageOffset = 0

        GetMessageElement($Parameters, $FieldValue, "NeighbourhoodCode", $MessageOffset)
        Local $RecordOffset = $MessageOffset

        For $x = $RecordOffset To UBound($Parameters) - 2

            If $Parameters[$x][$FieldName] == "Text" Then
                If $TransformBoundaryFields == True Then ;Correct message types 1, 2 and S for free field texts (V)
                    If StringLeft($Parameters[$x][$FieldValue], 1) == "S" Or StringLeft($Parameters[$x][$FieldValue], 1) == "s" Then
                        $Parameters[$x][$FieldValue] = "V" & StringMid($Parameters[$x][$FieldValue], 2)
                    EndIf

                    If StringLeft($Parameters[$x][$FieldValue], 1) == "1" Or StringLeft($Parameters[$x][$FieldValue], 1) == "2" Then
                        $Parameters[$x][$FieldValue] = "V" & StringMid($Parameters[$x][$FieldValue], 2)
                    EndIf

                EndIf

                $Parameters[$x][$FieldValue] = StringReplace($Parameters[$x][$FieldValue], ";", ",") ;Remove semicolons, SideAEtikettierer uses these for line splits
            EndIf

        Next


        If $instructionlist[0] > 0 Then ;Does the articlecode matches an instructionID?
            If $InstructionTarget == $InstructionToRecord Then
                If Number($instructionlist[1]) > 0 Then
                    Local $instruction = Query($ArticlesHandle, "SELECT InstructionText FROM InstructionTable WHERE InstructionID='" & Number($instructionlist[1]) & "';")

                    If $instruction[0] > 0 Then ;If yes, then generated a line for the inverted text
                        Local $CurMaxLines = $RecordQuantity
                        Local $OldBound = UBound($Parameters)

                        If $CurMaxLines < Number($LabelMaxLines) Then ;If the amount of lines are not matching maximum lines, fill it out with filler lines
                            $CurMaxLines = Number($LabelMaxLines)
                        EndIf

                        Local $RecordDifference = $CurMaxLines - $RecordQuantity

                        $MessageOffset = 0
                        SetMessageElement($Parameters, "Count", $CurMaxLines, $MessageOffset)

                        If $RecordDifference > 0 Then
                            ReDim $Parameters[UBound($Parameters) + $RecordDifference]
                            $Parameters[UBound($Parameters) - 1][$FieldName] = $Parameters[$OldBound - 1][$FieldName]
                            $Parameters[UBound($Parameters) - 1][$FieldType] = $Parameters[$OldBound - 1][$FieldType]
                            $Parameters[UBound($Parameters) - 1][$FieldSize] = $Parameters[$OldBound - 1][$FieldSize]
                            $Parameters[UBound($Parameters) - 1][$FieldValue] = $Parameters[$OldBound - 1][$FieldValue]
                            $Parameters[UBound($Parameters) - 2][$FieldName] = $Parameters[$OldBound - 2][$FieldName]
                            $Parameters[UBound($Parameters) - 2][$FieldType] = $Parameters[$OldBound - 2][$FieldType]
                            $Parameters[UBound($Parameters) - 2][$FieldSize] = $Parameters[$OldBound - 2][$FieldSize]
                            $Parameters[UBound($Parameters) - 2][$FieldValue] = $Parameters[$OldBound - 2][$FieldValue]

                            For $x = $OldBound - 1 To UBound($Parameters) - 3
                                $Parameters[$x][$FieldName] = "Text"
                                $Parameters[$x][$FieldType] = "String"
                                $Parameters[$x][$FieldSize] = "51"
                                $Parameters[$x][$FieldValue] = Trailfield("V", 51, $SFX_SPACE)
                            Next
                        EndIf

                        Local $WhiteChars = (50 - StringLen($instruction[1])) / 2
                        Local $WthChrs = ""

                        If $WhiteChars > 0 Then
                            $WthChrs = TrailField(Trailfield("V", 51, $SFX_SPACE), $WhiteChars, $TRIM_ONLY)
                        EndIf

                        $Parameters[UBound($Parameters) - 3][$FieldValue] = TrailField("V" & $WthChrs & $instruction[1], 51, $TRIM_ONLY)
                        $XsltSheetParameters[0][$select] = TrailField("V" & $WthChrs & $instruction[1], 51, $TRIM_ONLY)


                    Else
                        If Number($RecordQuantity) > Number($LabelMaxLines) Then
                            Local $CurMaxLines = $RecordQuantity
                            Local $OldBound = UBound($Parameters)

                            If $CurMaxLines < Number($LabelMaxLines) Then ;If the amount of lines are not matching maximum lines, fill it out with filler lines
                                $CurMaxLines = Number($LabelMaxLines)
                            EndIf

                            Local $RecordDifference = $CurMaxLines - $RecordQuantity

                            $MessageOffset = 0
                            SetMessageElement($Parameters, "Count", $CurMaxLines, $MessageOffset)

                            If $RecordDifference > 0 Then
                                ReDim $Parameters[UBound($Parameters) + $RecordDifference]
                                $Parameters[UBound($Parameters) - 1][$FieldName] = $Parameters[$OldBound - 1][$FieldName]
                                $Parameters[UBound($Parameters) - 1][$FieldType] = $Parameters[$OldBound - 1][$FieldType]
                                $Parameters[UBound($Parameters) - 1][$FieldSize] = $Parameters[$OldBound - 1][$FieldSize]
                                $Parameters[UBound($Parameters) - 1][$FieldValue] = $Parameters[$OldBound - 1][$FieldValue]
                                $Parameters[UBound($Parameters) - 2][$FieldName] = $Parameters[$OldBound - 2][$FieldName]
                                $Parameters[UBound($Parameters) - 2][$FieldType] = $Parameters[$OldBound - 2][$FieldType]
                                $Parameters[UBound($Parameters) - 2][$FieldSize] = $Parameters[$OldBound - 2][$FieldSize]
                                $Parameters[UBound($Parameters) - 2][$FieldValue] = $Parameters[$OldBound - 2][$FieldValue]

                                For $x = $OldBound - 1 To UBound($Parameters) - 3
                                    $Parameters[$x][$FieldName] = "Text"
                                    $Parameters[$x][$FieldType] = "String"
                                    $Parameters[$x][$FieldSize] = "51"
                                    $Parameters[$x][$FieldValue] = Trailfield("V", 51, $SFX_SPACE)
                                Next
                            EndIf

                        EndIf
                    EndIf
                Else
                    If Number($RecordQuantity) > Number($LabelMaxLines) Then
                        Local $CurMaxLines = $RecordQuantity
                        Local $OldBound = UBound($Parameters)

                        If $CurMaxLines < Number($LabelMaxLines) Then ;If the amount of lines are not matching maximum lines, fill it out with filler lines
                            $CurMaxLines = Number($LabelMaxLines)
                        EndIf

                        Local $RecordDifference = $CurMaxLines - $RecordQuantity

                        $MessageOffset = 0
                        SetMessageElement($Parameters, "Count", $CurMaxLines, $MessageOffset)

                        If $RecordDifference > 0 Then
                            ReDim $Parameters[UBound($Parameters) + $RecordDifference]
                            $Parameters[UBound($Parameters) - 1][$FieldName] = $Parameters[$OldBound - 1][$FieldName]
                            $Parameters[UBound($Parameters) - 1][$FieldType] = $Parameters[$OldBound - 1][$FieldType]
                            $Parameters[UBound($Parameters) - 1][$FieldSize] = $Parameters[$OldBound - 1][$FieldSize]
                            $Parameters[UBound($Parameters) - 1][$FieldValue] = $Parameters[$OldBound - 1][$FieldValue]
                            $Parameters[UBound($Parameters) - 2][$FieldName] = $Parameters[$OldBound - 2][$FieldName]
                            $Parameters[UBound($Parameters) - 2][$FieldType] = $Parameters[$OldBound - 2][$FieldType]
                            $Parameters[UBound($Parameters) - 2][$FieldSize] = $Parameters[$OldBound - 2][$FieldSize]
                            $Parameters[UBound($Parameters) - 2][$FieldValue] = $Parameters[$OldBound - 2][$FieldValue]

                            For $x = $OldBound - 1 To UBound($Parameters) - 3
                                $Parameters[$x][$FieldName] = "Text"
                                $Parameters[$x][$FieldType] = "String"
                                $Parameters[$x][$FieldSize] = "51"
                                $Parameters[$x][$FieldValue] = Trailfield("V", 51, $SFX_SPACE)
                            Next
                        EndIf

                    EndIf
                EndIf
            Else 
                Local $WhiteChars = (50 - StringLen($instruction[1])) / 2
                Local $WthChrs = ""

                If $WhiteChars > 0 Then
                    $WthChrs = TrailField(Trailfield("V", 51, $SFX_SPACE), $WhiteChars, $TRIM_ONLY)
                EndIf

                $XsltSheetParameters[0][$select] = TrailField("V" & $WthChrs & $instruction[1], 51, $TRIM_ONLY)
            EndIf

        Else
            If Number($RecordQuantity) > Number($LabelMaxLines) Then
                Local $CurMaxLines = $RecordQuantity
                Local $OldBound = UBound($Parameters)

                If $CurMaxLines < Number($LabelMaxLines) Then ;If the amount of lines are not matching maximum lines, fill it out with filler lines
                    $CurMaxLines = Number($LabelMaxLines)
                EndIf

                Local $RecordDifference = $CurMaxLines - $RecordQuantity

                $MessageOffset = 0
                SetMessageElement($Parameters, "Count", $CurMaxLines, $MessageOffset)

                If $RecordDifference > 0 Then
                    ReDim $Parameters[UBound($Parameters) + $RecordDifference]
                    $Parameters[UBound($Parameters) - 1][$FieldName] = $Parameters[$OldBound - 1][$FieldName]
                    $Parameters[UBound($Parameters) - 1][$FieldType] = $Parameters[$OldBound - 1][$FieldType]
                    $Parameters[UBound($Parameters) - 1][$FieldSize] = $Parameters[$OldBound - 1][$FieldSize]
                    $Parameters[UBound($Parameters) - 1][$FieldValue] = $Parameters[$OldBound - 1][$FieldValue]
                    $Parameters[UBound($Parameters) - 2][$FieldName] = $Parameters[$OldBound - 2][$FieldName]
                    $Parameters[UBound($Parameters) - 2][$FieldType] = $Parameters[$OldBound - 2][$FieldType]
                    $Parameters[UBound($Parameters) - 2][$FieldSize] = $Parameters[$OldBound - 2][$FieldSize]
                    $Parameters[UBound($Parameters) - 2][$FieldValue] = $Parameters[$OldBound - 2][$FieldValue]

                    For $x = $OldBound - 1 To UBound($Parameters) - 3
                        $Parameters[$x][$FieldName] = "Text"
                        $Parameters[$x][$FieldType] = "String"
                        $Parameters[$x][$FieldSize] = "51"
                        $Parameters[$x][$FieldValue] = Trailfield("V", 51, $SFX_SPACE)
                    Next
                    
                EndIf

            EndIf
        EndIf
    Else
        If StringLower(StringLeft($ItemTyp, 2)) == "st" Then
            StdOut("[Empty label?] Order:[" & $OrderNumber & "] -> Record quantiy < 1?!" & @CRLF)
        Else
            If Number($PrintStatus) == 1 Then
                StdOut("[IT:No label!] Order:[" & $OrderNumber & "] Status 1 returned" & @CRLF)
            Else
                StdOut("[         N/A] Order:[" & $OrderNumber & "] -> no pills:" & $ItemTyp & @CRLF)
            EndIf
        EndIf
    EndIf


    Local $articlecodelist = Query($ArticlesHandle, "SELECT ArticleCode FROM ArticleTable WHERE ArticleCode='" & $Barcode & "';")
    $MessageOffset = 0


    If $articlecodelist[0] > 0 Then ;Add barcodes from ITSystem to database record
        Exec($ArticlesHandle, "UPDATE ArticleTable SET BarCode1='" & GetMessageElement($Parameters, $FieldValue, "BarCode1", $MessageOffset) & "', BarCode2='" & GetMessageElement($Parameters, $FieldValue, "BarCode2", $MessageOffset) & "' WHERE ArticleCode='" & $Barcode & "';")
    EndIf



    If $NoPrice == True Then ;Remove price
        $MessageOffset = 0
        Local $Price = TrailField("0", 8, $PAD_ZERO)
        SetMessageElement($Parameters, "Price", $MessageOffset, $MessageOffset)
    EndIf


    $XsltSheetParameters[1][$name] = "CurrentDateTime"
    $XsltSheetParameters[1][$select] = @MDAY & "-" & @MON & "-" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC
    Local $offset = -1
    Local $XsltLayoutDefinition, $XsltLayoutDesign, $XsltDefinitionString, $XsltDesignString
    Local $resultDefenition = _FileReadToArray($XsltDefinitionTemplate, $XsltLayoutDefinition)
    $offset = -1
    Local $resultDesign = _FileReadToArray($XsltDesignTemplate, $XsltLayoutDesign)


    Local $OriginalProtocol = $ProtocolSideA
    $ProtocolSideA = $PROT_XML
    Local $BProcessingMessage = ConvertMessageToTargetFormat($Parameters, $TORWS)
    $ProtocolSideA = $OriginalProtocol
    $BProcessingMessage = StringReplace($BProcessingMessage, "<WaWi>", "")
    $BProcessingMessage = StringReplace($BProcessingMessage, "</WaWi>", "")
    $BProcessingMessage = PrettyPrintXML($BProcessingMessage, 0)

    Local $iRET = _XMLLoadXML($BProcessingMessage)


    For $x = 1 To UBound($XsltLayoutDefinition) - 1
        For $y = 0 To UBound($XsltSheetParameters) - 1
            If StringInStr($XsltLayoutDefinition[$x], "<xsl:param name=" & Chr(34) & $XsltSheetParameters[$y][$name] & Chr(34)) > 0 Then
                $XsltLayoutDefinition[$x] = "<xsl:param name=" & Chr(34) & $XsltSheetParameters[$y][$name] & Chr(34) & ">" & $XsltSheetParameters[$y][$select] & "</xsl:param>"
                ExitLoop
                CycleNetworkMessages()
            EndIf

        Next

        $XsltDefinitionString &= $XsltLayoutDefinition[$x] & @LF
        CycleNetworkMessages()
    Next

    $XsltDesignString = ""

    For $x = 1 To UBound($XsltLayoutDesign) - 1

        For $y = 0 To UBound($XsltSheetParameters) - 1
            If StringInStr($XsltLayoutDesign[$x], "<xsl:param name=" & Chr(34) & $XsltSheetParameters[$y][$name] & Chr(34)) > 0 Then
                $XsltLayoutDesign[$x] = "<xsl:param name=" & Chr(34) & $XsltSheetParameters[$y][$name] & Chr(34) & ">" & $XsltSheetParameters[$y][$select] & "</xsl:param>"
                ExitLoop
                CycleNetworkMessages()
            EndIf
        Next

        $XsltDesignString &= $XsltLayoutDesign[$x] & @LF
        CycleNetworkMessages()
    Next

    Local $result = _XMLTransform("", $XsltDefinitionString)

    If $result[0] <> 0 Then
        LogLine("Error in XML template:" & @LF & $XsltDefinitionTemplate & ": " & $result[1] & @CRLF)
        LogLine("Line: " & $result[2] & " Position: " & $result[3] & @CRLF)
        LogLine("content: " & $result[4] & @CRLF)
        LogLine("Errorposition: >>" & StringMid($result[4], Number($result[3]) - 1, 11) & "<<" & @CRLF)
    EndIf
    
    StdOut(PrettyPrintXML($objDoc.xml, 0) & @CRLF)
    $BProcessingMessage = $objDoc.xml
    Local $result = _XMLTransform("", $XsltDesignString)
    Local $PrintCommand = PrettyPrintXML($objDoc.xml, 1)

    If $result[0] <> 0 Then
        LogLine("Error in XML template:" & @LF & $XsltDesignTemplate & ": " & $result[1] & @CRLF)
        LogLine("Line: " & $result[2] & " Position: " & $result[3] & @CRLF)
        LogLine("content: " & $result[4] & @CRLF)
        LogLine("Errorposition: >>" & StringMid($result[4], Number($result[3]) - 1, 11) & "<<" & @CRLF)
    Else
        If Number($OutputNumber) > 0 And UBound($PrintCommand) > 0 And Number($PrintStatus) == 0 Then
            If UBound($PrinterTemplates) >= Number($OutputNumber) Then
                Local $result = _FileWriteFromArray($PrinterTemplates[Number($OutputNumber) - 1], $PrintCommand)

                Switch @error
                    Case 0
                        LogLine("Order [" & $OrderNumber & "] [B] Successful output to template:" & $PrinterTemplates[Number($OutputNumber) - 1] & @CRLF)

                    Case 1
                        LogLine("Order [" & $OrderNumber & "] [B] Could not open template:" & $PrinterTemplates[Number($OutputNumber) - 1] & @CRLF)

                    Case 2
                        LogLine("Order [" & $OrderNumber & "] [B] Output content is not an array for template:" & $PrinterTemplates[Number($OutputNumber) - 1] & @CRLF)

                    Case 3
                        LogLine("Order [" & $OrderNumber & "] [B] Error writing to template:" & $PrinterTemplates[Number($OutputNumber) - 1] & @CRLF)

                    Case 4
                        LogLine("Order [" & $OrderNumber & "] [B] Array dimension exceeds 2 for template:" & $PrinterTemplates[Number($OutputNumber) - 1] & @CRLF)

                EndSwitch
            Else
                LogLine("Order [" & $OrderNumber & "] [B] SQL Mismatch answer for output number or array bound exceeded (bound:" & UBound($PrinterTemplates) & "/target:" & Number($OutputNumber) - 1 & ")" & @CRLF)
            EndIf
        EndIf
    EndIf

    $Parameters = SplitXMLMessage($BProcessingMessage, $TargetSys)
    SendMessage(SerializeMessage(ConvertMessageToTargetFormat($Parameters, $TargetSys), $Encode), $TargetSys)
    Return False

EndFunc   ;==>ProcessB


Func ProcessA($Parameters)
    Local $OrderNumber, $RequesterNumber, $OutputNumber, $Status, $RecordQuantity, $Records, $TargetSys, $MessageOffset = 0
    $OrderNumber = GetMessageElement($Parameters, $FieldValue, "OrderNumber", $MessageOffset)

    $RequesterNumber = GetMessageElement($Parameters, $FieldValue, "RequesterNumber", $MessageOffset)
    $OutputNumber = GetMessageElement($Parameters, $FieldValue, "OutputNumber", $MessageOffset)
    $Status = GetMessageElement($Parameters, $FieldValue, "OrderState", $MessageOffset)
    $RecordQuantity = GetMessageElement($Parameters, $FieldValue, "Count", $MessageOffset)
    $TargetSys = $Parameters[UBound($Parameters) - 2][$FieldValue]
    Local $RecordOffset = $MessageOffset
    Dim $ArticleRecords[1]
    Dim $AttemptRecords[5][4]
    Local $SendAttempt = False
    Local $AttemptRecordQuantity = 0
    $MessageOffset = 0

    If Number(GetMessageElement($Parameters, $FieldName, "Country", $MessageOffset)) == -1 Then
        $Dialog_Format = $FORMAT_MEDIMAT 
    EndIf

    If UBound($Parameters) > 4 Then

        If Number($Status) == 4 And IsPrinterOutput($OutputNumber) Then

            For $x = 0 To 2
                For $y = 0 To 3 
                    $AttemptRecords[$x][$y] = $Parameters[$x][$y]
                Next
            Next

            $OrderNumber = $Parameters[0][$FieldValue]

            $AttemptRecords[3][$FieldName] = "Priority" 
            $AttemptRecords[3][$FieldType] = "Integer" 
            $AttemptRecords[3][$FieldSize] = "1" 
            $AttemptRecords[3][$FieldValue] = "1" 
            $AttemptRecords[4][$FieldName] = "Count"
            $AttemptRecords[4][$FieldType] = "List"
            $AttemptRecords[4][$FieldSize] = "0"
            $AttemptRecords[4][$FieldValue] = ""
            $MessageOffset = 0

            Local $LDeliveryQueue = Query2D($QueueHandle, "SELECT ArticleCode, PacksRequested, PacksDelivered, Pillsrequested,PillsDelivered, PillsInFullPack, DeliveryAttempts, OrderState FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "';")

            If UBound($LDeliveryQueue, 2) == 8 And UBound($LDeliveryQueue) > 1 Then
                For $x = 1 To UBound($LDeliveryQueue) - 1
                    If Number($LDeliveryQueue[$x][6]) < $AllowedDeliveryAttempts And Number($LDeliveryQueue[$x][7]) < 5 Then 
                        Local $LPCREQ = Number($LDeliveryQueue[$x][1]) ; Packs requested
                        Local $LPCDEL = Number($LDeliveryQueue[$x][2]) ; Packs delivered
                        Local $LPIREQ = Number($LDeliveryQueue[$x][3]) ; Pills requested
                        Local $LPIDEL = Number($LDeliveryQueue[$x][4]) ; Pills delivered
                        Local $LPIFP = Number($LDeliveryQueue[$x][5]) ; Pills in full pack
                        Local $LArticleCode = $LDeliveryQueue[$x][0] ; Article code
                        Local $PacksNotDelivered = $LPCREQ - $LPCDEL
                        Local $PillsNotDelivered = $LPIREQ - $LPIDEL

                        If $LPIFP > 0 Then 
                            If $PacksNotDelivered > 1 Then 
                                StdOut("[Machine failure during output] Order:[" & Number($OrderNumber) & "] ArticleCode:[" & TrailField($LArticleCode, 20, $SFX_SPACE) & "] Packs requested:[" & _
                                        $LPCREQ & "] Packs delivered:[" & $LPCDEL & "] Packs to re-output:[" & $PacksNotDelivered & "]" & " Attempt:" & Number($LDeliveryQueue[$x][6]) + 1 & @CRLF)
                                If $Dialog_Format == $FORMAT_SideA Then
                                    ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]

                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Country"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "3"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($WWCountry, 3, $PAD_ZERO)

                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Code"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "2"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = TrailField($WWCode, 3, $PAD_ZERO)
                                EndIf

                                $AttemptRecordQuantity += 1

                                If $PacksNotDelivered * $LPIFP == $PillsNotDelivered Then 
                                    ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode, 20, $SFX_SPACE)
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($PacksNotDelivered, 5, $PAD_ZERO)
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"
                                             
                                Else 
                                    StdOut("[Machine failure during output] Order:[" & Number($OrderNumber) & "] ArticleCode:[" & TrailField($LArticleCode, 20, $SFX_SPACE) & "] Packs requested:[" & _
                                            $LPCREQ & "] Packs delivered:[" & $LPCDEL & "] Packs to re-output:[" & $PacksNotDelivered & "]" & " Attempt:" & Number($LDeliveryQueue[$x][6]) + 1 & @CRLF)
                                    ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode, 20, $SFX_SPACE)
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($PacksNotDelivered - 1, 5, $PAD_ZERO)
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"

                                    If $Dialog_Format == $FORMAT_SideA Then
                                        ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Country"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "3"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($WWCountry, 3, $PAD_ZERO)

                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Code"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "2"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = TrailField(Number($WWCode) + 50, 3, $PAD_ZERO)

                                    EndIf

                                    ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                    $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode & TrailField(Mod($PillsNotDelivered, $LPIFP), 5, $PAD_ZERO), 20, $SFX_SPACE)
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField(1, 5, $PAD_ZERO)
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"

                                    $AttemptRecordQuantity += 2

                                EndIf

                                Exec($QueueHandle, "UPDATE ArticleDelivery SET DeliveryAttempts='" & (Number($LDeliveryQueue[$x][6]) + 1) & "' WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & $LArticleCode & "';")

                            Else
                                If $PacksNotDelivered > 0 Then 
                                    StdOut("[Machine failure during output] Order:[" & Number($OrderNumber) & "] ArticleCode:[" & TrailField($LArticleCode, 20, $SFX_SPACE) & "] Packs requested:[" & _
                                            $LPCREQ & "] Packs delivered:[" & $LPCDEL & "] Packs to re-output:[" & $PacksNotDelivered & "]" & " Attempt:" & Number($LDeliveryQueue[$x][6]) + 1 & @CRLF)

                                    If $PacksNotDelivered * $LPIFP == $PillsNotDelivered Then 
                                        If $Dialog_Format == $FORMAT_SideA Then
                                            ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Country"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "3"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($WWCountry, 3, $PAD_ZERO)

                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Code"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "2"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = TrailField($WWCode, 3, $PAD_ZERO)
                                        EndIf

                                        $AttemptRecordQuantity += 1

                                        ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode, 20, $SFX_SPACE)
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($PacksNotDelivered, 5, $PAD_ZERO)
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"

                                    Else 
                                        StdOut("[Machine failure during output] Order:[" & Number($OrderNumber) & "] ArticleCode:[" & TrailField($LArticleCode, 20, $SFX_SPACE) & "] Packs requested:[" & _
                                                $LPCREQ & "] Packs delivered:[" & $LPCDEL & "] Packs to re-output:[" & $PacksNotDelivered & "]" & " Attempt:" & Number($LDeliveryQueue[$x][6]) + 1 & @CRLF)

                                        If $Dialog_Format == $FORMAT_SideA Then
                                            ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Country"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "3"
                                            $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($WWCountry, 3, $PAD_ZERO)

                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Code"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "2"
                                            $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = TrailField(Number($WWCode) + 50, 3, $PAD_ZERO)

                                        EndIf

                                        $AttemptRecordQuantity += 1

                                        ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                        $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode & TrailField(Mod($PillsNotDelivered, $LPIFP), 5, $PAD_ZERO), 20, $SFX_SPACE)
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                        $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField(1, 5, $PAD_ZERO)
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                        $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"
                                    EndIf

                                    Exec($QueueHandle, "UPDATE ArticleDelivery SET DeliveryAttempts='" & (Number($LDeliveryQueue[$x][6]) + 1) & "' WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & $LArticleCode & "';")
                                Else
                                    Exec($QueueHandle, "UPDATE ArticleDelivery SET OrderState='" & Number($Status) & "' WHERE OrderNo='" & Number($OrderNumber) & "';")
                                EndIf


                            EndIf

                        Else
                            If $PacksNotDelivered > 0 Then 
                                StdOut("[Machine failure during output] Order:[" & Number($OrderNumber) & "] ArticleCode:[" & TrailField($LArticleCode, 20, $SFX_SPACE) & "] Packs requested:[" & _
                                        $LPCREQ & "] Packs delivered:[" & $LPCDEL & "] Packs to re-output:[" & $PacksNotDelivered & "]" & " Attempt:" & Number($LDeliveryQueue[$x][6]) + 1 & @CRLF)

                                If $Dialog_Format == $FORMAT_SideA Then
                                    ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Country"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "3"
                                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($WWCountry, 3, $PAD_ZERO)

                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Code"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "2"
                                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = TrailField($WWCode, 3, $PAD_ZERO)
                                EndIf

                                $AttemptRecordQuantity += 1

                                ReDim $AttemptRecords[UBound($AttemptRecords) + 3][4]
                                $AttemptRecords[UBound($AttemptRecords) - 3][$FieldName] = "ArticleCode"
                                $AttemptRecords[UBound($AttemptRecords) - 3][$FieldType] = "String"
                                $AttemptRecords[UBound($AttemptRecords) - 3][$FieldSize] = "20"
                                $AttemptRecords[UBound($AttemptRecords) - 3][$FieldValue] = TrailField($LArticleCode, 20, $SFX_SPACE)
                                $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "Quantity"
                                $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                                $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "5"
                                $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = TrailField($PacksNotDelivered, 5, $PAD_ZERO)
                                $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "Flag"
                                $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "Integer"
                                $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                                $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "0"

                                Exec($QueueHandle, "UPDATE ArticleDelivery SET DeliveryAttempts='" & (Number($LDeliveryQueue[$x][6]) + 1) & "' WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & $LArticleCode & "';")
                            Else
                                Exec($QueueHandle, "UPDATE ArticleDelivery SET OrderState='" & Number($Status) & "' WHERE OrderNo='" & Number($OrderNumber) & "';")
                            EndIf

                        EndIf

                    Else 
                        Exec($QueueHandle, "UPDATE ArticleDelivery SET OrderState='" & Number($Status) & "' WHERE OrderNo='" & Number($OrderNumber) & "';")
                    EndIf

                    CycleNetworkMessages()
                Next

                If $AttemptRecordQuantity > 0 Then 
                    $AttemptRecords[4][$FieldValue] = Trailfield(Number($AttemptRecordQuantity), 2, $PAD_ZERO) 

                    ReDim $AttemptRecords[UBound($AttemptRecords) + 2][4]
                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldName] = "TargetSys"
                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldType] = "Integer"
                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldSize] = "1"
                    $AttemptRecords[UBound($AttemptRecords) - 2][$FieldValue] = Number($TORWS)
                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldName] = "MessageType"
                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldType] = "String"
                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldSize] = "1"
                    $AttemptRecords[UBound($AttemptRecords) - 1][$FieldValue] = "A"
                    SendMessage(ConvertMessageToTargetFormat($AttemptRecords, $TORWS), $TORWS)
                EndIf

            Else
                Exec($QueueHandle, "UPDATE ArticleDelivery SET OrderState='" & Number($Status) & "' WHERE OrderNo='" & Number($OrderNumber) & "';")
            EndIf

        Else
            Exec($QueueHandle, "UPDATE ArticleDelivery SET OrderState='" & Number($Status) & "' WHERE OrderNo='" & Number($OrderNumber) & "';")
        EndIf

        If Number($RecordQuantity) > 0 Then
            Local $ArticleID = 0
            Dim $ArticleArray[$RecordQuantity][2]

            For $x = $RecordOffset To UBound($Parameters) - 3
                Local $RCountry = "000"
                Local $RType = "00"
                Local $RArticleCode = ""
                Local $RArticleCount = "00000"

                If IsPrinterOutput($OutputNumber) And Number($Status) == 1 Then
                    $MessageOffset = $x
                    $RArticleCode = GetMessageElement($Parameters, $FieldValue, "BarCode", $MessageOffset)
                    $RArticleCount = GetMessageElement($Parameters, $FieldValue, "Quantity", $MessageOffset)
                    $x = $MessageOffset

                    If $RArticleCode <> -1 Then
                        Local $FoundArticle = False
                        Local $APackCount = 0

                        For $y = 0 To UBound($ArticleArray) - 1
                            If $ArticleArray[$y][0] == StringLeft($RArticleCode, $ITBarcodeSize) Then
                                $ArticleArray[$y][1] += Number($RArticleCount)
                                $FoundArticle = True
                                $APackCount = Number($ArticleArray[$y][1])

                                ExitLoop
                            EndIf

                            CycleNetworkMessages()
                        Next

                        If Not $FoundArticle Then
                            For $y = 0 To UBound($ArticleArray) - 1
                                If $ArticleArray[$y][0] == "" Then
                                    $ArticleArray[$y][0] = StringLeft($RArticleCode, $ITBarcodeSize)
                                    $ArticleArray[$y][1] += Number($RArticleCount)
                                    $APackCount = Number($ArticleArray[$y][1])

                                    ExitLoop
                                EndIf

                                CycleNetworkMessages()
                            Next
                        EndIf

                        Local $LDeliveryQueue = Query2D($QueueHandle, "SELECT PacksRequested FROM ArticleDelivery WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & StringLeft($RArticleCode, $ITBarcodeSize) & "';")
                        If UBound($LDeliveryQueue, 2) > 1 And UBound($LDeliveryQueue) > 1 Then
                            Local $PackRequestCount = Number($LDeliveryQueue[1][0])
                            If Number($APackCount) > Number($PackRequestCount) Then
                                $PackRequestCount = $APackCount
                            EndIf

                            Exec($QueueHandle, "UPDATE ArticleDelivery SET PacksRequested='" & Number($PackRequestCount) & "' WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & StringLeft($RArticleCode, $ITBarcodeSize) & "';")
                            Wait(10)
                        Else
                            Exec($QueueHandle, "UPDATE ArticleDelivery SET PacksRequested='1' WHERE OrderNo='" & Number($OrderNumber) & "' And ArticleCode='" & StringLeft($RArticleCode, $ITBarcodeSize) & "';")
                            Wait(10)
                        EndIf
                    EndIf
                EndIf

                CycleNetworkMessages()

            Next

        Else
            StdOut("Record quantity in A msg 0? ->" & $OrderNumber & @CRLF)
        EndIf

    EndIf

    If $RequesterNumber <> $WWSRequester Then
        SendMessage(ConvertMessageToTargetFormat($Parameters, $TargetSys), $TargetSys)
    EndIf

    Return False

EndFunc   ;==>ProcessA

Share this post


Link to post
Share on other sites

I will try to see if i can create some small snippet that can reproduce the problem.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Quick observation...your are 'dim' an array in one of your functions.

If there is already a global variable of the array, the 'dim' ovewrites it...

example:

#include <Array.au3>
Local $array[2]
Test()
_ArrayDisplay($array)
Func Test()
    Dim $array[5]
EndFunc

the output will be a Ubound 5 array, not 2...do this to fix that

#include <Array.au3>
Local $array[2]
Test()
_ArrayDisplay($array)
Func Test()
    Local $array[5]
EndFunc

your code (one of many):

Func Query($DBHandle, $DBCommand)
    Local $hQuery, $aRow
;modify this to Local
    Dim $QueryList[1]
    $QueryList[0] = 0
Edited by jdelaney

IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.

Share this post


Link to post
Share on other sites

A lot of code. That test script might be a good idea. I see no Global variables. So I doubt Dim could interfere with a Global variable as all code is contained in UDFs with no Global declarations that I can see.

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Even if not global, if one function calls another, the called function will still override the 'global' from the context of it (aka, the caller).

I didn't over-analyze the script, but it's still bad practice.

Edited by jdelaney

IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.

Share this post


Link to post
Share on other sites

jdelaney, I guess you are referencing me. I require some proof of what you claim. Have you got something to show about this rather then stating the rather vague 2 words used of "bad practice" to try to help lever your opinion. Mind you, where did this "over-analyze" come from?

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

I merely pointed out a bad practice.  You can easily mess yourself up with the lack of a well placed 'local'...such as in his code above, I've already provided an example of it.

And Global is relative.  Sure, he never declared anything as global, but that means little when he uses the same variable name in multiple functions.

I'd suggested using ByRef, or returning the arrays of similar name, so you know they will be overwritten by those functions below it.  Seems more like spaghetti to me, to have a variable overwrite another from inside another function...which will happen, without use of 'local'...not to mention, as the script grows, it will become a debug nightmare.

My lack of over analysis was in regards to his script.  Merely pointed out what I considered a flaw.

Edited by jdelaney

IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.

Share this post


Link to post
Share on other sites

...Asking to post the whole function code means a lot of data, including adding the important side functions to also make the side quest processes clear...

Looking through this and I notice that it is not complete code as some variables are not declared before use.

I notice you seem to not be doing bundled sql transactions. Looping with sql commands would be constantly opening and closing file locks without transactions. This may help take some load off and help with synchronization with larger updates and less frequent access to the database. You can still do queries while a transaction is open and get updated data back. This could be worth looking into.

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

 

Quick observation...your are 'dim' an array in one of your functions.

If there is already a global variable of the array, the 'dim' ovewrites it...

example:

#include <Array.au3>
Local $array[2]
Test()
_ArrayDisplay($array)
Func Test()
    Dim $array[5]
EndFunc

the output will be a Ubound 5 array, not 2...do this to fix that

#include <Array.au3>
Local $array[2]
Test()
_ArrayDisplay($array)
Func Test()
    Local $array[5]
EndFunc

your code (one of many):

Func Query($DBHandle, $DBCommand)
    Local $hQuery, $aRow
;modify this to Local
    Dim $QueryList[1]
    $QueryList[0] = 0

Hi JDelaney, that was quite a good perception indeed. The QueryList is a global array, i should indeed have redimmed that one.

I rather use as less global variables as possible, but in certain cases i can't use garbage collectors cleaning up stuff that should not be cleaned up yet.

 

@MHZ, yes it is not complete, i have over 20 modulary source files that form the whole program from which i pulled code from that i considered necessary to add into the picture. I already attempted to strip a lot of stuff that was not relevant but i should really post a test snippet. So far, i could not regenerated the issue with my current code-state, i discovered some other issues in my code that had to be resolved. Let's hope i unawarely also fixed this issue along with it even though i don't see any particular relationship between my fixes and the issue i posted here. I am still keeping an eye on it and i also will try if i can reproduce on that smaller scale test-code if i get the time to do it.

Edited by lbsl

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0