Greenseed

Self Update Module

5 posts in this topic

#1 ·  Posted (edited)

Include this script to your actual project and when SUP_Check() is called your script is going to download the next version and self update him self then restart.

I am sorry but i did not bother to make a UDF or a more user friendly and flexible module since i still have a lot to go on my initial project ;)

1- inside your project you include thoses line , all together and before your script actual code, beside your log system if you have one

#include "self_update.au3"
SUP_SetLogCallBack("_log") ; optional , used to send log to your allready log system if success self loggin is disable
SUP_SetCheckCallBack("SUP_DownloadProgress") ; optional , will send the % of the download in progress
SUP_Start("VALID HTTP URL To YPOUR NEW FILE","DOWNLOAD FULL FILE PATH NAME") ; mandatory

2- Now anywhere in your script you call this line to check for a newer version

$fileVersionUrl: is if your using a custom web page to send fast information on the file like version that optional, if empty will always update when check

$parentGui="": the self updated will create a gui with a progress bar and try to attach it self to the $parentGui , that optional

SUP_Check($fileVersionUrl="",$parentGui="")

3- to check if your script has just restarted after a update

if IsDeclared("updateComplete") then
ConsoleWrite("Update Complete Sucess Bravo!")
endif

File: SUP_SelfUpdate.au3

The script can be compiled alone for debug purpose , look for 1 line to uncomment inside the script if running alone

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=e:SelfUpdate.exe
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include-once

;*************** Line to be use inside your own project************
;
;~ #include "self_update.au3"
;~ SUP_SetLogCallBack("_log")
;~ SUP_SetCheckCallBack("SUP_DownloadProgress")
;~ SUP_Start("e:SelfUpdate_FF.exe",@TempDir&"SelfUpdate_FF.exe")
;
;*******************************************************************


Global $SUP_LOGS_CALL[1] = [0]
Global $SUP_DOWN_CALL[1] = [0]
Global $SUP_URL
Global $SUP_FILE
Global $SUP_INFO_FILE
Global $SUP_DEST_FILE
Global $SUP_PID

;**************Uncomment to self debug that script alone*************
;~ SUP_Start(@ScriptDir&"SelfUpdate.exe",@TempDir&"SelfUpdate.exe")
;********************************************************************

Func SUP_Start($SUPURL,$SUPFILE)
$SUP_URL = $SUPURL
$SUP_FILE = $SUPFILE
$SUP_INFO_FILE = $SUP_FILE&".info"
if $CmdLine[0] > 0 Then
Switch $CmdLine[1]
case "update"
SUP_InitInfo()
if Not ProcessWaitClose($SUP_PID,30) Then
SUP_Log("UPDATE - Could not complete since """&$SUP_DEST_FILE&""" will not close",false)
Exit
EndIf
if Not FileCopy($SUP_FILE,$SUP_DEST_FILE,1) Then
SUP_Log("UPDATE - Could not copy the new file to """&$SUP_DEST_FILE&"""",false)
Exit
EndIf
Run($SUP_DEST_FILE&" updatecomplete")
exit
case "updatecomplete"
SUP_Delete()
;~ SUP_Log("UPDATE - Complete sucess")
Assign("updateComplete",true,2)
EndSwitch
;~ Else
;~ SUP_Check() ;for testing to be remove when linked with main
EndIf
;~ sleep(5000)
EndFunc

Func SUP_InitInfo()
local $data = FileRead($SUP_INFO_FILE)
$data = StringSplit($data,"|")
if $data[0] <> 2 Or $data[1]="" or $data[2] = "" Then
SUP_Log("UPDATE - Info File is invalid")
sleep(4000)
exit
EndIf
$SUP_PID = $data[1]
$SUP_DEST_FILE = $data[2]
EndFunc
Func SUP_Delete()
FileDelete($SUP_FILE)
FileDelete($SUP_INFO_FILE)
EndFunc

Func SUP_SetCheckCallBack($funcCallBack)
ReDim $SUP_DOWN_CALL[$SUP_DOWN_CALL[0]+2]
$SUP_DOWN_CALL[0] += 1
$SUP_DOWN_CALL[$SUP_DOWN_CALL[0]] = $funcCallBack
EndFunc
Func SUP_Check($fileVersionUrl="",$parentGui="")
;~ if $RUN then return
local $version = FileGetVersion(@AutoItExe)
local $nextVersion = "always update"
if $fileVersionUrl <> "" Then $nextVersion = BinaryToString(InetRead($fileVersionUrl,1))
;~ SUP_Log($version&" "&$nextVersion)
if $nextVersion = "" Or $version = $nextVersion Then
SUP_Log("UPDATE - No new version found")
Return
EndIf
SUP_Log("UPDATE - New version found")
SUP_Log("UPDATE - Downloading version "&$nextVersion)
local $size = InetGetSize($SUP_URL,1)
FileDelete($SUP_FILE)
local $handle = InetGet($SUP_URL,$SUP_FILE,1,1)
local $byteRead, $error = false
#include <WindowsConstants.au3>
GUICreate("ProgressBar",200,30,-1,-1,BitOR($WS_MINIMIZEBOX,$WS_DLGFRAME,$WS_POPUP,$WS_GROUP,$WS_CLIPSIBLINGS), BitOR($WS_EX_TOOLWINDOW,$WS_EX_TOPMOST),$parentGui)
local $progress = GUICtrlCreateProgress(0,0,200,30)
GUISetState(@SW_SHOW)
local $pct
do
Sleep(250)
$byteRead = InetGetInfo($handle, 0)
if @error Then
$error = true
ExitLoop
EndIf
GUICtrlSetData($progress,$byteRead*100/$size)
$pct = Round($byteRead*100/$size,2)
SUP_Log("UPDATE - Percent done: "&$pct)
If $SUP_DOWN_CALL[0] > 0 Then
For $i = 1 to $SUP_DOWN_CALL[0]
Call($SUP_DOWN_CALL[$i],$pct)
Next
EndIf
Until InetGetInfo($handle, 2)
GUIDelete()
if $error or Not InetGetInfo($handle,3) Then
InetClose($handle)
SUP_Log("UPDATE - Downloading next version failed")
SUP_Delete()
Return
EndIf
InetClose($handle)
FileDelete($SUP_INFO_FILE)
FileWrite($SUP_INFO_FILE,@AutoItPID&"|"&@ScriptFullPath)
SUP_Log("UPDATE - Exiting to complete update")

Run($SUP_FILE&" update")
if @error Then
SUP_Log("UPDATE - Unable to open the new file")
SUP_Delete()
Return
endif
SUP_Log("UPDATE - Exiting")
sleep(1000)
Exit
EndFunc

Func SUP_SetLogCallBack($funcCallBack)
ReDim $SUP_LOGS_CALL[$SUP_LOGS_CALL[0]+2]
$SUP_LOGS_CALL[0] += 1
$SUP_LOGS_CALL[$SUP_LOGS_CALL[0]] = $funcCallBack
EndFunc
Func SUP_Log($msg,$useCallBack=true)
If $useCallBack And $SUP_LOGS_CALL[0] > 0 Then
For $i = 1 to $SUP_LOGS_CALL[0]
Call($SUP_LOGS_CALL[$i],$msg)
Next
Return
EndIf
if @Compiled Then MsgBox(0,"Message",$msg)
ConsoleWrite($msg&@CRLF)
EndFunc
Edited by Greenseed

GreenseedMCSE+I, CCNA, A+Canada, QuebecMake Love Around You.

Share this post


Link to post
Share on other sites



This is great, very nice, thx )

Share this post


Link to post
Share on other sites

This looks good, it may solve a problem for me. Thanks for posting.

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Did somebody ever got this working? Tried like posted above, a small progressbar appears for some miliseconds - but the script is not updated. Or any other alternatives? The Compiled Exe should update itself without asking if a new version is available (wether via web or path, but prefered via filepath)

Edited by AIstarter

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

4 hours ago, AIstarter said:

Did somebody ever got this working? Tried like posted above, a small progress appears for some milliseconds - but the script is not updated. Or any other alternatives? The Compiled Exe should update itself without asking if a new version is available (whether via web or path, but preferred via file path)

Here is a simple function I use to update my application loader. It looks for a file at 2 locations, if one is unavailable it uses a backup. Then creates a batch file, downloads the new file with a different name, loads the batch, ends the process of the original file, renames and reloads. All pretty seamless. Doesn't offer a progress bar, but happens so fast you wouldn't see it anyway. I'm sure it needs clean up and consolidation, but it works, so I've left it as is.

 

Func Self_Update()
    If Not IsDeclared("update_path") Then
        Global $Path1 = FileGetShortName("\\network\path\to\updated\exe")
        Global $Path2 = FileGetShortName("c:\alernate\location\for\update\if\network\unavailable")
        If Not FileExists($Path1 & "\Application loader.exe") Then
            If Not FileExists($Path2 & "\Application loader.exe") Then
                MsgBox(48, "Update Error!", "Unable to locate an update file!")
            Else
                $Update_Path = $Path2
            EndIf
        Else
            $Update_Path = $Path1
        EndIf
        $NewVersion = FileGetVersion($Update_Path & "\Application loader.exe")
        $OldVersion = FileGetVersion(@ScriptFullPath)
        $Results = _StringCompareVersions($OldVersion, $NewVersion)
        If $Results = "-1" Then
            SplashTextOn("Updating Loader", "Please wait... This may take a few moments.", "400", "100", "-1", "-1", 50, "", "", "")
            Sleep(1000)
            FileCopy($Update_Path & "\Application loader.exe", @ScriptFullPath & ".new")
            Local $BatchPath = @ScriptDir & '\update.bat'
            $FileData = "@echo off" & @CRLF & _
                    "ping localhost -n 2 > nul" & @CRLF & _
                    ":loop" & @CRLF & _
                    'del /Q "' & @ScriptFullPath & '"' & @CRLF & _
                    'if exist "' & @ScriptFullPath & '" goto loop' & @CRLF & _
                    'move "' & @ScriptFullPath & '.new" "' & @ScriptFullPath & '"' & @CRLF & _
                    'start /B "Loading" "' & @ScriptFullPath & '"' & @CRLF & _
                    'del /Q "' & $BatchPath & '"' & @CRLF & _
                    "exit"
            FileWrite($BatchPath, $FileData)
            FileSetAttrib($BatchPath, "+H")
            Run($BatchPath, "", @SW_HIDE)
            SplashOff()
            Write2Log("Updated Application to version " & $NewVersion) ; - write to log file, remove if you don't need this.
            Exit
        EndIf
    EndIf
EndFunc   ;==>Self_Update

You will also need the attached UDF by @PeteF to make the version compare I use work.

StringCompareVersions.au3

Edited by zone97
1 person likes this

 

Spoiler

WinSizer 2.1 (01/04/2017) - Download - [ Windows Layout Manager ]
Folder+Program (12/23/2016) - Download - [ USB Shortcut Creator ]

 

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

    • Simpel
      By Simpel
      Hi, I created a gui with date field but formatted as time in HH:mm. It always shows "now-time". Even if I try to set it with GUICtrlSetData.
      #include <DateTimeConstants.au3> #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> Example() Func Example() GUICreate("My GUI get date", 200, 200, 800, 200) Local $idDate = GUICtrlCreateDate("", 20, 20, 100, 20, $DTS_TIMEFORMAT) ; to select a specific default format Local $sStyle = "HH:mm" ; Just display hours and minutes <<<<<<<<<<<<<<<<<<<<<<<<<<<< GUICtrlSendMsg($idDate, $DTM_SETFORMATW, 0, $sStyle) ConsoleWrite(GUICtrlRead($idDate) & @CRLF) GUICtrlSetData($idDate, "00:00") ConsoleWrite(GUICtrlRead($idDate) & @CRLF) GUISetState(@SW_SHOW) ; Loop until the user exits. While GUIGetMsg() <> $GUI_EVENT_CLOSE WEnd MsgBox($MB_SYSTEMMODAL, "Time", GUICtrlRead($idDate)) EndFunc ;==>Example How can I set the time field with another time and how can this field be set blank?
      Regards, Conrad
    • Vijaya7890
      By Vijaya7890
      Hi...
      I am trying to add a record in Binary Table in an MSI file.
      As Binary table has two fields/columns Name &Data , I am giving any string for Name(column 1) and streaming binary data from a VBS file into Data(column 2) .
      I have tried with VB script and it is working fine,
      Here is the VB Script file
      Dim Installer Dim Database Dim View Dim Record Dim query query="INSERT INTO `Binary` (`Name`, `Data`) VALUES ('NewBlob', ?)" Set Installer = CreateObject("WindowsInstaller.Installer") Set Record = Installer.CreateRecord(1) Record.SetStream 1, "C:\Users\Admin\Desktop\coder\CA_Test.vbs" Set Database = Installer.OpenDatabase("C:\Users\Admin\Desktop\7z920.msi", 1) Set View = Database.OpenView(query) View.Execute Record Database.Commit when i tried the same thing in autoit it is not working and it is not giving any syntax error.
      AutoIt file: 
      #include <File.au3> $idVarInput_CAName="CA_Test" $filepath="C:\Users\Admin\Desktop\coder\CA_Test.vbs" $idVarInput_MSIPath="C:\Users\Admin\Desktop\7z920.msi" $value="?" Local $Query = "INSERT INTO Binary(Name,Data) VALUES('" & $idVarInput_CAName & "','" & $value & "')" $oInstaller = ObjCreate("WindowsInstaller.Installer") $oRec=$oInstaller.CreateRecord(1) $r=$oRec.SetStream(1,$filepath) $oDB = $oInstaller.OpenDataBase($idVarInput_MSIPath,1) $oView = $oDB.OpenView($Query) $oView.Execute($oRec) $oDB.commit() Please Help!
      Thanks...
    • Nnet
      By Nnet
      Hello, Im using GUICtrlCreateListView to make table with items. But when it is new item with same first column a want just update allready existing row. Its posible?

      I cant figure it, if its better use other funkcion pls. tell me.
      Thank
    • wakillon
      By wakillon
      AutoIt&SciTEUpdater v1.0.2.1.au3

       

       
      External files are included in script.
      If UAC Enable, Run as Admin the first time.
      Previous downloads : 611

      Source : AutoItAndSciTEUpdater v1.0.2.1.au3

      Executable : AutoIt&SciTEUpdater.exe
       
      For never miss AutoIt (Release/Beta) and SciTE4AutoIt3 updates.
    • WoodGrain
      By WoodGrain
      Hi guys,
      I'm using this startup example to allow the program menu to insert an option to "AutoStart" the script. What I'd like to do is update the checkbox of the menu item after they click it to then reflect the "AutoStart" state (on or off).
      How do I update the menu on the event someone clicks the menu option? The registry is updating correctly, and if I close and re-run the script the menu is updated, but not in the same script execution. I wasn't sure with TrayItemSetState for my "Func AutoStart()" Function what the "controlID" was. I tried 0 through to 3 and "AutoStart" text. Perhaps this is where I'm going wrong?
      ; Add custom tray icon menu #NoTrayIcon #include <MsgBoxConstants.au3> #include <TrayConstants.au3> Opt("TrayMenuMode", 3) Opt("TrayOnEventMode", 1) #include '_Startup.au3' TrayCreateItem("AutoStart") TrayItemSetOnEvent(-1, "AutoStart") If _StartupRegistry_Exists() Then TrayItemSetState(-1, $TRAY_CHECKED) Else TrayItemSetState(-1, $TRAY_UNCHECKED) EndIf TrayCreateItem("About") TrayItemSetOnEvent(-1, "About") TrayCreateItem("") TrayCreateItem("Exit") TrayItemSetOnEvent(-1, "ExitScript") TraySetOnEvent($TRAY_EVENT_PRIMARYDOUBLE, "About") TraySetState($TRAY_ICONSTATE_SHOW) ; ################## ; ### OTHER CODE ### ; ################## Func About() MsgBox(0,"About","etc") EndFunc Func AutoStart() If _StartupRegistry_Exists() Then _StartupRegistry_Uninstall() TrayItemSetState("AutoStart", $TRAY_UNCHECKED) Else _StartupRegistry_Install() TrayItemSetState("AutoStart", $TRAY_CHECKED) EndIf EndFunc Func ExitScript() Exit EndFunc Thanks!