31290

Restart a function

4 posts in this topic

Hi guys, 

Hope you are fine today :)

I'm trying to restart a function by calling it back in the script:

Here's my code so far:

Func f_VPN()
    $iInputBox = InputBox("Password", "Please Enter the User's password.")
    If @Error = 1 Then 
            GUICtrlSetState($fVPN, $GUI_UNCHECKED)
    Else
        ShellExecute("C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe")
        $hVPN = WinWait("Cisco AnyConnect Secure Mobility Client", "Ready to connect")
        ControlClick($hVPN, "", "Button1")
        $hVPN1 = WinWait("Cisco AnyConnect | SEE VPN", "Cancel")
        ControlSetText($hVPN1, "", "Edit2", @Username)  
        Sleep(250)
        ControlSetText($hVPN1, "", "Edit3", $iInputBox)
        Sleep(250)
        ControlClick($hVPN1, "", "Button1")
        Sleep(5000)
        If ControlGetText("Cisco AnyConnect Secure Mobility Client", "", "Static2") = "Login Failed" Then 
            ControlClick("Cisco AnyConnect Secure Mobility Client", "", "Button4")
            WinClose($hVPN)
            f_VPN()
        Else
        ShellExecute("C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe")
        If ControlGetText("Cisco AnyConnect Secure Mobility Client", "", "Static2") = "Connected To SEE VPN." Then ControlClick("Cisco AnyConnect Secure Mobility Client", "", "Button1")
        Sleep(1000)
        WinClose("Cisco AnyConnect Secure Mobility Client", "")
        ProcessClose("vpnui.exe")
        ; ProcessClose("explorer.exe") <<< TO UNCOMMENT
        IniWrite($oIniFile, "LaptopChkBox", "VPN", "1")
        EndIf
    EndIf   
EndFunc

I'd like to the function to be restarted in the case the password provided is not correct. 
I've googled many things but nothing very relevant.

Any ideas over here?

Thanks :)

-31290

 


~~~ Doom Shall Never Die, Only The Players ~~~

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

How about breaking things up into nice separate functions so your program flow is much easier to control/steer?

Something like this (with a lot of pseudocode that you can fill in yourself :) ):

Global $MAX_PWD_FAIL_COUNT = 3

; main script
If Not fireItUp() Then
    MsgBox(16, "error", "something went wrong, you probably got an earlier error about this")
Else
    MsgBox(64, "all good", "vpn logged in!")
EndIf

Exit


Func fireItUp()

    $clientGui = startClient()
    If Not $clientGui Then
        MsgBox(64, "failure to start client", "failed")
        Return False
    EndIf

    $failCount = 0
    While Not loginClient($clientGui)
        $failCount += 1
        If $failCount > $MAX_PWD_FAIL_COUNT Then
            MsgBox(16, "failure to login client", "failed " & $MAX_PWD_FAIL_COUNT & " times! Cancelling.")
            ; break down gui, kill process, whatever
            cleanupAfterFailedLogin()
            ; Return False, so the calling code can tell that stuff went wrong
            Return False
        EndIf
    WEnd

    ; If we get here, we know that everything was ok
    cleanupAfterCorrectLogin()

    Return True ;
EndFunc   ;==>fireItUp

Func startClient()
    ; Start client
    ; Return $hVPN1 if success, False if failure
EndFunc   ;==>startClient

Func loginClient($clientGui)
    ; Do login stuff using $clientGui
    ; Wait for window to reflect success (then return True) or failure (then return False)
EndFunc   ;==>loginClient

Func cleanupAfterCorrectLogin()
    cleanupGeneral()
    ; ini write, log write, whatever specific for handling correct login
EndFunc   ;==>cleanupAfterCorrectLogin

Func cleanupAfterFailedLogin()
    cleanupGeneral()
    ; ini write, log write, whatever specific for handling failed login
EndFunc   ;==>cleanupAfterFailedLogin

Func cleanupGeneral()
    ; gui process/windows close, ini write etc., anything that needs to be done whether everything worked or not
EndFunc   ;==>cleanupGeneral

 

Edited by SadBunny

Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

Thanks for your input SadBunny.

Thing is that this "VPN" function (like many other function present in one file) is called when  a tech is clicking on a checkbox coming from a main GUI. Then  the tech have to enter the end user's password so the VPN connection can be tested. 

 

$gMainGUI = GUICreate("SEE CHECKLISTS", 333, 500)
    GUISetBkColor($Color_White)
    GUISetFont(8.5, 700, 0)
    ;GUICtrlCreatePic($sResources & "SAClogo.jpg", 75, 27, 183, 59)
    ;GUICtrlCreateLabel("SEE CHECKLISTS", 120, 114)
    GUICtrlSetColor(-1, 0x800080)
    ;GUICtrlCreateSeperator(0, 0, 135, 2, 390)
    GUICtrlCreateLabel("[ Current Computer name: " & @ComputerName & " ]", 50, 151, 324, 17)    
    GUICtrlSetColor(-1, $COLOR_RED)
    ;GUICtrlCreateSeperator(0, 0, 181, 2, 390)
    $fVPN = GUICtrlCreateCheckbox("Test the VPN connection", 5, 391)
    GUICtrlSetTip(-1, "Open Cisco and login with user's credentials")
    GUICtrlSetOnEvent($fVPN, "f_VPN")
    GUISetOnEvent($GUI_EVENT_CLOSE, "_exit")
    GUISetState(@SW_SHOW)

If login is OK, then go on with script. But if Login failed, VPN process test has to be launched one or two more times. That's why I really need the VPN function to be recalled within the function.


~~~ Doom Shall Never Die, Only The Players ~~~

Share this post


Link to post
Share on other sites

I believe the issue is with your Window naming, I can get it to work fine, if I change the ControlGetText and ControlClick "Title" and "ClassNN" after the "Sleep(5000)" line, I also removed the WinClose as I couldn't see the use of this.  I'm not sure why you can't just get the Tech to type the Password into the VPN Client though, especially since the Password window stays open after it fails.  You could just check once VPN has successfully logged in before updating your ini file.

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

  • Similar Content

    • wakillon
      By wakillon
      SciTE Hopper : Jump to Any line by one click and many other helpfull functions !


      As Ashalshaikh suggested me after leaving me the task to continue >SciTE Hopper, i open a new Topic about it.
      It will be more easy for futures updates.

      Many helpfull functions in contextual menu.
      SciTE Hopper is now multipurpose.
      • Color Catcher added
      • BinaryToAu3Kompressor added
      • TinyAu3Search replaced by StringFinder
      • RegJumper added
      • Edit With SciTE added (available in Options)
      • SpecialCharactersViewer added (available in Tray menu)
      New Contextual Menu :

      For a right Click on a function :

      • Copy function name
      • Insert a function header
      • Cut function
      • Copy function
      • Delete function
      • Create a variables List
      • Remove usseless Blank lines
      • Remove Debug lines ( all lines starting with ConsoleWrite or _ArrayDisplay )
      • Set AutoIt Code Layout
      • Remove Comments

      For entire script :

      • Create a functions List
      • Create a variables List
      • Remove usseless Blank lines
      • Remove Debug lines ( all lines starting with ConsoleWrite or _ArrayDisplay )
      • Set AutoIt Code Layout
      • Remove Comments
      • ( Open in SciTE a ) Duplicate of current Script in Temp Dir
      • ( Open in SciTE a ) Duplicate of current Script in Same Dir
      • Explore Parent Script Folder
      • Copy Script name
      • Copy Script path
      • Find Unused Functions
      • Find Unused Variables
      • Set all functions in alphabetic order.( func headers and regions ( in fact, all lines between functions ) are not supported.)

      SciTE Editor New Contextual Menu if SciTE Hopper is added ( in Options ) to SciTE Editor :
      when you made a selection in SciTE Editor you can :

      • Open a Reg Key in Regedit using RegJumper
      • Open a Url in your default Browser
      • Search on google in your default Browser
      • Search on AutoIt Website in your default Browser
      Now Can be added to windows start (minimized)
      Options are available by Tray Menu.
      A double click on tray icon will open clipboard content to SciTE Editor ( Handy when you have copied some code from your browser )

      How to proceed for add SciTE Hopper to SciTE Editor :
      Run Scite Editor, run Scite Hopper ( compiled! ) go to Options and select Add/Remove to SciTE Tab. then click on Add button and it's done !
      Right click on SciTE Editor and choose SciTE Hopper in Contextual Menu for run it when you need it !
      Update of 07 Dec 2017
      TinyAu3Search is replaced by StringFinder

      Previous downloads : 1287
      Script and compiled version are available in the download section
       
      Thanks to Ashalshaikh, Melba23, Th3 MMA, Alzri2, taitel, Manadar, taz742, Yashield, Authenticity, Xenobiologist for their help
      and asdf8 for his >Includes Helper and azjio for his >FileSearch.

      Hope it help you and happy Scripting !

       
    • 0Ethan0
      By 0Ethan0
      Ahoy Autoit Community!
      After many trials and errors I am unable to solve a problem I am facing and would appreciate any kind of input or better yet a solution 
      The Premise: An embeded slideshow viewer that runs after double-clicking an item in a ListView (each item will generate a different slideshow images).
      The Setup: GUI with a ListView Control and a simple exit button.
      The Issue: Once double clicked the slide plays however the GUI "locks"/non responsive until the slide is over. Same thing if I click on the "Test" button.
      The Culprit: I believe since it's in the images loop it can't accept any other commands until that loop is over.
      The Wish: I want to be able to use the GUI functions (selecting other items, clicking on button etc.) while the slideshow plays.
      The Code (stripped and simplified as much as I could):
      #include <GuiListView.au3> #include <File.au3> #include <GDIPlus.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt("GUIOnEventMode", 1) HotKeySet("{Esc}", "_Exit") Global $c=0 Global $ssGDI[3], $ssGraphic[2], $ssImage Global Const $bg_color = "000000" Global Const $ssW = 480, $ssH = 320 Global $aFiles = _FileListToArrayRec("d:\testStage\", "*.jpg;*.png;*.bmp;*.gif;*.JPG;*.PNG;*.BMP;*.GIF", $FLTAR_FILES, $FLTAR_NORECUR ,$FLTAR_SORT ,$FLTAR_FULLPATH ) $guiW = 1200 $guiH = 726 $mainWindow = GUICreate("Slideshow Viewer", $guiW, $guiH, -1, -1, $WS_POPUP) $Button1 = GUICtrlCreateButton("Exit", 0, 0, 50, 50) GUICtrlSetOnEvent($Button1, "_Exit") $Button1 = GUICtrlCreateButton("Test", 60, 0, 50, 50) GUICtrlSetOnEvent($Button1, "Test") Global $ListView = GUICtrlCreateListView("Entry Name|Category", 5, 75, 195, 280) _GUICtrlListView_SetColumnWidth ($ListView, 0, 100) _GUICtrlListView_SetColumnWidth ($ListView, 1, 100) GUICtrlSendMsg($ListView, $LVM_SETEXTENDEDLISTVIEWSTYLE, $LVS_EX_GRIDLINES, $LVS_EX_GRIDLINES) GUICtrlSendMsg($ListView, $LVM_SETEXTENDEDLISTVIEWSTYLE, $LVS_EX_FULLROWSELECT, $LVS_EX_FULLROWSELECT) GUICtrlCreateListViewItem("Name 1|Category 1", $ListView) GUICtrlCreateListViewItem("Name 2|Category 2", $ListView) screenshotWidgetInit($ssW,$ssH, 690, 100) GUISetState(@SW_SHOW, $mainWindow) GUIRegisterMsg($WM_NOTIFY, "WM_Notify_Events") While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE _Exit() EndSwitch WEnd Func Test() For $k = 1 To UBound($aFiles) - 1 screenshotWidgetTransition($aFiles[$k]) Next EndFunc Func ListView_Click() ConsoleWrite("Left Click") EndFunc Func ListView_DoubleClick() ConsoleWrite("Double Left Click") Test() EndFunc Func WM_Notify_Events($hWndGUI, $MsgID, $wParam, $lParam) #forceref $hWndGUI, $MsgID, $wParam Local $tagNMHDR, $event, $hwndFrom, $code $tagNMHDR = DllStructCreate("int;int;int", $lParam) If @error Then Return $event = DllStructGetData($tagNMHDR, 3) Select Case $wParam = $ListView Select Case $event = $NM_CLICK ListView_Click () Case $event = $NM_DBLCLK ListView_DoubleClick () EndSelect EndSelect Return $GUI_RUNDEFMSG EndFunc Func screenshotWidgetTransition($image, $delay = 0, $speed = 1, $sleep = 2000) Local $a, $d = $c, $iX, $iY $ssImage = _GDIPlus_ImageLoadFromFile($image) $iX = _GDIPlus_ImageGetWidth($ssImage) $iY = _GDIPlus_ImageGetHeight($ssImage) $FDesktop=$ssH/$ssW $Fact =1 If $iX > $ssW And $FDesktop > ($iY/$iX) Then $Fact=$ssW/$iX ElseIf $iY > $ssH Then $Fact=$ssH/$iY EndIf $H1 = Round(($Fact * $iY),0) $W1 = Round(($Fact * $iX),0) _GDIPlus_GraphicsDrawImageRect($ssGraphic[$d], $ssImage,($ssW - $W1)/2, ($ssH - $H1) / 2,$W1,$H1) WinSetTrans($ssGDI[$d], "", 0) WinSetOnTop($ssGDI[$d], "", 1) For $a = 0 To 254 Step $speed WinSetTrans($ssGDI[$d], "", $a) Sleep($delay) Next WinSetTrans($ssGDI[$d], "", 254) WinSetOnTop($ssGDI[Not ($d)], "", 0) WinSetTrans($ssGDI[Not ($d)], "", 0) _GDIPlus_GraphicsClear($ssGraphic[Not ($d)]) $c = 1 - $d _GDIPlus_ImageDispose ($ssImage) ; very important to realease the pics Sleep($sleep) EndFunc ;==>screenshotWidgetTransition Func screenshotWidgetInit($ssW,$ssH,$ssX,$ssY) $ssGDI[2] = GUICreate("", $ssW, $ssH, $ssX, $ssY, $WS_POPUP, $WS_EX_MDICHILD, $mainWindow) $ssGDI[0] = GUICreate("", $ssW, $ssH, 3, 3, $WS_POPUP, $WS_EX_MDICHILD, $ssGDI[2]) $ssGDI[1] = GUICreate("", $ssW, $ssH, 3, 3, $WS_POPUP, $WS_EX_MDICHILD, $ssGDI[2]) ; GUISetBkColor("0x" & $bg_color, $ssGDI[2]) GUISetState(@SW_SHOW, $ssGDI[2]) GUISetState(@SW_SHOW, $ssGDI[0]) GUISetState(@SW_SHOW, $ssGDI[1]) WinSetTrans($ssGDI[0], "", 0) WinSetTrans($ssGDI[1], "", 0) _GDIPlus_Startup() $ssGraphic[0] = _GDIPlus_GraphicsCreateFromHWND($ssGDI[0]) $ssGraphic[1] = _GDIPlus_GraphicsCreateFromHWND($ssGDI[1]) _GDIPlus_GraphicsClear($ssGraphic[0], "0xFF" & $bg_color) _GDIPlus_GraphicsClear($ssGraphic[1], "0xFF" & $bg_color) EndFunc ;==>screenshotWidgetInit Func _Exit() _GDIPlus_ImageDispose($ssImage) _GDIPlus_GraphicsDispose($ssGraphic[0]) _GDIPlus_GraphicsDispose($ssGraphic[1]) GUIDelete($ssGDI[0]) GUIDelete($ssGDI[1]) GUIDelete($ssGDI[2]) _GDIPlus_Shutdown() Exit EndFunc ;==>_Exit I hope someone can shed light on this; perhaps a different approach is needed?
      Thank you in advance!
      P.S.
      The script is patched from different scripts of different users in the forum - thank you again users!
    • Patryk
      By Patryk
      Dear Colleagues,
      I have no idea how to refer to style.display in my loop. There is a button like: 
      <input name="ctl00$bodyPlaceholder$btnFecharProcessamento" class="button" id="bodyPlaceholder_btnFecharProcessamento" style="display: none;" onclick="FecharJanelaProcessamento();return false;" type="submit" value="Fechar"> I want it to be clicked as soon as button's style change from style="display: none;" to  style= ="display: inline-block;" 
      This is what I got, but it's not working...
      Func GetButtons() $oButtons = _IEGetObjByName($oForm,"ctl00$bodyPlaceholder$btnFecharProcessamento",-1) $i = 0 While $i <> 1 For $oBtn In $oButtons If _IEFormElementGetValue($oBtn) = "Fechar" And $oBtn.document.style.display = "display: inline-block;" Then $i = 1 _IEAction($oBtn, "focus") _IEAction($oBtn, "click") ExitLoop EndIf Next WEnd EndFunc  
      I will really appreciate if you could help me with these loop!
    • mati
      By mati
      Hi,
      I wonder if
      AutoIt3Wrapper_run_debug_mode = Y can include run information about functions which are called within the main code. So far I noticed in the console that the function itself is called but no specific run information from  inside the function is provided. Is there a chance to show the entire debug log including functions in the console?
      I furthermore noticed a stop of information when a loop is entered. What could be the reason for that?
       
      Thanks for help.
    • Nareshm
      By Nareshm
      How to repeat my script when my control class does not match ?
       
      My Script : winActivate ( " PS :: Version - 2.2.0.0  - [PS Bill]")                   ControlClick ( "PS :: Version - 2.2.0.0  - [PS Bill]", "", "[NAME:btnSavebyFP]")                   ControlSend(" PS :: Version - 2.2.0.0  - [PS Bill]", "", "[NAME:btnSavebyFP]", "{enter}")                   WinActive ("Verification Number Entry ::")                   ControlClick("Next >", "","[NAME:btnNext]") ;if   >>>> Control <<<<  does not match repeat my script, ;if match exit script  

      Class:    WindowsForm734a
      Instance:    15
      ClassnameNN:    WindowsForm34a15
      Name:    BillPrint
      Advanced (Class):    [NAME:BillPrint]
      ID:    7875
      Text:    
      Position:    39, 310
      Size:    1221, 306
      ControlClick Coords:    745, 20
      Style:    0x56010000
      ExStyle:    0x00000000
      Handle:    0x00000000000C0468