Jump to content

Global Variable undefined.


Recommended Posts

I am often having this problem with the scope of global variables. My set of test cases contain code that spans across probably 15 .au3 files. Is this ok to do? I believe it is causing problems. I mean. If somewhere in my code I setup a Global variable. Shouldn't I be able to access that global variable anywhere my code? I mean, it wouldn't be getting from script to script if they weren't all connected via include to include. I have had this same problem numerous times and I'm not sure why. I can't just be including every file inside of every other file, because then I get that "Function already defined error". So I'm not sure how to correct this. I really need to use this variable for some code later one. And if I tried to pass it, I'd have to pass it along through probably 8 functions that don't need it. Any ideas?

Thanks,

Programit

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

I am often having this problem with the scope of global variables. My set of test cases contain code that spans across probably 15 .au3 files. Is this ok to do? I believe it is causing problems. I mean. If somewhere in my code I setup a Global variable. Shouldn't I be able to access that global variable anywhere my code? I mean, it wouldn't be getting from script to script if they weren't all connected via include to include. I have had this same problem numerous times and I'm not sure why. I can't just be including every file inside of every other file, because then I get that "Function already defined error". So I'm not sure how to correct this. I really need to use this variable for some code later one. And if I tried to pass it, I'd have to pass it along through probably 8 functions that don't need it. Any ideas?

Thanks,

Programit

put up a sample of one of those test cases so we can see what is going on.

[u]You can download my projects at:[/u] Pulsar Software
Link to comment
Share on other sites

Hi!

Something to remember is that the #include directive only performs a copy paste operation before execution of the script.

So for example if we have these include files:

something.au3

Func blabla()
EndFunc
Global $testvar

another.au3

MsgBox(0,"",$testvar)

If you then include them in a master script file like this:

#include <anything.au3>
#include <something.au3>

The code that reaches the autoit engine is this:

MsgBox(0,"",$testvar)
Func blabla()
EndFunc
Global $testvar

As you can see there are obvious errors in the code.

Generally you shouldn't get these kinds of problems, because you should always try to get your includes to be as much stand-alone as possible, and if you really need to use other includes, use include in that header and make sure the header you're including as #include-once, that way you will know for sure that the include has been included at run time.

However making 2 includes Dependant on eachother will never work.

Try for example making these to includes work:

1.au3

Global $1
MsgBox(0,"",$2)

2.au3

Global $2
MsgBox(0,"",$1)

:mellow:

Broken link? PM me and I'll send you the file!

Link to comment
Share on other sites

I didn't want to have to post ALL of the code but here you go. Its not going to be pretty going through it though..

Ok. It starts in UI. Then moves to TestCaseMain. Then Test case main includes the SaveCompanyConfig(). Which gets called in the ProcessShipmentDataFile. Then later on in the ProcessShipmentDataFile I call GetCaclulatedSOP10200(). Which has a line in it that says:

MsgBox(1,"Use for item fulfillment", $UseForItemFulfill)

And then it pops up and says that $UseForItemFulfill is undefined. This is an example to something I run into often and am unsure of on how to fix.

Here is where my application starts:

UI.au3

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GuiButton.au3>
#include <GuiEdit.au3>
#include <GUIConstantsEx.au3>
#include <GuiTreeView.au3>
#include <GuiImageList.au3>
#include <ListBoxConstants.au3>
#include <ProgressConstants.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
;~ #include "GeneralFunctions.au3"
#include "TestCaseMain.au3"

Global $currentprogress
Global $totalProgress
Global $hItem[20]
Global $NumOfTests = 0;Keeps track of the # of test selected. Used in calculating total Progress. 

_Main()

Func _Main()
    Local $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS, $TVS_CHECKBOXES)
    
;Build array of tests to be used to create X amount of check boxes
    $query = "SELECT * FROM AutoQA.dbo.TestCases"
    GetDBRow($query,"AutoQA")

    Opt("GUIOnEventMode", 1)
    #Region ### START Koda GUI section ### Form=C:\Documents and Settings\xxxxxxxxxx\Main.kxf
    $Form1 = GUICreate("Form1", 633, 447, 190, 124)
    GUISetOnEvent($GUI_EVENT_CLOSE, "Form1Close")
    GUISetOnEvent($GUI_EVENT_MINIMIZE, "Form1Minimize")
    GUISetOnEvent($GUI_EVENT_MAXIMIZE, "Form1Maximize")
    GUISetOnEvent($GUI_EVENT_RESTORE, "Form1Restore")
    Global $Log = GUICtrlCreateEdit("", 16, 208, 601, 209) 
    $Label1 = GUICtrlCreateLabel("Test Cases:", 16, 8, 60, 17)
    Global $Pause = GUICtrlCreateButton("Pause", 408, 144, 75, 25, 0)
    GUICtrlSetOnEvent(-1, "PauseClick")
    $Start = GUICtrlCreateButton("Start", 512, 144, 75, 25, 0)
    GUICtrlSetOnEvent(-1, "StartClick")
    $Current = GUICtrlCreateLabel("Current Progress", 408, 48, 82, 17)
    $Total = GUICtrlCreateLabel("Total Progress", 408, 96, 72, 17)
    $currentprogress = GUICtrlCreateProgress(408, 64, 198, 17)
    $totalProgress = GUICtrlCreateProgress(408, 112, 198, 17)
    $CurrentTest = GUICtrlCreateLabel("Current Test", 408, 24, 180, 17)
    Global $TreeView1 = GUICtrlCreateTreeView(16, 24, 369, 161,$iStyle, $WS_EX_CLIENTEDGE)
    _GUICtrlTreeView_BeginUpdate($TreeView1)
    $end = 0
    $i = 1
    
    While $end = 0
        $testCase = $getDBRow[$i][1]
        If $getDBRow[$i][0] == "END" Then ExitLoop
        $hItem[$i] = GUICtrlCreateTreeViewItem(StringFormat($testCase), $TreeView1)
        $i = $i + 1;Increment Array Counter
    WEnd
    _GUICtrlTreeView_EndUpdate($TreeView1)
    
    $MenuItem1 = GUICtrlCreateMenu("&File")
    $MenuItem2 = GUICtrlCreateMenuItem("Exit", $MenuItem1)
    GUICtrlSetOnEvent(-1, "ExitClick")
    GUISetState(@SW_SHOW)
    Dim $Form1_AccelTable[1][2] = [["x", $MenuItem2]]
    GUISetAccelerators($Form1_AccelTable)
    #EndRegion ### END Koda GUI section ###
 
    While 1
        Sleep(100)
    WEnd

EndFunc  ;==>_Main

;************FUNCTIONS********************;
Func ExitClick();File > Exit
    Exit
EndFunc
Func Form1Close();When form is closed via red X or top left menu. 
    Exit
EndFunc
Func Form1Maximize();Runs when form is maximized
EndFunc
Func Form1Minimize();Runs when form is maximized
EndFunc
Func Form1Restore();Runs when form is restored or opened
EndFunc
Func PauseClick()
;~  MsgBox(1,"","PauseClick")
    
    $PauseText = _GUICtrlButton_GetText($Pause)
;~  MsgBox(1,"","Pause Text = " & $PauseText)
    If $PauseText = "Pause" Then
    _GUICtrlButton_SetText($Pause,"Resume") 
    $TempText = _GUICtrlButton_GetText($Pause)
    While($TempText == "Resume")
        sleep(100)
        $ButtonState = _GUICtrlButton_GetState($Pause)
        ConsoleWrite("Button State: " & $ButtonState & @CRLF)
        If $ButtonState == '620' Then ExitLoop
    WEnd
    
    Else
    _GUICtrlButton_SetText($Pause,"Pause")
    EndIf
EndFunc
Func StartClick()
;~  MsgBox(1,"","Start button Clicked")
    $NumOfTests = 0
;********* BEGIN SETTING dbo.TestCases ****************
    For $x = 1 To UBound($hItem) - 1
;~      $hItem[$x] = GUICtrlCreateTreeViewItem(StringFormat("[%02d] New Item", $x + 1), $hTreeView)
        If $hItem[$x] == "" Then ExitLoop
        $checked = _GUICtrlTreeView_GetChecked($TreeView1, $hItem[$x])
;~      MsgBox(1,"",$getDBRow[$x][1] & " is set to " & $checked)
        If $checked Then
        $query = "UPDATE AutoQA.dbo.TestCases SET Active = 1 WHERE TestCaseName = '" & $getDBRow[$x][1] & "'"
        $NumOfTests = $NumOfTests + 1
        Else
        $query = "UPDATE AutoQA.dbo.TestCases SET Active = 0 WHERE TestCaseName = '" & $getDBRow[$x][1] & "'"
        EndIf
        ExecuteQuery_NonQuery($query,"AutoQA")
    Next
;********* END SETTING dbo.TestCases ****************
    MsgBox(1,"Number of Items checked", $NumOfTests)
    BeginTests();RUN MAIN
EndFunc
Func AppendLog($tempstring);Add data to the Log Txt area box.
    _GUICtrlEdit_AppendText($Log, @CRLF & $tempstring)  
EndFunc
Func TotalClick()
    MsgBox(1,"","TotalClick")
EndFunc

TestCaseMain.au3

#Include "..\..\Script Library\ShipmentFunctions.au3"
Opt("WinWaitDelay", 1) 

Global $NumCompleted = 0
Global $CurrentPercentage = 0

Func BeginTests()
    Global $TraceFlag = 2
    Global $FailedCaseCount = 0
    Global $PassedCaseCount = 0;$Result = Login('sa', 'sa')
    $CurrentTestCaseName = "Main"
    execute()
    Login("sa", "sa")

;----BEGIN Looping through active test cases--------;
    $Query = "SELECT * FROM TestCases WHERE Active = 1"
    If ($TraceFlag >= 1) Then WriteLine("TestCaseMain - " & $Query)

    _SQLConnect ($QADatabaseName)
    $oRS3 = ObjCreate("ADODB.Recordset")
    $oRS3.open($Query ,$adCN,$adOpenStatic,$adLockOptimistic,$adCmdText)
    While (NOT $oRS3.EOF);Loop through rows in table till we hit the end.
        If ($TraceFlag >= 1) Then Writeline($oRS3.Fields("TestCaseName").Value & " " & $oRS3.Fields("FileName").Value )
        $WorkingDir = @ScriptDir 
        
        $FileName = $oRS3.Fields("FileName").Value
    ;$DataFile = $oRS3.Fields("TestData").Value
        $Parameters = $oRS3.Fields("Parameters").Value
        $subDir = ""
        $index = StringInStr($FileName , "\")
        If ($index > 0) Then
            $subDir = "\" & StringLeft($FileName, $index)
            $FileName = StringRight($FileName, StringLen($FileName) - $index)       
        EndIf   
        
        $CurrentPercentage = 50
        GUICtrlSetData($currentprogress,$CurrentPercentage)
        
        
    ;$Parameters = " DataFile=" & $DataFile & " $TraceFlag=" & $TraceFlag
        $ExitCode = ShellExecuteWait("C:\Program Files\AutoIt3\autoit3.exe", $FileName & " " & $Parameters, @ScriptDir & $subDir) 
        $NumCompleted = $NumCompleted + 1
        If ($ExitCode > 0) Then 
            If ($TraceFlag >= 1) Then WriteLine("TestCase: " & $FileName & " FAILED!")
            _GUICtrlEdit_AppendText($Log, @CRLF & "Test Case: " & $FileName & " FAILED!")
            $FailedCaseCount = $FailedCaseCount + 1
        Else
            If ($TraceFlag >= 1) Then WriteLine("TestCase: " & $FileName & " PASSED!")
            _GUICtrlEdit_AppendText($Log, @CRLF & "Test Case: " & $FileName & " PASSED!")
            $PassedCaseCount = $PassedCaseCount + 1
        EndIf
;~      $PercentageCompleted = ($NumCompleted / $NumOfTests) * 100;Calculate Percentage Completed
        $PercentageCompleted = (($NumCompleted / $NumOfTests) * 100) + ($CurrentPercentage * (1 / $NumOfTests))
        GUICtrlSetData($totalProgress,$PercentageCompleted)
        $CurrentPercentage = 0
        GUICtrlSetData($currentprogress,$CurrentPercentage)
        $oRS3.MoveNext
    WEnd
    
    $NumCompleted = 0
    $CurrentPercentage = 0
    $PercentageCompleted = 0
    
    CloseApplication()
    If ($TraceFlag >= 1) Then WriteLine("Test Case Main Results" & $CRLF & "Passed: " & $PassedCaseCount & " Failed: " & $FailedCaseCount)
    MsgBox(0, "Results", "Test Case Main Results" & $CRLF & "Passed: " & $PassedCaseCount & " Failed: " & $FailedCaseCount)
;~  _SQLClose();Commented out temporarily!!!!!TEST TEST TEST TEST
EndFunc

ShipmentFunctions

#Include <GuiListBox.au3>
#Include <GuiComboBox.au3>
#Include "ProcessShipmentDataFile.au3"
#Include "GridFunctions.au3"
#Include "GeneralFunctions.au3"
;----------------------------------------------------------------------------------------------
;*********************** GLOBAL VARIABLES *************************************
Global $DefaultCarrier
Global $NonERPCustDest = ""
Global $ReturnedGridMessage = ""
Global $TraceFlag = 1
Global $hwndOrderGrid = 0;Gets set by calling InitGridMessaging method
Global $hwndPackGrid = 0 ;Gets set by calling InitGridMessaging method
;************************ GLOBAL CONSTANTS ************************************


Global Const $BeginShipmentScreenText = "Select Master Container or Container to continue."
Global Const $StartShipmentScreenText = "Select New Shipment to begin shipping process."
Global Const $AfterContainerShipmentScreenText = "Container Detail"
Global Const $Shipment_FunctionMenu =  "Function"
Global Const $ShipmentFunctionMenu_NewContainer = "New Container"
Global Const $ShipmentFunctionMenu_NewMaster = "New Master"
Global Const $ShipmentFunctionMenu_NewInner = "New Inner"
Global Const $ShipmentFunctionMenu_NewOrder = "New Order"

;~ Global Const $Shipment_PackGrid = "[CLASSNN:WindowsForms10.window.8.app.0.202c66613]";original
;~ Global Const $Shipment_PackGrid = "[CLASSNN:WindowsForms10.window.8.app.0.202c6668]";Try 2
Global Const $Shipment_PackGrid = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6661]"


Global Const $Shipment_TreeView = "[CLASSNN:WindowsForms10.window.8.app.0.202c6668]"
Global Const $Shipment_OrderGrid ="[CLASSNN:WindowsForms10.window.8.app.0.202c6669]"

Global Const $ShipmentOption_Title = "Shipment Options"
Global Const $ShipmentOption_OkBtn = "[CLASSNN:WindowsForms10.window.8.app.0.202c6662]"
Global Const $ShipmentOption_CancelBtn = "[CLASSNN:WindowsForms10.window.8.app.0.202c6661]"
Global Const $ShipmentOption_ShipMethodCB= "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6661]"

Global Const $InvalidShipMethodWarn_OkBtn = "[CLASSNN:Button1]"
Global Const $InvalidShipMethodWarn_Title ="Invalid Shipping Method"

Global Const $SavePrompt_Title = "Confirm..."
Global Const $SavePrompt_Text = "By continuing this action, the   shipment will not be saved.  Do you wish to continue?";"Do you want to save this shipment?"
Global Const $SavePrompt_YesBtn = "[CLASSNN:Button1]"
Global Const $SavePrompt_NoBtn = "[CLASSNN:Button2]"

Global Const $WeightDlg_Title = "Enter Weight"
Global Const $WeightDlg_Text = "Enter Weight of Current Container"
Global Const $WeightDlg_CalcdTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6661]"

Global Const $RateShopDlg_Title = "Rate Shopping Selection"
Global Const $RateShopDlg_Grid = "[CLASSNN:WindowsForms10.window.8.app.0.202c6661]"
Global Const $RateShopDlg_btnOK = "[CLASSNN:WindowsForms10.window.8.app.0.202c6663]"
Global Const $RateShopDlg_btnCancel = "[CLASSNN:WindowsForms10.window.8.app.0.202c6662]"

Global Const $ThresholdWarnDlg_Title = "Threshold Exceeded"

Global Const $VerifyOptionchangedPrompt_Title = "Option Changes"
Global Const $VerifyOptionchangedPrompt_YesBtn = "[CLASSNN:Button1]"

Global Const $NonERPSelectDestinationPrompt_Title = "Select Destination"
Global Const $NonERPSelectDestinationPrompt_DestCombo = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6661]"
Global Const $NonERPSelectDestinationprompt_OkBtn = "[CLASSNN:WindowsForms10.window.8.app.0.202c6662]"

Global Const $ShipmentDestinationPrompt_Title = "Shipment Destination"
Global Const $ShipmentDestinationPrompt_SingleBtn =  "[CLASS:WindowsForms10.window.8.app.0.202c666; INSTANCE:1]" 
Global Const $ShipmentDestinationPrompt_MasterBtn =  "[CLASSNN:WindowsForms10.window.8.app.0.b7ab7b2]"

Global Const $SLBQuantityDlg_Title = "Serial/Lot/Bin Information - Item Number:"
Global Const $SLBQuantityDlg_CancelBtn = "[CLASS:WindowsForms10.window.8.app.0.202c666; INSTANCE:1]"

Global Const $ReportMissingPrompt_Title = "Report File Missing"
Global Const $ReportMissingPrompt_OkBtn = "[CLASSNN:Button1]"

Global Const $EnterDocumentNumberDlg_Title = "Begin Shipment"
Global Const $EnterDocumentNumberDlg_Textbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6661]"
Global Const $EnterDocumentNumberDlg_btnOK  =  "[CLASSNN:WindowsForms10.window.8.app.0.202c6662]" 
Global Const $EnterDocumentNumberDlg_btnCancel =  "[CLASSNN:WindowsForms10.window.8.app.0.202c6661]"

Global Const $ShipmentSearch_Title = "Shipment Search List"
Global Const $ShipmentSearch_InquiryMenuOption = "Shipment Search List"
Global Const $ShipmentSearch_SearchModeButton = "[CLASSNN:WindowsForms10.window.8.app.0.202c66616]"
Global Const $ShipmentSearch_ResultGrid = "[CLASSNN:WindowsForms10.window.8.app.0.202c66619]"
Global Const $ShipmentSearch_ShipmentNumberTextbox= "[CLASSNN:WindowsForms10.EDIT.app.0.202c66616]"

Global Const $SelectDestination_Title = "Select Destination"
Global Const $SelectDestination_CustomerCombo = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6661]"
Global Const $SelectDestination_OkBtn = "[CLASSNN:WindowsForms10.window.8.app.0.202c6662]"

Global Const $RecallValidationCorrectionsDlg_Title = "Recall Validation Corrections"

Global Const $MissingPrinterDlg_Title = "Error"
Global Const $MissingPrinterDlg_Text = "Printer has not been selected.  Please select a printer to print labels."
Global Const $MissingPrinterDlg_btnOK = "[CLASSNN:Button1]"

Global Const $ItemDetailDlg_Class = "[CLASS:WindowsForms10.window.8.app.0.202c666]"
Global Const $ItemDetailDlg_SedUomSedCombo = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6663]"
Global Const $ItemDetailDlg_SedScheduleBNumberTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6666]"
Global Const $ItemDetailDlg_SedScheduleBQtyTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6665]"
Global Const $ItemDetailDlg_SedExtendedValueTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6667]"
Global Const $ItemDetailDlg_SedWeightTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6664]"
Global Const $ItemDetailDlg_LTLCommodityClassDescTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6669]"
Global Const $ItemDetailDlg_LTLWeightTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6668]"
Global Const $ItemDetailDlg_LTLFreightyClassTextbox = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6664]"    
Global Const $ItemDetailDlg_LTLCommodityClassTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c66610]"      
Global Const $ItemDetailDlg_CiUomCiCombo = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6662]"   
Global Const $ItemDetailDlg_CiCommodityDescTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6661]" 
Global Const $ItemDetailDlg_CiUnitPriceTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6662]" 

Global Const $ItemDetailDlg_CiNumberOfUnitsTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6663]" 
Global Const $ItemDetailDlg_CiManfCountryCombo = "[CLASSNN:WindowsForms10.COMBOBOX.app.0.202c6661]" 
Global Const $ItemDetailDlg_btnOK = "[CLASSNN:WindowsForms10.window.8.app.0.202c6665]" 

;Missing Globals
Global Const $WM_GET_CONTANIER_COUNT = "1"
Global Const $WM_SET_ACTIVE_CONTANIER = "1"


;*************** FUNCTIONS **********************************
;************************************************************

REMOVED

GeneralFunctions.au3

;********************************** INCLUDES ****************************************************
#include "sql.au3"
#Include <GuiComboBox.au3>

;********************************** GLOBAL VARIABLES ********************************************
Global $CRLF = Chr(13) & Chr(10)

Global $QADatabaseName = "AutoQA"
;~ Global $QADatabaseServer = "PAUL"
;~ Global $QADatabaseUser = "sa"
;~ Global $QADatabasePwd = "sa123"

Global Const $Company_ID = 1
;~ Global $UseForItemFulfill = 0
;~ Global $ShortedQTYToBO = 0
;~ Global $AllowNoDocumentShipping = 0
;~ Global $AllowUserPaymentMethodChange = 0
;~ Global $ShipAgainstBOQuantities = 0
;~ Global $SaveNonERPAddresses = 0
;~ Global $WarnOnPartialShip = 0
;~ Global $WarnIfDoubleShipped = 0
;~ Global $DisableASNWriteBack = 0
;~ Global $UseMultiBin = 0
;~ Global $DisableInnerWeightPrompt = 0
;~ Global $CombineAddress = 0

Global $CurrentTestCaseName = "Undefined"
Global $TraceFlag = 1
Global $CaseResultsOff = 0  ;Set to 1 to not write case results to database
Global $writeToTextOff = 0  ;Set to 1 to not write case results to txt file
;********************************** GLOBAL CONSTANTS ********************************************
Global Const $LoginDlg_Title = "Login to "
Global Const $LoginDlg_PasswordTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6662]"
Global Const $LoginDlg_UsernameTextbox = "[CLASSNN:WindowsForms10.EDIT.app.0.202c6661]"
Global Const $LoginDlg_btnLogin = "[CLASSNN:WindowsForms10.window.8.app.0.202c6665]"
Global Const $LoginDlg_btnConfirm = "[CLASSNN:WindowsForms10.window.8.app.0.202c6669]"

Global Const $MDIParentWindow = "[CLASSNN:WindowsForms10.MDICLIENT.app.0.202c666]"
Global Const $MainframeTitle = "- "
;***********************************  FUNCTIONS  ************************************************

Func execute()
;~  Global $CurrentTestCaseName = "Execute "
    Run("C:\Program Files\\.exe");Execute EXE
    WinWait("Login to ","",5);Wait for to open. 
    If Not WinActive("Login to ","") Then WinActivate("Login to ","");If Login Page is not active, make it the active screen
    WinWaitActive("Login to ","",5);Wait for it to be the active screen
    If Not WinActive("Login to ","") Then 
        WriteToText("FAIL - Could not open executable. QUITTING!")
        CaseResults(0, "FAIL - Could not open executable. QUITTING!")
    EndIf
EndFunc

Func ()
    Dim $OK=""
    If Not WinActive("") Then WinActivate("","");If is not the active screen, then make it so.
    WinWaitActive("","",3);Wait for it to be the active screen
EndFunc

Func WriteToText($String);Write data to text file.
    If ($writeToTextOff == 1) Then Return
;Saves $String to text file
    DIM $OK="";Initialize $OK For this Function
    $file = FileOpen("test.txt", 1)
    If $file = -1 Then
        MsgBox(0, "Error", "Unable to open file.")
        Exit
    EndIf
    $datetime=@MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN & ":" & @SEC & " - "
    FileWrite($file, $datetime & $String & @CRLF)

    FileClose($file)
    
    Return $OK
EndFunc

Func Login($username, $password);Login($username, $password) - Logs the user into with the given username/password
    DIM $OK="";Initialize $OK For this Function
    WinWait("Login to ","",5);Wait for to open. 
    If Not WinActive("Login to ","") Then WinActivate("Login to ","");If Login Page is not active, make it the active screen
    WinWaitActive("Login to ","",5);Wait for it to be the active screen
    If Not WinActive("[TITLE:Login to; CLASS:WindowsForms10.window.8.app.0.202c666; INSTANCE:1]", "") Then WinActivate("[TITLE:Login to; CLASS:WindowsForms10.window.8.app.0.202c666; INSTANCE:1]", "");If the 'User ID' field is not selected
    WinWaitActive("[TITLE:Login to; CLASS:WindowsForms10.window.8.app.0.202c666; INSTANCE:1]", "")
    Send($username);Username
    Send(@TAB) 
    Send($password);Password
    Send("{Enter}")
;Sleep(1000)
    WinWait("Invalid Login Attempt","","1");Wait a sec for an error to pop up
    if(WinActive("Invalid Login Attempt")) Then;IF an error popped up THEN
        $OK=StringTrimLeft(WinGetText("Invalid Login Attempt",""),3) & " " & $username & "//" & $password;Save the error message
    Else;Else no error popped up. 
        $OK="Login Successful" & " " & $username & "//" & $password;Set message as "Login Successful"
    EndIf 
    Send("{Enter}")
    SaveCompanyConfig()
    Return $OK;Return Message
EndFunc;End Login


Func SetCompanyConfig()
;Compile Query
    $Query = "UPDATE .dbo.Company SET "
    $Query = $Query & "UseForItemFulfill = " & $UseForItemFulfill & ", "
    $Query = $Query & "ShortedQTYToBO = " & $ShortedQTYToBO & ", "
    $Query = $Query & "AllowNoDocumentShipping = " & $AllowNoDocumentShipping & ", "
    $Query = $Query & "AllowUserPaymentMethodChange = " & $AllowUserPaymentMethodChange & ", "
    $Query = $Query & "ShipAgainstBOQuantities = " & $ShipAgainstBOQuantities & ", "
    $Query = $Query & "SaveNonERPAddresses = " & $SaveNonERPAddresses & ", "
    $Query = $Query & "WarnOnPartialShip = " & $WarnOnPartialShip & ", "
    $Query = $Query & "WarnIfDoubleShipped = " & $WarnIfDoubleShipped & ", "
    $Query = $Query & "DisableASNWriteBack = " & $DisableASNWriteBack & ", "
    $Query = $Query & "UseMultiBin = " & $UseMultiBin & ", "
    $Query = $Query & "DisableInnerWeightPrompt = " & $DisableInnerWeightPrompt & ", "
    $Query = $Query & "CombineAddress = " & $CombineAddress & ""
    $Query = $Query & " WHERE Company_ID = '" & $Company_ID & "'"
    If ($TraceFlag >= 1) Then WriteLine("SetCompanyConfig() | Query:'" & $Query & "'")
;Execute Query
    $oConn1 = ObjCreate("ADODB.Connection") 
    $error = $oConn1.Open ("DRIVER={SQL Server};SERVER=" & $Server & ";DATABASE=" & $QADatabaseName & ";uid=" & $QADatabaseUser & ";pwd=" & $QADatabasePwd & ";");<==Connect with required credentials
        If $error Then MsgBox(4096, "error code", "error code: " & $error)
    $oRSValid = ObjCreate("ADODB.Recordset")
    $error = $oRSValid.open($Query, $oConn1, $adOpenStatic, $adLockOptimistic, $adCmdText)
        If $error Then MsgBox(4096, "error code", "error code: " & $error)
    $oConn1.Close
;Log Out
;Log Back in
;Quit
EndFunc

Func SaveCompanyConfig();Saves out Company Config Options into global variables to be used later. 
    MsgBox(1,"","Saving Company Config")
    If ($TraceFlag >= 1) Then WriteLine("SavingCompanyConfig")
    $Query = "Select * FROM .dbo.Company WHERE Company_ID = '" & $Company_ID & "'";
;Saves out the following Options configurations from the company database. 
;UseForItemFulfill - Use for item fullfillment
;ShortedQTYToBO - Shorted Quatntities to back order
;AllowNoDocumentShipping - Allow Non-ERP Shipments
;AllowUserPaymentMethodChange - Allow user to change billing options
;ShipAgainstBOQuantities - Ship against back order quantities
;SaveNonERPAddresses - Save Non-ERP Address Defaults
;WarnOnPartialShip - Display Warning on partial shipment
;WarnIfDoubleShipped - Warn if double shipped
;DisableASNWriteBack - Disable ANS Write-Back
;UseMultiBin - Use Multi Bin
;DisableInnerWeightPrompt - Disable Inner Wgt. Prompt
;CombineAddress - Combine Address line 2 and 3 for FedEx Shipments

    $oConn1 = ObjCreate("ADODB.Connection") 
    $error = $oConn1.Open ("DRIVER={SQL Server};SERVER=" & $Server & ";DATABASE=" & $QADatabaseName & ";uid=" & $User & ";pwd=" & $Password & ";");<==Connect with required credentials
    $oRSValid = ObjCreate("ADODB.Recordset")
    $error = $oRSValid.open($Query, $oConn1, $adOpenStatic, $adLockOptimistic, $adCmdText)
    $intNbLignes = $oRSValid.Fields.count
    $Validrecs = $oRSValid.recordCount
    For $i = 0 to $Validrecs - 1
        For $j = 0 to $intNbLignes - 1
            $ColumnHeader = $oRSValid.Fields($j).name
            If $ColumnHeader = "UseForItemFulfill" Then;j=20 value=-1
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value )
                Global $UseForItemFulfill = $oRSValid.Fields($j).value
                MsgBox(1,"Setting up a Global","UseForItemFulfill = " & $UseForItemFulfill)
            ElseIf $ColumnHeader = "ShortedQTYToBO" Then;j=26 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $ShortedQTYToBO = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "AllowNoDocumentShipping" Then;j=28 value=-1
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $AllowNoDocumentShipping = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "AllowUserPaymentMethodChange" Then;j=34 value=-1
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $AllowUserPaymentMethodChange = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "ShipAgainstBOQuantities" Then;j=21 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $ShipAgainstBOQuantities = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "SaveNonERPAddresses" Then;j=63 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $SaveNonERPAddresses = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "WarnOnPartialShip" Then;j=41 value=-1
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $WarnOnPartialShip = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "WarnIfDoubleShipped" Then;j=58 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $WarnIfDoubleShipped = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "DisableASNWriteBack" Then;j=72 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value )
                Global $DisableASNWriteBack = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "UseMultiBin" Then;j=57 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $UseMultiBin = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "DisableInnerWeightPrompt" Then;j=71 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value)
                Global $DisableInnerWeightPrompt = $oRSValid.Fields($j).value
            ElseIf $ColumnHeader = "CombineAddress" Then;j=70 value=0
                If ($TraceFlag >= 1) Then WriteLine("j = " & $j & ", and " & $ColumnHeader & "= " & $oRSValid.Fields($j).value )
                Global $CombineAddress = $oRSValid.Fields($j).value
            EndIf
        Next
    $oRSValid.MoveNext
    Next
    MsgBox(1,"",$UseForItemFulfill)
EndFunc

ProcessShipmentDataFile.au3

#include <file.au3>
#include-once  <GuiListBox.au3>

Global Enum $REG_CONTAINER = 1, $Master = 2, $Inner = 3;Container Types
Global $DefaultCarrier = ""
Global $TraceFlag = 1
Global $PackedItems[1]

Func ProcessCreateShipmentsDataFile($FileName, $ReturnShipmentNumber)
    If ($TraceFlag >= 1) Then WriteLine("ProcessCreateShipmentsDataFile($FileName, $ReturnShipmentNumber) -  $FileName=" & $FileName)
    Dim $aRecords
    $aRecords = ReadCreateShipmentDataFile($FileName);Saves lines from file into array
    $ProcessingItemDetails = 0

    For $x = 1 To $aRecords[0]
        If ($TraceFlag >= 1) Then WriteLine("ProcessCreateShipmentsDataFile($FileName, $ReturnShipmentNumber) - DataFile Line = " & $aRecords[$x])
        
        $aRecords[$x] = StringStripWS($aRecords[$x], 1)
;~      WriteLine("Processing: " & $aRecords[$x])
;~      MsgBox(1, "Processing Next Line", $aRecords[$x])
;~      ConsoleWrite($aRecords[$x])
        ConsoleWrite("$aRecords[$x]")
        
        If ($ProcessingItemDetails == 1) Then
            If StringInStr($aRecords[$x], "End Item Details", 2) Then
                $ProcessingItemDetails = 0
                CloseItemDetailsDlg()
                Send("{Tab}");Tab to next pack grid line
            Else
                ProcessItemDetails($aRecords[$x])
            EndIf
        ElseIf StringInStr($aRecords[$x], "Item Details", 2) Then
            If ($TraceFlag >= 1) Then WriteLine("Setting $ProcessingItemDetails = 1")
            $ProcessingItemDetails = 1
        EndIf
        
        If StringInStr($aRecords[$x], "Begin Shipment", 2) Then;Opens Shipment Window and ends
            CallCreateShipmentFromMenu()
        EndIf
        
        If StringInStr($aRecords[$x], "Open Order:", 2) Then
            $CurrentPercentage = 50
;~          GUICtrlSetData($currentprogress, $CurrentPercentage)
            OpenOrder($aRecords[$x])
        EndIf
        
        If StringInStr($aRecords[$x], "Default Carrier", 2) Then
            $CurrentPercentage = 25
;~          GUICtrlSetData($currentprogress, $CurrentPercentage)
            WriteLine("Setting Default Carrier: = " & $aRecords[$x])
            SaveDefaultCarrier($aRecords[$x])
        EndIf
        
        If StringInStr($aRecords[$x], "NonERP Customer Dest:", 2) Then;Sets $NonERPCustDest as
            $p = StringSplit($aRecords[$x], ":")
            $NonERPCustDest = $p[2]
            WriteLine("Setting NonERP Customer Dest: = " & $NonERPCustDest)
        EndIf
        
        If StringInStr($aRecords[$x], "Create Container:", 2) Then
            $CurrentPercentage = 75
;~          GUICtrlSetData($currentprogress,$CurrentPercentage)
            $results = StringSplit($aRecords[$x], ":")
            $ContainerType = $results[2]
            If (StringInStr($ContainerType, "New Container") > 0) Then
                CreateContainer($REG_CONTAINER)
;~              MsgBox(1, "Processing Next Line", "Container Created")
            ElseIf (StringInStr($ContainerType, "New Master") > 0) Then
                CreateContainer($Master)
            ElseIf (StringInStr($ContainerType, "New Inner Same Master") > 0) Then
                If ($TraceFlag >= 1) Then WriteLine("About to create Inner")
                CreateContainer($Inner)
            Else
                CaseResults(0, "Unknown Container Type" & $ContainerType)
            EndIf
        EndIf
        
        If StringInStr($aRecords[$x], "Pack Item:", 2) Then
            PackItem($aRecords[$x])
        EndIf

        If StringInStr($aRecords[$x], "End Item Pack", 2) Then
            Send("{TAB}")
        EndIf
        
        If StringInStr($aRecords[$x], "COMMIT SHIPMENT", 2) Then
;~          If IsDeclared($OrderNumber) THEN;TESTTESTTESTTESTTESTTESTTESTTEST
;~          _Arraylay($PackedItems)
            Global $ShipmentNumber = GetShipmentNumber();Pulls value from windows handle
            GetCaclulatedSOP10200()
            $CurrentPercentage = 80
;~          GUICtrlSetData($currentprogress,$CurrentPercentage)
            ProcessCommitShipment($aRecords[$x])
            If ($ReturnShipmentNumber == True) Then
                Return $ShipmentNumber
            EndIf
        EndIf
        
        If StringInStr($aRecords[$x], "SAVE SHIPMENT", 2) Then
            Global $ShipmentNumber = GetShipmentNumber()
;~          ConsoleWrite("***** New Shipment Number: " & $ShipmentNumber & "*****" & Chr(13) & Chr(10))
            SaveShipment()
            If ($ReturnShipmentNumber == True) Then
                Return $ShipmentNumber
            EndIf
        EndIf
    Next
EndFunc  ;==>ProcessCreateShipmentsDataFile

Func GetCaclulatedSOP10200()
    Global $Calculated[100][13]
;~  $getDBRow["item"] = 2343
;~  $EnterShipmentNumber = "ORDST2234"
;~  MsgBox(1,"OrderNum", $OrderNumber)
    $query = "Select ITEMNMBR,QUANTITY,QTYFULFI,QTYTOINV,QTYTBAOR,QTYREMAI,ACTLSHIP,FUFILDAT,ATYALLOC,QTYCANCE FROM TWO.dbo.SOP10200 WHERE SOPNUMBE = '" & $OrderNumber & "'"
;~  $query = "Select QUANTITY,QTYFULFI,QTYTOINV,QTYTBAOR,ACTLSHIP,FUFILDAT From TWO.dbo.SOP10200 where SOPNUMBE='ORDST2231'
;~  $query = "Select * FROM AutoQA.dbo.ERP3_SHP_ContainerItemDetail"
    GetDBRow($query, "TWO")
    $Calculated = $getDBRow
;~  _ArrayDisplay($Calculated)
;~  $ArrayMaxIndex = _ArrayMaxIndex($getDBRow,1)
;~  MsgBox(1,"","Array max index = " & @error)
    $run = True
    $row = 1;Skip 0 b/c it contains the column headers
;~  _ArrayDisplay($Calculated)
    While $run
        If $Calculated[$row][0] = "END" Then ExitLoop;$run = false
        
    ;*******PULL OUT CURRENT VALUES FROM DB*********************
;~      _ArrayDisplay($Calculated)
        $item = $Calculated[$row][0]
        $QUANTITY = $Calculated[$row][1];Save QUANTITY - 45
        $QTYFULFI = $Calculated[$row][2];Save QTYFULFI - 67
        $QTYTOINV = $Calculated[$row][3];Save QTYTOINV - 65
        $QTYTBAOR = $Calculated[$row][4];Save QTYTBAOR - 64
        $QTYREMAI = $Calculated[$row][5];Save QTYREMAI - 62
        $FUFILDAT = $Calculated[$row][7];Save FUFILDAT - 73
        $ACTLSHIP = $Calculated[$row][6];Save ACTLSHIP - 74
        $ATYALLOC = $Calculated[$row][8];Save ATYALLOC - 46
        $QTYCANCE = $Calculated[$row][9];Save QTYCANCE - 52
        
        
    ;****************CALCULATE WHAT VALUES SHOULD BE*****
    ;Pull out the # of this item packed on this shipment.
        $searchIndex = _ArraySearch($PackedItems, $item, 0, UBound($PackedItems), "", 1);Find out where in the array this item falls
        If $searchIndex == -1 Then
            MsgBox(1, "ERROR", "The item:'" & $item & "' was not found in the array")
            ExitLoop
        EndIf
        $string = $PackedItems[$searchIndex];Pull out the string
        $Array = StringSplit($string, "^");Build array on that parsed string
        $PackedQuantity = $Array[2];Pull out the quantity of item packed in this shipment
        
;~      _ArrayDisplay($PackedItems)
        MsgBox(1,"","Item Packed:'" & $item & "' Quantity:'" & $PackedQuantity & "'")
        ResetToMain()
        MsgBox(1,"Use for item fulfillment", $UseForItemFulfill)
        If $UseForItemFulfill == -1 Then;If Checked then TWO database should be updated
        MsgBox(1,"","Item Packed:'" & $item & "' Quantity:'" & $PackedQuantity & "'")
        ;Calculate QTYFULFI
            
            $N_QTYFULFI = $QTYFULFI + $PackedQuantity
            
        ;Calculate QTYREMAI
            $N_QTYREMAI = $QUANTITY - $QTYCANCE

        ;Calculate QTYTBAOR
        ;If shorten quantity to backorder is turned ON then N_QTYTBAOR = QTYREMAI - N_QtyToInv
        ;ELSE N_QTYTBAOR = QTYTBAOR (should not change)
            If $ShortedQTYToBO == -1 Then
                $N_QTYTBAOR = $N_QTYREMAI - $N_QtyToInv
            Else
                $N_QTYTBAOR = $QTYTBAOR
            EndIf
            
        ;Calculate QTYTOINV
        ;We decided to Use the following equation because quantity remaining includes cancelled quantities.
        ;We don't care if QTYFULFI = 0 b/c were only making modifications to the QTYTOINV if an item is being shipped.
            $N_QtyToInv = $QTYREMAI - $N_QTYTBAOR
            
            
        ;Calculate FUFILDAT
        ;When '2008-10-16 00:00:00.000' is pulled from table it looks like '20081016000000'
            $N_FUFILDAT = @YEAR & @MON & @MDAY & "000000"
        ;Calculate ACTLSHIP
            $N_ACTLSHIP = $N_FUFILDAT
        ;Calculate ATYALLOC
        ;AtyAlloc can be >= QtyFulfilled, usually it will be equal
        ;AtyAlloc could be greater if I have not fulfilled the order yet, or if I fulfilled partially but did not backorder
            $N_ATYALLOC = $ATYALLOC
            
        Else;The database should not change
            $N_QTYFULFI = $QTYFULFI
            $N_QtyToInv = $QTYTOINV
            $N_QTYTBAOR = $QTYTBAOR
            $N_FUFILDAT = $FUFILDAT
            $N_QTYREMAI = $QTYREMAI
            $N_ATYALLOC = $ATYALLOC
            $N_ACTLSHIP = $ACTLSHIP
        EndIf
    ;********* PUT NEW VALUES BACK IN *****************************
        $Calculated[$row][2] = $N_QTYFULFI;Save QTYFULFI - 67
        $Calculated[$row][3] = $N_QtyToInv;Save QTYTOINV - 65
        $Calculated[$row][4] = $N_QTYTBAOR;Save QTYTBAOR - 64
        $Calculated[$row][5] = $N_QTYREMAI;Save QTYREMAI - 62
        $Calculated[$row][7] = $N_FUFILDAT;Save FUFILDAT - 73
        $Calculated[$row][6] = $N_ACTLSHIP;Save ACTLSHIP - 74
        $Calculated[$row][8] = $N_ATYALLOC;Save ATYALLOC - 46
        
        $row = $row + 1
        If $Calculated[$row][0] = "END" Then ExitLoop;$run = false
    WEnd
    
    _ArrayDisplay($Calculated)
EndFunc  ;==>GetCaclulatedSOP10200

;Reads in a Shipment File, into an array.
Func ReadCreateShipmentDataFile($FileName)
    If ($TraceFlag >= 1) Then WriteLine("ReadCreateShipmentDataFile($FileName)")
    Dim $aRecords
    If Not _FileReadToArray($FileName, $aRecords) Then
;~      MsgBox(4096,"Error", " Error reading log to Array    error:" & @error)
        Exit
    EndIf
    Return $aRecords
EndFunc  ;==>ReadCreateShipmentDataFile

;Processes and stores the [Default Carrier] line from a Shipment File for later use if needed.
Func SaveDefaultCarrier($Command)
    If ($TraceFlag >= 1) Then WriteLine("SaveDefaultCarrier(" & $Command & ")")
    $SplitCommand = StringSplit($Command, ":")
    Global $DefaultCarrier = $SplitCommand[2]
    If ($TraceFlag >= 1) Then WriteLine("$DefaultCarrier = '" & $SplitCommand[2] & "'")
EndFunc  ;==>SaveDefaultCarrier

;Processes the [Open Order] line from a Shipment File. "Open Order:`Order#`"
Func OpenOrder($Command)
    WriteLine("Running OpenOrder($Command)")
    $Docnum = StringSplit($Command, ":")
;~  Open Order:3
;~  $Docnum[1]:$Docnum[0]
;~  MsgBox(1, "Processing Next Line", $Docnum[0]);2         ;Number of pieces
;~  MsgBox(1, "Processing Next Line", $Docnum[1]);"Open Order"  ;First Piece
;~  MsgBox(1, "Processing Next Line", $Docnum[2]);Order#        ;Second Piece
    If ($Docnum[0] == 2) Then;If there was an Order # entered, OR It wasn't "Order Number:"
        Global $OrderNumber = $Docnum[2];Sets this up so it can be used in place of shipping # for 'ERPCommitShipment'
    ;Enter Shipment Number
        EnterShipmentNumber($Docnum[2])
    ;If no Order entered, Enter Destination
        CheckForNonERPDestWindow();Enters the Destination
        
;~          Send("{Enter}");DOING THIS TO COMBAT THE DOUBLE SHIPMENT METHOD
        
    ;Enter Shipment Method
;~          MsgBox(1,"","About to enter Shipment Method")
        EnterShipmentMethod()
;~          MsgBox(1,"","Just entered 1st shipment method")
        WinWaitActive($ShipmentOption_Title, "", 1)
        If WinActive($ShipmentOption_Title, "") Then
;~              MsgBox(1,"","Need to enter 2nd shipment method")
            EnterShipmentMethod()
;~              MsgBox(1,"","Just entered 2nd shipment method")
        EndIf
        
    ;Check for shipping destination window
        CheckForShipmentDestWindow()
        
    ;Check for an Invalid Shipping method warning
        CheckForInvalidShippingMethod(False)
        
    ;$r = WinExists(" - ", "Shipment Number:")
    ;If ($r == 0) Then CaseResults(0, "OpenOrder - Failed")
    Else;No Number entered
;~          MsgBox(0, "ERROR", "No Document Number Specified in Command. " & $Command)
        Exit -1
    EndIf
EndFunc  ;==>OpenOrder

;Processes the [Pack Item] line from a Shipment File.
Func PackItem($Command)
    WriteLine("PackItem($Command) -$Command = " & $Command & "   Traceflag:" & $TraceFlag)
    $results = StringSplit($Command, ":")
    $PackInfo = StringSplit($results[2], ";")
    $item = $PackInfo[1]
    $QUANTITY = $PackInfo[2]
;~  MsgBox(1,"","'" & $item & "' | '" & $quantity & "'")

;~  $searchIndex = _ArraySearch($PackedItems,$item);Check to see if this item is in the array, and save out where it is found
;~  If $searchIndex == -1 Then;If item is not found
;~      $index = _ArrayAdd($PackedItems,$item);Add the item and save out where that item is added.
;~      if $index ==  -1 Then MsgBox(1,"ERROR","That item could not be added on line 210 of ProcessShipmentDataFile")
;~      MsgBox(1,"Index","The index = '" & $index & "'")
;~      $PackedItems[$index][1] = $quantity;Save the quantity to $PackedItems[index of item found]["0"]
;~  Else;Else set $PackedItems[Item#][0]=$PackedItems[Item#][0] + Quantity
;~      $PackedItems[$searchIndex][1] = $PackedItems[$searchIndex][1] + $quantity
;~  EndIf
;Add item/Quantity to to the $ItemsPacked array
    $searchIndex = _ArraySearch($PackedItems, $item, 0, UBound($PackedItems), "", 1);Search through array for name
    If $searchIndex == -1 Then;If item is not found
;~      MsgBox(1, "", "Item does notItem does not exist. Adding it.")
        _ArrayAdd($PackedItems, $item & "^" & $QUANTITY)
    Else
;~      MsgBox(1, "", "Item exists, adding quantity.")
        $string = $PackedItems[$searchIndex]
        $Array = StringSplit($string, "^")
        $name = $Array[1]
        $old_quantity = $Array[2]
;~      MsgBox(1, "", "Name = '" & $name & " and old quantity = '" & $old_quantity & "'")
        $old_quantity = $old_quantity + $QUANTITY
        $PackedItems[$searchIndex] = $name & "^" & $old_quantity
    EndIf
;~  _ArrayDisplay($PackedItems, "$PackedItems AFTER _ArrayAdd()")
    
    
;PackItem_ByTyping($PackInfo[1], $PackInfo[2]);Item, Quantity
    Send($PackInfo[1])
    Send("{TAB}")
    Send($PackInfo[2])
;~  MsgBox(1, "Processing Next Line", "Item Packed")
;~  CheckForSLBScreen_SkipIt()
EndFunc  ;==>PackItem

;Processes the [COMMIT SHIPMENT | SAVE SHIPMENT] line from a Shipment File.
Func ProcessCommitShipment($Command)
    If ($TraceFlag >= 1) Then WriteLine("ProcessCommitShipment($Command)")
    CommitShipment()
;~  MsgBox(1,"","Closing Doc # Dialog")
    CloseDocumentNumberDlg()
    If ($TraceFlag >= 1) Then WriteLine("***** COMMIT - New Shipment Number: " & $ShipmentNumber & "*****")
EndFunc  ;==>ProcessCommitShipment
What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

Man I sure hope someone responds. I spent a while going through that code and removing necessary items and getting it viewable.

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

  • Developers

Have you tried adding the #include-once directive in the "to-be-included" files as suggested?

This will avoid the included file being added multiple times.

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Have you tried adding the #include-once directive in the "to-be-included" files as suggested?

This will avoid the included file being added multiple times.

Jos

This sounds like it is for when you include a file multiple times and you don't want to get that stupid "Function already defined" error. Which I'm not doing. Each file is only included into the process once. I can try it though to see if it changes anything. Not sure if its going to help me with my issue of my Global variable '$UseForItemFulfill' just disappearing.

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

  • Developers

I didn't look in detail to all the code posted but in general the way we have setup all UDF files is that each file includes whatever it needs to run independently and we ensure that all included files contain an #include-Once to avoid any duplicate definitions.

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

What you need to do is to remove all the global variables that you want to use outside of the file they are declared in and place them in a separate file and include this in your main script before any other include files. Similarly any include files that just declare constants should be included before any of the constants are used. The order of the included files is important if the include files are not completely independent of each other.

"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to build bigger and better idiots. So far, the universe is winning."- Rick Cook

Link to comment
Share on other sites

I didn't look in detail to all the code posted but in general the way we have setup all UDF files is that each file includes whatever it needs to run independently and we ensure that all included files contain an #include-Once to avoid any duplicate definitions.

Well I probably could make it so each file is set up to run independently. But that would involve tons of duplicate code in every file. Just to solve this issue I would have to copy and paste the code to pull the application settings into every file. So that they don't have to call a separate files function do do so, but that just doesn't seem like a good way to do things.

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

What you need to do is to remove all the global variables that you want to use outside of the file they are declared in and place them in a separate file and include this in your main script before any other include files. Similarly any include files that just declare constants should be included before any of the constants are used. The order of the included files is important if the include files are not completely independent of each other.

I'm going to try this now but it makes me wonder something...

If I have my Main file here:

MAIN

#include Globals.au3

And Inside my globals I have all of them setup:

GLOBALS

Global A = ""

GLobal Const B = ""

And then my main calls a different file and sets that global

A = "ABC"

Isn't that going to set a local 'A' rather than setting the value of the Global 'A'? Or do I say global still in the other files I call? Like:

Global A = "ABC"

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

http://www.autoitscript.com/autoit3/docs/keywords/Dim.htm

Declaring the same variable name again will erase all array values and reset the dimensions to the new definition. Declaring a variable with a simple value in the same scope will not change the value in the variable.

As already mentioned the script will look like this:

;Include

Global $A = ""

Global Const $B = ""

;Include end

Global $A = "ABC"

$A is now declared as "ABC" and the previous value are deleted. It will still be a Global variable. Keep in mind that you should always declare a variable and not only write $A, use Dim $A or Global $A.

Link to comment
Share on other sites

Well I'm pretty sure I found my issue. In my main code I say:

$ExitCode = ShellExecuteWait("C:\Program Files\AutoIt3\autoit3.exe", $FileName & " " & $Parameters, @ScriptDir & $subDir)

When I do that, the file being called has NO scope of any globals previously setup. Correct?

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

Well I'm pretty sure I found my issue. In my main code I say:

$ExitCode = ShellExecuteWait("C:\Program Files\AutoIt3\autoit3.exe", $FileName & " " & $Parameters, @ScriptDir & $subDir)

When I do that, the file being called has NO scope of any globals previously setup. Correct?

To answer that we need to know the context:

Is $FileName already declared as Global before this line is executed?

Is this line of code inside a function?

If it's a function: Is $FileName a declared parameter of the function?

If it's a function: Is $FileName declared Local in the function (automatically done if it's an input parameter)?

:mellow:

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

To answer that we need to know the context:

Is $FileName already declared as Global before this line is executed?

Is this line of code inside a function?

If it's a function: Is $FileName a declared parameter of the function?

If it's a function: Is $FileName declared Local in the function (automatically done if it's an input parameter)?

:mellow:

The code is all above in code tags. Its in the TestCaseMain.au3

FileName is a variable that gets defined as it is pulled form a SQL TBL. As you can see in the code I posted above, it loops through my "Test Cases" table looking for active tests and then calling that line with the filename & parameters.

So is a local variable of the function. So it calls SciTE with the file to open, and the parameters to pass.

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

The code is all above in code tags. Its in the TestCaseMain.au3

FileName is a variable that gets defined as it is pulled form a SQL TBL. As you can see in the code I posted above, it loops through my "Test Cases" table looking for active tests and then calling that line with the filename & parameters.

So is a local variable of the function. So it calls SciTE with the file to open, and the parameters to pass.

The first thing that will force you to fix this is to put the following at the top of every script (not required in the include files):
Opt('MustDeclareVars', 1)

AutoIt allows some things that are often considered bad practice, and one of them is declaring a variable by assignment of a value. (This is for a good reason - to make AutoIt easy to use for non-programmer types like me.) By the time you start writing complicated script with multiple include files, you really need to step up your game. In this case, force yourself to consider the scope of every variable you use. The above option will help with that.

The $FileName variable is not explicitly declared, except where it is used as a function input parameter (because that is an automatic Local declaration). The first place I see it declared is by assignment in the BeginTests() function:

$FileName = $oRS3.Fields("FileName").Value

The 'MustDeclareVars' option will force you to fix that, like declaring "Local $FileName" near the top of the function. It will also force you to fix the bad habit of declaring Globals inside a function, like:

Func BeginTests()
    Global $TraceFlag = 2
    Global $FailedCaseCount = 0
    Global $PassedCaseCount = 0;$Result = Login('sa', 'sa')
    $CurrentTestCaseName = "Main"

   ; <snip>
EndFunc

The first four lines of that function are all bad practice that 'MustDeclareVars' will force you to fix. The first three lines should be outside a function near the top of the include file, and $CurrentTestCaseName should have Local in front of it if it is not already Global from some other statement (no, I'm not going looking for it).

Remember we are talking about best practice and reducing confusion here - not just making it work. It could work and you could ignore some Syntax warnings, but the more complicated the script, the more likely this stuff is going to bite you in buttocks.

:mellow:

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
Share on other sites

The first thing that will force you to fix this is to put the following at the top of every script (not required in the include files):

Opt('MustDeclareVars', 1)

AutoIt allows some things that are often considered bad practice, and one of them is declaring a variable by assignment of a value. (This is for a good reason - to make AutoIt easy to use for non-programmer types like me.) By the time you start writing complicated script with multiple include files, you really need to step up your game. In this case, force yourself to consider the scope of every variable you use. The above option will help with that.

The $FileName variable is not explicitly declared, except where it is used as a function input parameter (because that is an automatic Local declaration). The first place I see it declared is by assignment in the BeginTests() function:

$FileName = $oRS3.Fields("FileName").Value

The 'MustDeclareVars' option will force you to fix that, like declaring "Local $FileName" near the top of the function. It will also force you to fix the bad habit of declaring Globals inside a function, like:

Func BeginTests()
    Global $TraceFlag = 2
    Global $FailedCaseCount = 0
    Global $PassedCaseCount = 0;$Result = Login('sa', 'sa')
    $CurrentTestCaseName = "Main"

  ; <snip>
EndFunc

The first four lines of that function are all bad practice that 'MustDeclareVars' will force you to fix. The first three lines should be outside a function near the top of the include file, and $CurrentTestCaseName should have Local in front of it if it is not already Global from some other statement (no, I'm not going looking for it).

Remember we are talking about best practice and reducing confusion here - not just making it work. It could work and you could ignore some Syntax warnings, but the more complicated the script, the more likely this stuff is going to bite you in buttocks.

:mellow:

Thank you for that. I am going to give it a go. I definitely need to get things working "correctly" now. Because I know that I will be adding more and more code, full time, for a while so things could get ugly. Keep in mind I have only been using AutoIt and SciTE for a couple weeks, so I have a lot to learn still.

What I'm using AutoIt for: I was hired as QA to write automated tests for our software. So I macro any possible situation/process a user could get themselves into, and then check to see that the outcome is what I expect.
Link to comment
Share on other sites

Keep in mind I have only been using AutoIt and SciTE for a couple weeks, so I have a lot to learn still.

Been there, done that, got the Carpal Tunnel Syndrome Telethon t-shirt...

:mellow:

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...