Jump to content
Sign in to follow this  
njahncke

Simple Script Review Request

Recommended Posts

njahncke

Hey there everyone,

I'm rather new to a lot of the functionality that AutoIt provides, having used it mostly to automate common network and systems engineering tasks in the past, and am wondering if any of you feel like taking a look at the following script and just giving me some pointers about shortcuts I'm missing, flow inefficiencies, et cetera. Thanks in advance for any help at all! This is a great community, and I'm happy to be a part of it.

~ Norris

#cs -----------------------------------------------------------------------------------------------------------------------

 Script Function:
    This script will repeatedly log in and then out of the ApplicationX application until exited by pressing the Escape key.
    Each run will generate a new log file in the "<script DIR>\AXALU Logs" directory.

#ce -----------------------------------------------------------------------------------------------------------------------

;~ Version and Author
Global $scriptName = "ApplicationX Auto-Login Utility v0.5"
Global $authorName = "Norris"

;--------------------------------------------------------------------------------------------------------------------------
; Initialization ----------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

;~ Welcome Prompt
If MsgBox(262209,$scriptName,"This utility will stress the login capability of the ApplicationX application." & @CR & "Press the Escape key at any time to exit." & @CR & @CR & "Please click OK to continue.") = 2 Then Exit

;~ Include Declarations
#include <Date.au3>

;~ Set HotKeys
HotKeySet("{ESC}","Abort")

;~ Variable Declarations
Global $loginCount = 0
Global $startTimestamp = _Now()
Global $logFileName = "AXALU Log " & @MON & "-" & @MDAY & "-" & @YEAR & "@" & @HOUR & "-" & @MIN & "-" & @SEC & ".htm"
Global $logTemp = FileOpen(@ScriptDir & "\AXALU Logs\~temp.tmp",9)
Global $logFile = FileOpen(@ScriptDir & "\AXALU Logs\" & $logFileName,9)
Global $resultCode = ""
Global $resultText = ""

;--------------------------------------------------------------------------------------------------------------------------
; Program Execution -------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

Record("AXALU Initializing...")

; If ApplicationX is already running, close it so we can predict its interface upon restart.
; If ApplicationX fails to close, terminate execution with error code "shutdownFailure"
If ProcessExists("ApplicationX.exe") Then
    Record("ApplicationX is currently running. Closing ApplicationX...")
    ProcessClose("ApplicationX.exe")
    If WinWaitClose("ApplicationX","",7) = 0 Then Close("shutdownFailure")
    Record("ApplicationX closed.")
EndIf

; Start ApplicationX back up again; first window up should be the Login window.
; If the Login window never appears, terminate execution with error code "initializationFailure"
Record("Starting ApplicationX...")
Run("C:\win\ApplicationX.exe","C:\win")
If WinWaitActive("ApplicationX","Login",7) = 0 Then Close("initializationFailure")
Record("ApplicationX started.")

; Begin looping through login and logout.
; At present, this will be done indefinitely.
While 1
    ControlClick("ApplicationX","Login","[CLASS:WindowsForms10.window.8.app.0.378734a; INSTANCE:2]")
    If WinWaitActive("ApplicationX","Home",7) = 0 Then Close("logoutFailure")
    $loginCount += 1
    Record("Login successful. This is login number " & $loginCount & ".")
    ControlClick("ApplicationX","Home","[CLASS:WindowsForms10.window.8.app.0.378734a; INSTANCE:5]")
    If WinWaitActive("ApplicationX","Login",7) = 0 Then Close("loginFailure")
    Record("Logout successful.")
WEnd

; This will currently never happen, but it corresponds to our Pass condition.
Close("none")

;--------------------------------------------------------------------------------------------------------------------------
; Functions ---------------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

; Basic function for log entries. 
Func Record($record)
    FileWriteLine($logTemp,_Now() & " *** " & $record)
EndFunc

; We can't send parameters along with functions called via HotKey, so create a delegate.
Func Abort()
    Close("abort")
EndFunc

; Our general shutdown handler.
; This function works on $errorCode to determine the type of error, if any.
; It then either notifies the user of the error type and exits, or formats the result vars the GenerateReport function will use and calls it.
; After error notification, if appropriate, the system closes the ApplicationX application and prompts the user regarding display of the result report.
Func Close($errorCode)
    Local $s = "s"
    If $loginCount <> 1 Then $s = ""

    Switch $errorCode
    Case "abort"
        Record("Program terminated upon request by user.")
        $resultCode = "aborted"
        $resultText = "Test Aborted by user after " & $loginCount & " successful login" & $s & "."
    Case "shutdownFailure"
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system was unable to shut down the ApplicationX application." & @CR & @CR & "Please exit ApplicationX manually and then restart this program.")
        Exit
    Case "initializationFailure"
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system was unable to initialize the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
        Exit
    Case "loginFailure"
        Record("Abnormal program termination: ApplicationX login failed.")
        $resultCode = "failed"
        $resultText = "Login Failure after " & $loginCount & " successful login" & $s & "."
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system failed to log in to the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
    Case "logoutFailure"
        Record("Abnormal program termination: ApplicationX login failed.")
        $resultCode = "failed"
        $resultText = "Logout Failure after " & $loginCount & " successful login" & $s & "."
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system failed to log in to the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
    Case "none"
        Record("Test passed!")
        $resultCode = "passed"
        $resultText = "Test Passed after " & $loginCount & " successful logins!"
    Case Else
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","An unknown error has occurred.")
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        Exit
    EndSwitch

    GenerateReport()
    FileClose($logFile)
    ProcessClose("ApplicationX.exe")
    If MsgBox(262209,$scriptName,"Click OK to open the result report for this test pass.") = 1 Then Run("C:\Program Files\Internet Explorer\iexplore.exe " & @ScriptDir & "\AXALU Logs\" & $logFileName)
    Exit
EndFunc

; Prepare .htm file for inclusion of log contents, then loop through $logTemp until EOF.
; Individual lines of the actual log are sequenced in alternating row colors for ease of reading.
; Finish off by properly terminating the new result file, close $logTemp and then delete it.
Func GenerateReport()
    FileClose($logTemp)
    FileOpen(@ScriptDir & "\AXALU Logs\~temp.tmp",0)
    FileWriteLine($logFile,"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><title>"&$scriptName&"</title><style type='text/css'>body{font-family:Arial;font-size:12px;color:#2B6593;}h1{font-size:24px;color:#6FA9D5;margin:0px 0px 10px 0px;}h2{font-weight:normal;font-size:18px;color:#5E98C4;margin:10px 0px 10px 0px;}hr{color:#2B6593;margin:0px 0px 0px 0px;}.logOdd{background-color:#EEEEFE;padding:3px 5px 3px 5px;margin:0px 10px 0px 10px;}.logEven{background-color:#E8E8F8;padding:3px 5px 3px 5px;margin:0px 10px 0px 10px;}.passed{color:#00AA00;}.aborted{color:#FF9900;}.failed{color:#FF0000;}</style></head><body><h1>"&$scriptName&"</h1><hr /><h2><b>Date & Time:</b> "&$startTimestamp&"</h2><h2><b>Test Result:</b> <span class='"&$resultCode&"'>"&$resultText&"</span></h2><hr /><h2><b>Test Log:</b></h2>")
    Local $lineCounter = 1
    While 1
        $line = FileReadLine($logTemp)
        If @error = -1 Then ExitLoop
        If Mod($lineCounter,2) = 0 Then
            FileWriteLine($logFile,"<div class='logEven'>")
        Else
            FileWriteLine($logFile,"<div class='logOdd'>")
        EndIf
        If StringInStr($line,"passed") Then
            FileWriteLine($logFile,"<span class='passed'>")
        ElseIf StringInStr($line,"terminated") Then
            FileWriteLine($logFile,"<span class='aborted'>")
        ElseIf StringInStr($line,"failed") Then
            FileWriteLine($logFile,"<span class='failed'>")
        EndIf
        FileWriteLine($logFile,$line)
        FileWriteLine($logFile,"</span></div>")
        $lineCounter += 1
    WEnd
    FileWriteLine($logFile,"</body></html>")
    FileClose($logTemp)
    FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
EndFunc

Share this post


Link to post
Share on other sites
Nahuel

That looks very tidy. Keep commenting on your scripts, you'll see how useful that can be.

I made a small modification on the way it handles the Run error. If the script can't find ApplicationX, then it will exit with a fatal AutoIt error. I chaged that adding: Opt("RunErrorsFatal",0).

#cs -----------------------------------------------------------------------------------------------------------------------

 Script Function:
    This script will repeatedly log in and then out of the ApplicationX application until exited by pressing the Escape key.
    Each run will generate a new log file in the "<script DIR>\AXALU Logs" directory.

#ce -----------------------------------------------------------------------------------------------------------------------

;~ Version and Author
Global $scriptName = "ApplicationX Auto-Login Utility v0.5"
Global $authorName = "Norris"

;--------------------------------------------------------------------------------------------------------------------------
; Initialization ----------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

;~ Welcome Prompt
If MsgBox(262209,$scriptName,"This utility will stress the login capability of the ApplicationX application." & @CR & "Press the Escape key at any time to exit." & @CR & @CR & "Please click OK to continue.") = 2 Then Exit

;~ Include Declarations
#include <Date.au3>

;~ Set HotKeys and special options
HotKeySet("{ESC}","Abort")
;modification. Nahuel
Opt("RunErrorsFatal",0);Silent error. Sets @error to 1.

;~ Variable Declarations
Global $loginCount = 0
Global $startTimestamp = _Now()
Global $logFileName = "AXALU Log " & @MON & "-" & @MDAY & "-" & @YEAR & "@" & @HOUR & "-" & @MIN & "-" & @SEC & ".htm"
Global $logTemp = FileOpen(@ScriptDir & "\AXALU Logs\~temp.tmp",9)
Global $logFile = FileOpen(@ScriptDir & "\AXALU Logs\" & $logFileName,9)
Global $resultCode = ""
Global $resultText = ""

;--------------------------------------------------------------------------------------------------------------------------
; Program Execution -------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

Record("AXALU Initializing...")

; If ApplicationX is already running, close it so we can predict its interface upon restart.
; If ApplicationX fails to close, terminate execution with error code "shutdownFailure"
If ProcessExists("ApplicationX.exe") Then
    Record("ApplicationX is currently running. Closing ApplicationX...")
    ProcessClose("ApplicationX.exe")
    If WinWaitClose("ApplicationX","",7) = 0 Then Close("shutdownFailure")
    Record("ApplicationX closed.")
EndIf

; Start ApplicationX back up again; first window up should be the Login window.
; If the Login window never appears, terminate execution with error code "initializationFailure"
Record("Starting ApplicationX...")
Run("C:\win\ApplicationX.exe","C:\win")
; ~ my modification. Nahuel ~
If @error Then;If it can't run ApplicationX then abort.
    MsgBox(16,"Fatal Error","Unable to execute ApplicationX. " & @CRLF & "Aborted.")
    Exit
EndIf


;Maybe this won't be necessary after the slight change I made
If WinWaitActive("ApplicationX","Login",7) = 0 Then Close("initializationFailure")
Record("ApplicationX started.")

; Begin looping through login and logout.
; At present, this will be done indefinitely.
While 1
    ControlClick("ApplicationX","Login","[CLASS:WindowsForms10.window.8.app.0.378734a; INSTANCE:2]")
    If WinWaitActive("ApplicationX","Home",7) = 0 Then Close("logoutFailure")
    $loginCount += 1
    Record("Login successful. This is login number " & $loginCount & ".")
    ControlClick("ApplicationX","Home","[CLASS:WindowsForms10.window.8.app.0.378734a; INSTANCE:5]")
    If WinWaitActive("ApplicationX","Login",7) = 0 Then Close("loginFailure")
    Record("Logout successful.")
WEnd

; This will currently never happen, but it corresponds to our Pass condition.
Close("none")

;--------------------------------------------------------------------------------------------------------------------------
; Functions ---------------------------------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------------------------------------------

; Basic function for log entries. 
Func Record($record)
    FileWriteLine($logTemp,_Now() & " *** " & $record)
EndFunc

; We can't send parameters along with functions called via HotKey, so create a delegate.
Func Abort()
    Close("abort")
EndFunc

; Our general shutdown handler.
; This function works on $errorCode to determine the type of error, if any.
; It then either notifies the user of the error type and exits, or formats the result vars the GenerateReport function will use and calls it.
; After error notification, if appropriate, the system closes the ApplicationX application and prompts the user regarding display of the result report.
Func Close($errorCode)
    Local $s = "s"
    If $loginCount <> 1 Then $s = ""

    Switch $errorCode
    Case "abort"
        Record("Program terminated upon request by user.")
        $resultCode = "aborted"
        $resultText = "Test Aborted by user after " & $loginCount & " successful login" & $s & "."
    Case "shutdownFailure"
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system was unable to shut down the ApplicationX application." & @CR & @CR & "Please exit ApplicationX manually and then restart this program.")
        Exit
    Case "initializationFailure"
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system was unable to initialize the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
        Exit
    Case "loginFailure"
        Record("Abnormal program termination: ApplicationX login failed.")
        $resultCode = "failed"
        $resultText = "Login Failure after " & $loginCount & " successful login" & $s & "."
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system failed to log in to the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
    Case "logoutFailure"
        Record("Abnormal program termination: ApplicationX login failed.")
        $resultCode = "failed"
        $resultText = "Logout Failure after " & $loginCount & " successful login" & $s & "."
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","The system failed to log in to the ApplicationX application." & @CR & @CR & "Please contact " & $authorName & " for support.")
    Case "none"
        Record("Test passed!")
        $resultCode = "passed"
        $resultText = "Test Passed after " & $loginCount & " successful logins!"
    Case Else
        MsgBox(270352,"ApplicationX Auto-Login Utility Error","An unknown error has occurred.")
        FileClose($logTemp)
        FileDelete(@ScriptDir & "\AXALU Logs\temp.tmp")
        FileClose($logFile)
        FileDelete(@ScriptDir & "\AXALU Logs\" & $logFileName)
        Exit
    EndSwitch

    GenerateReport()
    FileClose($logFile)
    ProcessClose("ApplicationX.exe")
    If MsgBox(262209,$scriptName,"Click OK to open the result report for this test pass.") = 1 Then Run("C:\Program Files\Internet Explorer\iexplore.exe " & @ScriptDir & "\AXALU Logs\" & $logFileName)
    Exit
EndFunc

; Prepare .htm file for inclusion of log contents, then loop through $logTemp until EOF.
; Individual lines of the actual log are sequenced in alternating row colors for ease of reading.
; Finish off by properly terminating the new result file, close $logTemp and then delete it.
Func GenerateReport()
    FileClose($logTemp)
    FileOpen(@ScriptDir & "\AXALU Logs\~temp.tmp",0)
    FileWriteLine($logFile,"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><title>"&$scriptName&"</title><style type='text/css'>body{font-family:Arial;font-size:12px;color:#2B6593;}h1{font-size:24px;color:#6FA9D5;margin:0px 0px 10px 0px;}h2{font-weight:normal;font-size:18px;color:#5E98C4;margin:10px 0px 10px 0px;}hr{color:#2B6593;margin:0px 0px 0px 0px;}.logOdd{background-color:#EEEEFE;padding:3px 5px 3px 5px;margin:0px 10px 0px 10px;}.logEven{background-color:#E8E8F8;padding:3px 5px 3px 5px;margin:0px 10px 0px 10px;}.passed{color:#00AA00;}.aborted{color:#FF9900;}.failed{color:#FF0000;}</style></head><body><h1>"&$scriptName&"</h1><hr /><h2><b>Date & Time:</b> "&$startTimestamp&"</h2><h2><b>Test Result:</b> <span class='"&$resultCode&"'>"&$resultText&"</span></h2><hr /><h2><b>Test Log:</b></h2>")
    Local $lineCounter = 1
    While 1
        $line = FileReadLine($logTemp)
        If @error = -1 Then ExitLoop
        If Mod($lineCounter,2) = 0 Then
            FileWriteLine($logFile,"<div class='logEven'>")
        Else
            FileWriteLine($logFile,"<div class='logOdd'>")
        EndIf
        If StringInStr($line,"passed") Then
            FileWriteLine($logFile,"<span class='passed'>")
        ElseIf StringInStr($line,"terminated") Then
            FileWriteLine($logFile,"<span class='aborted'>")
        ElseIf StringInStr($line,"failed") Then
            FileWriteLine($logFile,"<span class='failed'>")
        EndIf
        FileWriteLine($logFile,$line)
        FileWriteLine($logFile,"</span></div>")
        $lineCounter += 1
    WEnd
    FileWriteLine($logFile,"</body></html>")
    FileClose($logTemp)
    FileDelete(@ScriptDir & "\AXALU Logs\~temp.tmp")
EndFunc
Edited by Nahuel

Share this post


Link to post
Share on other sites
njahncke

Hey Nahuel,

Thanks very much for the suggestion. I think you're right, and that was exactly the kind of advice I was looking for: how best to leverage existing AutoIt functionality to avoid coding unnecessary solutions.

~ Norris

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  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.