Jump to content

Working Code Just looking at cleanup


Nhardel
 Share

Recommended Posts

I have a working script so I am not looking for that type of help, but I am looking at being a better coder so would love for people to take a look at my code and tell me where i went the long way around and what would be better coding practices. The program main fuction is to back up a directory.

The flow is as follows:

Start timer

map network drive based on credentials given

locate all files in base dir given in .ini file

zip files

copy zip to network drive

del network drive

at the same time give a gui log and backend running log of the process

I will also be working on a script that will read these zip files and extract only certain files back out based on user needs so any thing that I may want to do to the backup process now to help later would be great.

Thanks in advance for any suggestions :)

#Region;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=..\App Lab Backup.exe
#EndRegion;**** Directives created by AutoIt3Wrapper_GUI ****
#include <EditConstants.au3>
#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#Include <GuiStatusBar.au3>
#include <7Zip.au3>
#Include <Array.au3>
#Include <File.au3>
#include <Timers.au3>

Opt("GUIOnEventMode", 1)
#Region ### START Koda GUI section ### Form=
Global $hGUI = GUICreate("Application Labs Backup", 461, 281, -1, -1)
Global $Label_usr = GUICtrlCreateLabel("Username", 5, 20, 86, 20)
GUICtrlSetFont(-1, 12, 800, 0, "MS Sans Serif")
Global $Input_usr = GUICtrlCreateInput("", 5, 50, 121, 21)
Global $Label_pswd = GUICtrlCreateLabel("Password", 5, 100, 81, 24)
GUICtrlSetFont(-1, 12, 800, 0, "MS Sans Serif")
Global $Input_pswd = GUICtrlCreateInput("", 5, 130, 121, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
Global $btn_Backup = GUICtrlCreateButton("Backup", 340, 225, 75, 25, 0)
Global $ctlProgress = GUICtrlCreateProgress(5, 230, 265, 16)
Global $StatusBar = _GUICtrlStatusBar_Create($hGUI)
_GUICtrlStatusBar_SetSimple($StatusBar)
_GUICtrlStatusBar_SetText($StatusBar, "")
Global $ctlEdit = GUICtrlCreateEdit("", 170, 10, 275, 189, BitOR($ES_READONLY,$ES_WANTRETURN,$WS_VSCROLL))
GUICtrlSetData(-1, "")
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###


GUISetOnEvent($GUI_EVENT_CLOSE, "Gui_Exit")
GuictrlSetonevent($btn_Backup, "backup")
$Ini = @ScriptDir & "\settings.ini"
global $dir_array[1],$set_Ini


While 1
    Sleep(100)
WEnd

Func Backup()
     Local $starttime = _Timer_Init()                                           ;start timer
    GUICtrlSetData($ctlEdit, "")                                                ;Clears log for new backup
    $usr = guictrlread($Input_usr)                                              ;read username ctrl
    $pswd = guictrlread($Input_pswd)                                            ;read password ctrl
    $settings = _iniread($ini)                                                  ;read setting.ini file
    $zipFile=$settings[2][2]&"\"&@year&@Mon&@MDAY&@HOUR&@MIN&@SEC&$settings[3][2];sets filename for archive
    $backup_Folder=$settings[1][2]                                              ;sets folder to zip
    Report("",$ctlEdit)
    Report("#####################",$ctlEdit)    
    Report("#  Starting Backup Process  #",$ctlEdit)
    Report("#####################",$ctlEdit)    
    Report("",$ctlEdit)     
    Report(@MON&"\"&@MDAY&"\"&@YEAR&" "&@HOUR&":"&@MIN&":"&@SEC,$ctlEdit)       ;Log
    Report("",$ctlEdit)                                                         ;Log
    Report("Files to be archived:",$ctlEdit)                                    ;Log
    $files = RecursiveFileSearch($settings[1][2])                               ;Finds paths to files that are being archived
    Report("",$ctlEdit)                                                         ;Log
    $drive = mapdrive($settings[2][2],$usr,$pswd)                               ;Maps a drive to network storage
    Pack_Archive($zipFile,$backup_Folder)                                       ;zips up folder and saves to network
    Report("",$ctlEdit)                                                         ;Log
    delmapdrive($drive)                                                         ;Deletes mapped drive
    timer($starttime)                                                           ;Gives total time needed to backup
EndFunc

Func timer($starttime)
    $a =  _Timer_Diff($starttime)/1000
    $b = round($a,4)
    _GUICtrlStatusBar_SetText($StatusBar, "Backup required "& $b&" seconds to complete")
    report("Backup required "& $b&" seconds to complete",$ctlEdit)
    Report("",$ctlEdit) 
    $log = guictrlread($ctlEdit)
    _FileWriteLog(@ScriptDir & "\logs\"&@year&@Mon&@MDAY&".log",$log)

EndFunc
    
Func Report($_desc,$_ctrl_1="",$_ctrl_2="",$_ctrl_3="",$_ctrl_4="",$_ctrl_5="")
    dim $_ctrl_id[5]
    $_ctrl_id[0] = $_ctrl_1
    $_ctrl_id[1] = $_ctrl_2
    $_ctrl_id[2] = $_ctrl_3
    $_ctrl_id[3] = $_ctrl_4
    $_ctrl_id[4] = $_ctrl_5
    for $a = 0 to 4
        $_ctrl = $_ctrl_id[$a]
        GUICtrlSetData($_ctrl, $_desc & @CRLF, 1)
    Next
EndFunc

Func mapdrive($_dest,$_usr,$_pswd)
    Report("Mapping Drive to:",$ctlEdit)
    Report($_dest,$ctlEdit)
    $a = DriveMapAdd("*",$_dest,8,$_usr,$_pswd)
    $b = @error
    if $a = "" then
        Report("Error setting up connection to remote drive",$ctlEdit)
        Report("Error code returned: " & $b&";" &$a,$ctlEdit)
        Report("",$ctlEdit)
    Else
        Report("Success in mapping backup drive",$ctlEdit)
        Report("",$ctlEdit)
    EndIf
        return $a       
EndFunc
    
Func delmapdrive($_drive)
    Report("Attempting to delete mapped drive "& $_drive ,$ctlEdit)
    $a = DriveMapDel($_drive)   
    if $a = 1 then 
        report("Drive deleted successfully",$ctlEdit)
        Report("",$ctlEdit)
        return 1
    Else
        report("There was an error disconnecting your computer from the mapped drive: " & $_drive,$ctlEdit)
        Report("",$ctlEdit)
        return 0        
    EndIf
EndFunc

Func _iniread($ini)
    Local $aArray[1][3]
    $sect_Ini = IniReadSectionNames($ini)
    For $a = 1 to $sect_Ini[0]
        $set_Ini = IniReadSection($Ini,$sect_Ini[$a]); Read in Section
        for $b =1 to $set_Ini[0][0]
            redim $aArray[ubound($aArray)+1][3]
            $aArray[UBound($aArray)-1][0] = $sect_ini[$a]
            $aArray[UBound($aArray)-1][1] = $set_Ini[$b][0]
            $aArray[UBound($aArray)-1][2] = $set_Ini[$b][1]
        Next
    Next
    return $aArray
EndFunc

Func RecursiveFileSearch($startDir = @DesktopDir, $depth = 0, $size = 1)
 Local $RFSstring = "", $search, $STRresult
 ReDim $dir_array[$size]
   
    Local $search = FileFindFirstFile($startDir & "\*.*")
    If @error Then Return SetError(1, 0, $RFSstring)
    
;Search through all files and folders in directory
    While 1
        $next = FileFindNextFile($search)
        If @error Then ExitLoop
        
        If StringInStr(FileGetAttrib($startDir & "\" & $next), "D") Then
       ;If folder, recurse
            $RFSstring = RecursiveFileSearch($startDir & "\" & $next, $depth + 1, UBound($dir_array))
        Else
       ; Else test this filename
            $RFSstring = $startDir & "\" & $next
            $a = $set_Ini[1][1]
            $RFSstring = stringtrim($a, $RFSstring)
            Report($RFSstring,$ctlEdit)
            _ArrayAdd($dir_array, $RFSstring)
        EndIf
    WEnd
    Return $dir_array
EndFunc

Func stringtrim($trim = "",$old_string="")
    $a = StringLen($trim)
    Return stringtrimleft($old_string,$a)
EndFunc

Func Pack_Archive($ArcFile,$sFolder)
    $retResult = _7ZipSetOwnerWindowEx($hGUI, "_ARCHIVERPROC")
    If $retResult = 0 Then
        report("An Error occured",$ctlEdit)
    EndIf
    Report("Begin Archiving",$ctlEdit)
            
    $retResult = _7ZipAdd($hGUI, $ArcFile, $sFolder, 1)
            
    If @error = 0 Then
        Report("",$ctlEdit)
        report("################################",$ctlEdit)
        report("#           Archive created successfully            #",$ctlEdit)
        report("################################",$ctlEdit)
    Else
        report("An Error occured",$ctlEdit)
    
    EndIf
    GUICtrlSetData($ctlProgress, 0)
;~  GUICtrlSetData($ctlEdit, "")
    $retResult = _7ZipKillOwnerWindowEx($hGUI)
    If $retResult = 0 Then
        report("An Error occured closing setowner",$ctlEdit)
    EndIf
EndFunc

Func _ARCHIVERPROC($hWnd, $Msg, $nState, $ExInfo)
    Local $iFileSize, $iWriteSize, $iPercent = 0
    
    If $nState = 0 Then
        Local $EXTRACTINGINFO = DllStructCreate($tagEXTRACTINGINFO, $ExInfo)
        
        GUICtrlSetData($ctlEdit, DllStructGetData($EXTRACTINGINFO, "szSourceFileName") & @CRLF, 1)
    
        $iFileSize = DllStructGetData($EXTRACTINGINFO, "dwFileSize")
        $iWriteSize = DllStructGetData($EXTRACTINGINFO, "dwWriteSize")
    
        $iPercent = Int($iWriteSize / $iFileSize * 100)
    
        GUICtrlSetData($ctlProgress, $iPercent)
        Return 1
    EndIf
    
    If $nState = 2 Then GUICtrlSetData($ctlProgress, 100)
    
    Return 1
EndFunc

Func Gui_Exit()
Exit
EndFunc

you will need the 7zip udf from Rasim Got it here.

settings.ini file looks like this

[General]

Loc=C:\Documents and Settings\user\Desktop\Lab Backup

Dest=\\usandl0000\app lab backup

Filetype=.zip

Link to comment
Share on other sites

  • Moderators

You need error checking, you're using arrays, but not validating that they are in fact an array or if an error occurred. The way it is written is if you are in a 100% optimal environment, which will only happen (on your PC) lol.

Just a quick example:

Func _iniread($ini)
    Local $aArray[1][3]
    $sect_Ini = IniReadSectionNames($ini)
    For $a = 1 to $sect_Ini[0]
        $set_Ini = IniReadSection($Ini,$sect_Ini[$a]); Read in Section
        for $b =1 to $set_Ini[0][0]
            redim $aArray[ubound($aArray)+1][3]
            $aArray[UBound($aArray)-1][0] = $sect_ini[$a]
            $aArray[UBound($aArray)-1][1] = $set_Ini[$b][0]
            $aArray[UBound($aArray)-1][2] = $set_Ini[$b][1]
        Next
    Next
    return $aArray
EndFunc

Might become:

$a_returned = _IniRead("C:\AU3\ChangeLog.ini")
If Not @error Then
    _ArrayDisplay($a_returned, "Ini's Values")
EndIf

Func _IniRead($s_ini)
    Local $a_array[1][3], $a_section, $i_count
    Local $a_names = IniReadSectionNames($s_ini)
; Now we have to verify where ever called this if there was an error so we don't crash that part
    If @error Then Return SetError(1, 0, 0)
    
    For $i = 1 To $a_names[0]
        $a_section = IniReadSection($s_ini, $a_names[$i])
    ; No need to throw an error (called with non-array variable)
        If @error Then ContinueLoop
    ; We only need to Redim once, Redim takes a lot of time in a loop
    ; We should try and find the fastest most efficient method
        ReDim $a_array[$a_array[0][0] + $a_section[0][0] + 1][3]
        For $n = 1 To $a_section[0][0]
            $i_count += 1; Used to keep track of where we are in the element increment
            $a_array[$i_count][0] = $a_names[$i]
            $a_array[$i_count][1] = $a_section[$n][0]
            $a_array[$i_count][2] = $a_section[$n][1]
        Next
    ; [0][0] will have the total number of elements now
        $a_array[0][0] += $a_section[0][0]
    Next
    
    Return $a_array
EndFunc
May look like more code, but you'll see I know if something fails, and the way I incremented the array ubound will be much faster.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

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...