Aphotic

Simple SQL Query Tool

7 posts in this topic

#1 ·  Posted (edited)

Hey Guys,

I've been using AutoIT for about 3 years now, lurking the forums, scouring documentation, and creating things relevant to my job function.

I work entry level IT and utilizing AutoIT has earned me much respect in the workplace. I made my first application on the level of sharing with the community that has no relevance to my company other than the data that is used with it.

Our tech's were using development software to make simple pre-written queries. I was made aware of the process in order to assist in automating it. We found that the software they were using was being sunset in our environment so they'd need a replacement; and upon me realizing that they only needed a simple query tool, decided to 'homegrow' a simple app and save some hefty licensing fees.

I built in some versatility to the SQL database you can connect to but it is only tested working with a Sybase 15 system (note the example connection string).

I'd love to hear some suggestions and critique. I'm sure there are some editing functionalities that I could implement into the query edit box that I haven't bothered looking at. (other than CTRA+A to select all)

 

Thanks guys!

#include <WindowsConstants.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <GuiListView.au3>
#include <File.au3>
#include <Crypt.au3>
#include <Date.au3>

$oMyError = ObjEvent("AutoIt.Error","MyErrFunc")
Local $unique = "SQL-Query-Tool" ;TO ALLOW ONLY ONE INSTANCE OF THE TOOL
If WinExists($unique) Then
   MsgBox(0,'Duplicate Process', 'This script is already running....' & @CRLF & "If the window is not visible, terminate the process from Task Manager" & @CRLF & 'This instance will terminate after clicking OK')
   Exit
EndIf
AutoItWinSetTitle($unique)

Local $fResized = False, $GUIs, $temp, $Qlist[0][3], $x, $selQ[2], $guics[4]
Local $conName, $conStr, $conPW, $selC, $selConn, $sqlErr
Local $fh

Local $readme = "You may delete this entry if desired once other ." & @CRLF & _
"Although it is prefaced with 'zz' for sorting" & @CRLF & _
@CRLF & _
"-Select a Query from the drop-down" & @CRLF & _
"-Note: changing selection will not lose" & @CRLF & _
"        changes made during this session" & @CRLF & _
"-Click Run Query to produce results" & @CRLF & _
@CRLF & _
"-Select from 'Query Options' to create new," & @CRLF & _
"        edit name, save, and delete queries" & @CRLF & _
@CRLF & _
"-Click 'Connection Settings' to change" & @CRLF & _
"        server settings"

$conName = IniReadSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Name")
If @error = 1 Then
   DirCreate(@AppDataDir & "\SQL-Query-Tool\")
   IniWrite(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Name", "1", "Connection_Name_Placeholder")
   IniWrite(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-String", "1", "Connection_String_Placeholder")
   IniWrite(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Password", "1", "Connection_Password_Placeholder")
EndIf

$selConn = IniRead(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Selected", "Number", "Placeholder")
If $selConn = "Placeholder" Then
   DirCreate(@AppDataDir & "\SQL-Query-Tool\")
   IniWrite(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Selected", "Number", "1")
   $selConn = 1
EndIf

$temp = _FileListToArray(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\")
If @error = 1 Or @error = 4 Then
   DirCreate(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\")
   FileWrite(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\zz_Readme.txt", $readme)
   $temp = _FileListToArray(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\")
EndIf

QueryLoad(False)
$selQ[0] = $Qlist[1][0]

Local $GUI = GUICreate("Simple SQL Query Tool", 260, 320, -1, -1, BitOR($WS_SIZEBOX,$WS_MINIMIZEBOX));, @DesktopWidth-275, @DesktopHeight-500)
GUIRegisterMsg($WM_SIZE, 'MY_WM_SIZE')
Local $querysel = GUICtrlCreateCombo("", 5, 5, 155, 25, $CBS_DROPDOWNLIST)
GUICtrlSetData($querysel, $Qlist[0][1], $Qlist[1][0])
GUICtrlSetResizing(-1, 552)
Local $queryopt = GUICtrlCreateCombo("Query Options", 165, 5, 90, 20, $CBS_DROPDOWNLIST)
GUICtrlSetData($queryopt, "Save to File|New|Edit Name|Delete|Open Query Folder")
GUICtrlSetResizing(-1, 552)
Local $tab = GUICtrlCreateTab(5, 35, 235, 200)
$qtab = GUICtrlCreateTabItem("            Query            ")
Local $query = GuiCtrlCreateEdit("", 10, 60, 240, 170)
GUICtrlSetFont(-1, 9, 0, 0, "Lucida Console")
GUICtrlSetData($query, $Qlist[1][1])
$rtab = GUICtrlCreateTabItem("            Results            ")
Local $result = GuiCtrlCreateEdit("", 10, 80, 240, 150)
GUICtrlSetFont(-1, 9, 0, 0, "Lucida Console")
Local $status = GUICtrlCreateLabel("Last Ran: None", 15, 62, 500)
GUICtrlSetResizing(-1, 802)
GUICtrlCreateTabItem("")
Local $run = GUICtrlCreateButton("Run Query", 5, 270, 130, 25)
GUICtrlSetResizing(-1, 584)
Local $settings = GUICtrlCreateButton("Connection Settings", 140, 270, 115, 25)
GUICtrlSetResizing(-1, 584)

Local $consel = GUICtrlCreateCombo("", 5, 5, 390, 25, $CBS_DROPDOWNLIST)
GUICtrlSetResizing(-1, 802)
Local $newc = GUICtrlCreateButton("New", 400, 5, 40, 20)
GUICtrlSetResizing(-1, 802)
Local $edic = GUICtrlCreateButton("Edit", 445, 5, 40, 20)
GUICtrlSetResizing(-1, 802)
Local $delc = GUICtrlCreateButton("Delete", 490, 5, 40, 20)
GUICtrlSetResizing(-1, 802)
Local $test = GUICtrlCreateButton("Test Connection", 540, 5, 95, 20)
GUICtrlSetResizing(-1, 802)
Local $return = GUICtrlCreateButton("Return to Query", 640, 5, 95, 20)
GUICtrlSetResizing(-1, 802)
Local $divider = GUICtrlCreateLabel("",-5,30,760,3,BitOR($SS_SUNKEN,$WS_BORDER))
GUICtrlSetResizing(-1, 802)
Local $cnamel = GUICtrlCreateLabel("Connection Name:", 15, 45)
GUICtrlSetResizing(-1, 802)
Local $cname = GUICtrlCreateInput("", 110, 41, 200, 20)
GUICtrlSetResizing(-1, 802)
Local $cstringl = GUICtrlCreateLabel("                Connection String" & @CRLF & _
   "Replace your password with *PW*.   For example:" & @CRLF & _
   "Provider=ASEOLEDB;User ID=-USERID-;Password=*PW*;Data Source=-SERVER-:-PORT-;Initial Catalog=-DatabaseName-" & @CRLF & _
   "If you need assistance with your specific connection string try using:     https://www.connectionstrings.com/", 5, 70, 740, 60)
GUICtrlSetResizing(-1, 802)
Local $cstring = GUICtrlCreateInput("", 10, 125, 725, 20)
GUICtrlSetResizing(-1, 802)
Local $pwl = GUICtrlCreateLabel("Password:", 10, 165)
GUICtrlSetResizing(-1, 802)
Local $pw = GUICtrlCreateInput("", 65, 161, 340, 20, BitOR($ES_PASSWORD, $ES_AUTOHSCROLL))
GUICtrlSetResizing(-1, 802)
Local $savc = GUICtrlCreateButton("Save", 480, 161, 100, 20)
GUICtrlSetResizing(-1, 802)
Local $canc = GUICtrlCreateButton("Cancel", 600, 161, 100, 20)
GUICtrlSetResizing(-1, 802)

Guimod("SETTINGS", $GUI_HIDE+1)
GuiMod('SETTINGS-ENTRY', $GUI_DISABLE)
$selC = $selConn
GuiMod('RELOAD-CON')

Local $hSelAll = GUICtrlCreateDummy()
Dim $AccelKeys[1][2] = [["^a", $hSelAll]]
GUISetAccelerators($AccelKeys, $GUI)

GUISetState(@SW_SHOW)

Local $nMsg
While 1
   $nMsg = GUIGetMsg()
   Switch $nMsg               ;Checks if a button has been pressed
   Case $querysel
      $selQ[1] = GUICtrlRead($querysel)
      If $selQ[0] <> $selQ[1] Then QuerySelect()
      GUICtrlSetState($qtab, $GUI_SHOW)
   Case $queryopt
      Switch GUICtrlRead($queryopt)
      Case "Save to File"
         $fh = FileOpen(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & GuiCtrlRead($querysel) & ".txt", 2)
         FileWrite($fh, GuiCtrlRead($query))
         $Qlist[_ArraySearch($Qlist, GuiCtrlRead($querysel), 0, 0, 0, 0, 1, 0)][1] = GuiCtrlRead($query)
         $Qlist[_ArraySearch($Qlist, GuiCtrlRead($querysel), 0, 0, 0, 0, 1, 0)][2] = False
         GUICtrlSetData($qtab, "            Query            ")
      Case "New"
         $temp = InputBox("New Query Name","Enter a name for your new query." & @CRLF & "Please be aware only letters, numbers, underscores, and spaces are allowed." & @CRLF & "Symbols will be removed.", "", "", Default, Default, Default, Default, 0, $GUI)
         $temp = StringRegExpReplace($temp, "[^A-Za-z0-9 _]", "")
         If $temp <> "" And _ArraySearch($Qlist, $temp, 0, 0, 0, 0, 1, 0) = -1 Then
            FileWriteLine(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & $temp & ".txt", "--First Line Placeholder")
            QueryLoad()
            GUICtrlSetData($querysel, "")
            GUICtrlSetData($querysel, $QList[0][1], $temp)
            $selQ[1] = GUICtrlRead($querysel)
            If $selQ[0] <> $selQ[1] Then QuerySelect()
         Else
            MsgBox(0,'Invalid Input','Invalid name entered. (Symbols and Duplicate Names are not allowed)', 0, $GUI)
         EndIf
      Case "Edit Name"
         $temp = InputBox("Edit Query name","Enter a new name for your query." & @CRLF & "Please be aware only letters, numbers, underscores, and spaces are allowed." & @CRLF & "Symbols will be removed.", GuiCtrlRead($querysel))
         $temp = StringRegExpReplace($temp, "[^A-Za-z0-9 _]", "")
         If $temp <> "" And _ArraySearch($Qlist, $temp, 0, 0, 0, 0, 1, 0) = -1 Then
            FileMove(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & GuiCtrlRead($querysel) & ".txt", @AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & $temp & ".txt")
            $selQ[0] = $temp
            QueryLoad()
            GUICtrlSetData($querysel, "")
            GUICtrlSetData($querysel, $QList[0][1], $temp)
            $selQ[1] = GUICtrlRead($querysel)
            If $selQ[0] <> $selQ[1] Then QuerySelect()
         Else
            MsgBox(0,'Invalid Input','Invalid name entered. (Symbols and Duplicate Names are not allowed)', 0, $GUI)
         EndIf
      Case "Delete"
         If UBound($Qlist) = 2 Then
            MsgBox(0,'Deletion Error','You may not delete the only saved query', 0, $GUI)
         Else
            If MsgBox(4, 'Confirm Deletion', "Are you sure you want to delete the query named: " & @CRLF & GUICtrlRead($querysel), 0, $GUI) = 6 Then
                  FileDelete(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & GuiCtrlRead($querysel) & ".txt")
               QueryLoad()
               GUICtrlSetData($querysel, "")
               GUICtrlSetData($querysel, $QList[0][1], $Qlist[1][0])
               $selQ[1] = GUICtrlRead($querysel)
               $selQ[0] = $selQ[1]
               GUICtrlSetData($query, $Qlist[1][1])
            EndIf
         EndIf
      Case "Open Query Folder"
         ShellExecute(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\")
      EndSwitch
      GUICtrlSetData($queryopt, 'Query Options', 'Query Options')
   Case $run
      GuiMod("RUNNING", $GUI_DISABLE)
      ToolTip("Executing SQL query, please wait...")
      $sqlCon = ObjCreate("ADODB.Connection")
      $sqlCon.Mode = 16  ; shared
      $sqlCon.CursorLocation = 3 ; client side cursor
      Local $connString = StringReplace(GuiCtrlRead($cstring), "*PW*", GuiCtrlRead($pw))
      $sqlCon.Open($connString)
      If @error Then
         MsgBox(0, "Fail", "Failed to connect to the database")
      Else
         $sqlCon.CommandTimeout = 60
         GUICtrlSetData($result, ProcessQuery(GuiCtrlRead($query)))
         GUICtrlSetState($rtab , $GUI_SHOW)
         GuiCtrlSetData($status, "Last Ran: " & GuiCtrlRead($querysel) & " - " & StringRight(_NowCalc(), 8))
      EndIf
      ToolTip("")
      GuiMod("RUNNING", $GUI_ENABLE)
   Case $settings
      ToolTip("Loading...")
      $selC = $selConn
      GuiMod('MAIN', $GUI_HIDE)
      GuiMod('RELOAD-CON')
      GuiMod('SETTINGS', $GUI_SHOW)
      ToolTip("")
   Case $consel
      If GUICtrlRead($consel) <> $selC Then
         $selC = _ArraySearch($conName, GUICtrlRead($consel), 0, 0, 0, 0, 1, 1)
         GUICtrlSetData($cname, $conName[$selC][1])
         GUICtrlSetData($cString, $conStr[$selC][1])
         GUICtrlSetData($pw, StringEncrypt(False, $conPW[$selC][1]))
         $selC = GUICtrlRead($consel)
      EndIf
   Case $newc
      GuiMod('SETTINGS-SELECT', $GUI_DISABLE)
      GuiMod('SETTINGS-ENTRY', $GUI_ENABLE)
      GuiCtrlSetData($consel, '*New-Connection-Entry*', '*New-Connection-Entry*')
      GuiCtrlSetData($cname, '')
      GuiCtrlSetData($cString, '')
      GuiCtrlSetData($pw, '')
      $selC = -1
   Case $edic
      GuiMod('SETTINGS-SELECT', $GUI_DISABLE)
      GuiMod('SETTINGS-ENTRY', $GUI_ENABLE)
      $selC = GUICtrlRead($consel)
      _ArrayDisplay($conName, "2")
      $selC = _ArraySearch($conName, $selC, 0, 0, 0, 0, 1, 1)
      GuiCtrlSetData($cname, $conName[$selC][1])
      $conName[$selC][1] &= "*"
      GuiCtrlSetData($cString, $conStr[$selC][1])
      GuiCtrlSetData($pw, StringEncrypt(False, $conPW[$selC][1]))
   Case $delc
      If UBound($conName) = 2 Then
         MsgBox(0,'Error','You can not delete the only connection setting.', 0, $GUI)
      Else
         $selC = GuiCtrlRead($consel)
         If MsgBox(4, 'Confirm Deletion', 'Are you sure you want to delete the connection: ' & $selC, 0, $GUI) = 6 Then
            ToolTip('Loading...')
            $selC = _ArraySearch($conName, $selC, 0, 0, 0, 0, 1, 1)
            $conName[$selC][1] = '*!*BLANK*!*'
            $conStr[$selC][1] = '*!*BLANK*!*'
            $conPW[$selC][1] = '*!*BLANK*!*'
            IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Name", $conName)
            IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-String", $conStr)
            IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Password", $conPW)
            GuiMod('RELOAD-CON')
            ToolTip('')
         EndIf
      EndIf
   Case $savc
      If GuiCtrlRead($cname) = "" Or _ArraySearch($conName, GuiCtrlRead($cname), 0, 0, 0, 0, 1, 1) > -1 Then
         MsgBox(0,'Invalid Input',"You can't have a blank connection name or two connections with the same name", 0, $GUI)
      Else
         ToolTip("Loading...")
         If $selC = -1 Then
            For $i = 1 To UBound($conName)-1
               If $conName[$i][1] = '*!*BLANK*!*' Then
                  $selC = $i
                  $conName[$i][1] = GuiCtrlRead($cname)
                  $conStr[$i][1] = GuiCtrlRead($cstring)
                  $conPW[$i][1] = StringEncrypt(True, GuiCtrlRead($pw))
                  ExitLoop
               ElseIf $i = UBound($conName)-1 Then
                  $selC = UBound($conName)
                  _ArrayAdd($conName, UBound($conName) & "|" & GuiCtrlRead($cname))
                  _ArrayAdd($conStr, UBound($conStr) & "|" & GuiCtrlRead($cstring))
                  _ArrayAdd($conPW, UBound($conPW) & "|" & StringEncrypt(True, GuiCtrlRead($pw)))
               EndIf
            Next
         Else
            $conName[$selC][1] = GuiCtrlRead($cname)
            $conStr[$selC][1] = GuiCtrlRead($cstring)
            $conPW[$selC][1] = StringEncrypt(True, GuiCtrlRead($pw))
         EndIf
         IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Name", $conName)
         IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-String", $conStr)
         IniWriteSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Password", $conPW)
         GuiMod('SETTINGS-SELECT', $GUI_ENABLE)
         GuiMod('SETTINGS-ENTRY', $GUI_DISABLE)
         GuiMod('RELOAD-CON')
         ToolTip('')
      EndIf
   Case $canc
      ToolTip("Loading...")
      GuiMod('SETTINGS-SELECT', $GUI_ENABLE)
      GuiMod('SETTINGS-ENTRY', $GUI_DISABLE)
      GuiMod('RELOAD-CON')
      ToolTip('')
   Case $test
      $sqlCon = ObjCreate("ADODB.Connection")
      $sqlCon.Mode = 16  ; shared
      $sqlCon.CursorLocation = 3 ; client side cursor
      Local $connString = StringReplace(GuiCtrlRead($cstring), "*PW*", GuiCtrlRead($pw))
      $sqlCon.Open($connString)
      If @error Then
         MsgBox(0, "Fail", "Failed to connect to the database")
      Else
         MsgBox(0, "Success", "Successfully connected to the database")
      EndIf
   Case $return
      $selConn = _ArraySearch($conName, $selC, 0, 0, 0, 0, 1, 1)
      IniWrite(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Selected", "Number", $selConn)
      GuiMod('SETTINGS', $GUI_HIDE)
      GuiMod('MAIN', $GUI_SHOW)
   Case $hSelAll
      _SelectAllTextInEdit()
   Case $GUI_EVENT_CLOSE
      Exit
   EndSwitch
   If $fResized Then
      GuiMod('RESIZE')
      $fResized = False
   EndIf
   If $guics[0] = True Then _Input_Check($cname)
WEnd

Func QuerySelect()
   Local $oldp = _ArraySearch($Qlist, $selQ[0], 0, 0, 0, 0, 1, 0)
   Local $old = GuiCtrlRead($query)
   If $Qlist[$oldp][1] <> $old Then
      $Qlist[$oldp][1] = $old
      $Qlist[$oldp][2] = True
   EndIf
   Local $newp = _ArraySearch($Qlist, $selQ[1], 0, 0, 0, 0, 1, 0)
   GUICtrlSetData($query, $Qlist[$newp][1])
   $selQ[0] = $selQ[1]
   If $Qlist[$newp][2] = False Then
      GUICtrlSetData($qtab, "            Query            ")
   Else
      GUICtrlSetData($qtab, "    Query (unsaved)   ")
   EndIf
EndFunc

Func QueryLoad($reload = True)
   Local $qFiles = _FileListToArray(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\")
   Local $tQlist[UBound($qFiles)][3]
   Local $selT
   $tQlist[0][0] = $qFiles[0]
   $tQlist[0][1] = ""
   For $i = 1 To $tQlist[0][0]
      $tQlist[$i][0] = StringTrimRight($qFiles[$i], 4)
      If $reload Then
         $selT = _ArraySearch($Qlist, $tQlist[$i][0], 0, 0, 0, 0, 1, 0)
         If $selT > -1 Then
            $tQlist[$i][1] = $Qlist[$selT][1]
            $tQlist[$i][2] = $Qlist[$selT][2]
         Else
            $tQlist[$i][1] = FileRead(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & $qFiles[$i])
            $tQlist[$i][2] = False
         EndIf
      Else
         $tQlist[$i][1] = FileRead(@AppDataDir & "\SQL-Query-Tool\Saved-Queries\" & $qFiles[$i])
         $tQlist[$i][2] = False
      EndIf
      $tQlist[0][1] &= StringTrimRight($qFiles[$i], 4)
      If $i < $tQlist[0][0] Then $tQlist[0][1] &= "|"
   Next
   $Qlist = $tQlist
EndFunc

Func ProcessQuery($input)
   Local $resultO = $sqlCon.Execute($input)
   If Not @error Then
      Local $resultT = ""
      Local $recordE = 0
      Local $resultA[2][0]
      Local $i, $z
      While $recordE = 0 and IsObj($resultO)
         Redim $resultA[2][0]
         For $oField In $resultO.Fields
            Redim $resultA[2][UBound($resultA, 2)+1]
            $resultA[1][UBound($resultA, 2)-1] = $oField.Name
         Next
         ReDim $resultA[UBound($resultA)+1][UBound($resultA, 2)]
         While Not $resultO.EOF
            ReDim $resultA[UBound($resultA)+1][UBound($resultA, 2)]
            $i = 0
            For $oField in $resultO.Fields
               $resultA[UBound($resultA)-1][$i] = StringStripWS(StringStripWS($oField.Value, 1), 2)
               $i += 1
            Next
            $resultO.MoveNext
         WEnd
         For $i = 0 To UBound($resultA, 2)-1
            $z = 0
            For $x = 1 To UBound($resultA)-1
               If StringLen($resultA[$x][$i]) > $z Then $z = StringLen($resultA[$x][$i])
            Next
            $resultA[0][$i] = $z
         Next
         For $i = 0 To UBound($resultA, 2)-1
            $z = ""
            For $x = 1 To $resultA[0][$i] + 4
               $z &= "-"
            Next
            $resultA[2][$i] = $z
         Next
         For $x = 1 To UBound($resultA)-1
            For $i = 0 To UBound($resultA, 2)-1
               $resultT &= $resultA[$x][$i]
               For $z = StringLen($resultA[$x][$i]) To $resultA[0][$i] + 4
                  $resultT &= " "
               Next
            Next
            $resultT &= @CRLF
         Next
         $resultT &= @CRLF & "Total Lines Returned: " & UBound($resultA)-3 & @CRLF
         $resultT &= "__________________________________________________________" & @CRLF & @CRLF & @CRLF
         $resultO = $resultO.NextRecordset
         $recordE = @error
      WEnd
      $resultO.Close
   Else
      Local $resultT = $sqlErr
   EndIf
   Return $resultT
EndFunc

Func GuiMod($action, $toggle = 0)
   Switch $action
      Case 'RESIZE'
         If ($GUIs[2] < 266 or $GUIs[3] < 306) And $guics[0] = False Then WinMove($GUI, '', $GUIs[0], $GUIs[1], 276, 336)
         GUICtrlSetPos($tab, 5, 35, $GUIs[2] - 25, $GUIs[3] - 106)
         GUICtrlSetPos($query, 10, 60, $GUIs[2] - 36, $GUIs[3] - 136)
         GUICtrlSetPos($result, 10, 80, $GUIs[2] - 36, $GUIs[3] - 156)
         GUICtrlSetPos($result, 10, 80)
      Case 'MAIN'
         GUICtrlSetState($querysel, $toggle)
         GUICtrlSetState($queryopt, $toggle)
         GUICtrlSetState($tab, $toggle)
         GUICtrlSetState($query, $toggle)
         GUICtrlSetState($result, $toggle)
         GUICtrlSetState($status, $toggle)
         GUICtrlSetState($run, $toggle)
         GUICtrlSetState($settings, $toggle)
      Case 'SETTINGS'
         If $toggle = $GUI_SHOW Then
            GUISetStyle(BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_SYSMENU))
            $GUIs = WinGetPos($GUI)
            $guics[0] = True
            $guics[1] = $GUIs[2]
            $guics[2] = $GUIs[3]
            $guics[3] = $GUIs[0]
            WinMove($GUI, '', 25, $GUIs[1], 750, 221)
         ElseIf $toggle = $GUI_HIDE Then
            GUISetStyle(BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_SYSMENU, $WS_SIZEBOX))
            $guics[0] = False
            WinMove($GUI, '', $guics[3], Default, $guics[1], $guics[2])
         ElseIf $toggle = $GUI_HIDE+1 Then
            $toggle -= 1
         EndIf
         GUICtrlSetState($consel, $toggle)
         GUICtrlSetState($newc, $toggle)
         GUICtrlSetState($edic, $toggle)
         GUICtrlSetState($delc, $toggle)
         GUICtrlSetState($test, $toggle)
         GUICtrlSetState($return, $toggle)
         GUICtrlSetState($divider, $toggle)
         GUICtrlSetState($cnamel, $toggle)
         GUICtrlSetState($cname, $toggle)
         GUICtrlSetState($cstringl, $toggle)
         GUICtrlSetState($cstring, $toggle)
         GUICtrlSetState($pwl, $toggle)
         GUICtrlSetState($pw, $toggle)
         GUICtrlSetState($savc, $toggle)
         GUICtrlSetState($canc, $toggle)
      Case 'SETTINGS-SELECT'
         GUICtrlSetState($consel, $toggle)
         GUICtrlSetState($newc, $toggle)
         GUICtrlSetState($edic, $toggle)
         GUICtrlSetState($delc, $toggle)
         GUICtrlSetState($test, $toggle)
         GUICtrlSetState($return, $toggle)
      Case 'SETTINGS-ENTRY'
         GUICtrlSetState($cnamel, $toggle)
         GUICtrlSetState($cname, $toggle)
         GUICtrlSetState($cstringl, $toggle)
         GUICtrlSetState($cstring, $toggle)
         GUICtrlSetState($pwl, $toggle)
         GUICtrlSetState($pw, $toggle)
         GUICtrlSetState($savc, $toggle)
         GUICtrlSetState($canc, $toggle)
      Case 'RUNNING'
         GUICtrlSetState($querysel, $toggle)
         GUICtrlSetState($queryopt, $toggle)
         GUICtrlSetState($query, $toggle)
         GUICtrlSetState($tab, $toggle)
         GUICtrlSetState($result, $toggle)
         GUICtrlSetState($run, $toggle)
         GUICtrlSetState($settings, $toggle)
      Case 'RELOAD-CON'
         $conName = IniReadSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Name")
         $conStr = IniReadSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-String")
         $conPW = IniReadSection(@AppDataDir & "\SQL-Query-Tool\settings.ini", "Connection-Password")
         Local $sC = $conName
         _ArraySort($sC, 0, 1, 0, 1)
         GUICtrlSetData($consel, "")
         If $conName[$selC][1] <> "*!*BLANK*!*" Then
            GuiCtrlSetData($cname, $conName[$selC][1])
            GuiCtrlSetData($cString, $conStr[$selC][1])
            GuiCtrlSetData($pw, StringEncrypt(False, $conPW[$selC][1]))
            $selC = $conName[$selC][1]
         Else
            For $i = 1 To UBound($sC)-1
               If $sC[$i][1] <> '*!*BLANK*!*' Then
                  GuiCtrlSetData($cname, $sC[$i][1])
                  GuiCtrlSetData($cString, $conStr[$sC[$i][0]][1])
                  GuiCtrlSetData($pw, StringEncrypt(False, $conPW[$sC[$i][0]][1]))
                  $selC = $sC[$i][1]
                  ExitLoop
               EndIf
            Next
         EndIf
         For $i = 1 To UBound($sC)-1
            If $sC[$i][1] <> '*!*BLANK*!*' Then GUICtrlSetData($consel, $sC[$i][1], $selC)
         Next
   EndSwitch
EndFunc

Func MY_WM_SIZE($hWnd, $Msg, $wParam, $lParam)
   $GUIs = WinGetPos($GUI)
   $fResized = True
   Return $GUI_RUNDEFMSG
EndFunc  ;==>MY_WM_SIZE

Func StringEncrypt($bEncrypt, $sData, $sPassword = 'SQL')
   If $sData = "" Then Return ''
    _Crypt_Startup() ; Start the Crypt library.
    Local $sReturn = ''
    If $bEncrypt Then ; If the flag is set to True then encrypt, otherwise decrypt.
        $sReturn = _Crypt_EncryptData($sData, $sPassword, $CALG_RC4)
    Else
        $sReturn = BinaryToString(_Crypt_DecryptData($sData, $sPassword, $CALG_RC4))
    EndIf
    _Crypt_Shutdown() ; Shutdown the Crypt library.
    Return $sReturn
EndFunc   ;==>StringEncrypt

Func _Input_Check($hInput)
   Local $sText = GUICtrlRead($hInput)
   If StringRegExp($sText, "[^A-Za-z0-9 _]") Then GUICtrlSetData($hInput, StringRegExpReplace($sText, "[^A-Za-z0-9 _]", ""))
EndFunc

Func _SelectAllTextInEdit();will make select all text in any focused edit
    Local $theHandle = _WinAPI_GetFocus()
    Local $TheClass = _WinAPI_GetClassName($theHandle)
    If $TheClass = 'Edit' Then _GUICtrlEdit_SetSel($theHandle, 0, -1)
EndFunc

Func MyErrFunc()
  $HexNumber=hex($oMyError.number,8)
  $sqlErr = "We intercepted a COM Error !" & @CRLF & @CRLF & _
             "err.description is: "    & @TAB & $oMyError.description    & @CRLF & _
             "err.windescription:"     & @TAB & $oMyError.windescription & @CRLF & _
             "err.number is: "         & @TAB & $HexNumber              & @CRLF & _
             "err.lastdllerror is: "   & @TAB & $oMyError.lastdllerror   & @CRLF & _
             "err.scriptline is: "     & @TAB & $oMyError.scriptline     & @CRLF & _
             "err.source is: "         & @TAB & $oMyError.source         & @CRLF & _
             "err.helpfile is: "       & @TAB & $oMyError.helpfile       & @CRLF & _
             "err.helpcontext is: "    & @TAB & $oMyError.helpcontext
  SetError(1)  ; to check for after this function returns
Endfunc

 

Edited by Aphotic

Share this post


Link to post
Share on other sites



Hi.

Interesting.

here is my list what you can do:

1.

do not post user name and host to forum

2.

make bigger GuiCtrlCreateEdit

 

3.

use:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7
#Tidy_Parameters=/sort_funcs /reel

at top of your script

and fix this 

Z:\TOOLs\Macro\FORUM\___FORUM -- z forum\Simple_SQL_Query_Tool.au3 - 0 error(s), 12 warning(s)

4.

What you are checking with this error ?

Are you sure here about this comment in MsgBox ?

$sqlCon.Open($connString)
            $sqlCon.CommandTimeout = 60
            If @error Then
                MsgBox(0, "Fail", "Failed to connect to the database")

5.

look in my signature or just click here:

specially to the attached _sql.au3

 

6.

search on the forum all my post about SQL and ADO.

 

7.

if you have some spare time look also here:

Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * How to post code on the forum * UDF-Spec Questions

 

Best regards,

mLipok

 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

... and beware of SQL attacks and injections!

1 person likes this

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Hi.

Interesting.

here is my list what you can do:

1.

do not post user name and host to forum  Removed, thank you

2.

make bigger GuiCtrlCreateEdit   The window is re-sizable, it launches small because I will be automating the tool further in another script

 

3.

use:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7
#Tidy_Parameters=/sort_funcs /reel

at top of your script

and fix this  Not sure what this refers to but I get the concept and will search around and do so, thank you

4.

What you are checking with this error ?

Are you sure here about this comment in MsgBox ? Meant to check for a failed connection, I moved the Timeoutsetting to only if it connects successfully, thank you

$sqlCon.Open($connString)
            $sqlCon.CommandTimeout = 60
            If @error Then
                MsgBox(0, "Fail", "Failed to connect to the database")

5.

look in my signature or just click here: Will follow-up when I have more time, thank you

specially to the attached _sql.au3

 

6.

search on the forum all my post about SQL and ADO. Will follow-up when I have more time, thank you

 

7.

if you have some spare time look also here: Will follow-up when I have more time, thank you

Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * How to post code on the forum * UDF-Spec Questions

 

Best regards,

mLipok

 

 

... and beware of SQL attacks and injections! I have very limited SQL experience, I'll need to research and follow-up, thank you

 

 

 

Responses in bold, I'm out for now but will definitely look into those points that I wasn't able to, thanks a bunch!

 

Edited by Aphotic

Share this post


Link to post
Share on other sites

You are welcome.

mLipok

 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

#6 ·  Posted

hi,

I was wondering how this script works if dataset contains "blob" data? I have blob data in the mysql db and i was how i could show that data back to the user? The data stored is jpg, png, gif.

did you ever address the points above from the other folks? If so, how?

thanks! 

 

Share this post


Link to post
Share on other sites

#7 ·  Posted

You might get ideas from this post, even it uses SQLite as the engine, the display of BLOBs pictures can be transposed into your framework.

 


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

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

    • AndyS19
      By AndyS19
      I have code that does a WMI SQL query to find all defined printers, and I want to parse the returned object in several places.  However, after parsing it the first time, all other times fail to find any printer objects.
      Here is my test code:
      test() Func test() Local $oPrinters, $oPrinter, $err, $cnt, $oP, $query $query = "SELECT * FROM Win32_Printer" $oPrinters = doQuery($query) $err = @error LogMsg("+++: $err = " & $err & ", isObj($oPrinters) = " & IsObj($oPrinters)) If ($err == 0) Then LogMsg("FIRST LOOP") ; <=== FIRST LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") LogMsg("SECOND LOOP") ; <== SECOND LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") EndIf EndFunc ;==>test Func doQuery($sQuery, $lnum = @ScriptLineNumber) #forceref $lnum LogMsg("+++:" & $lnum & ": doQuery(" & '"' & $sQuery & '"' & ") entered") Local $oWMIService, $oResults, $errstr Local $wbemFlags = BitOR(0x20, 0x10) ; $wbemFlagReturnImmediately and wbemFlagForwardOnly $oWMIService = ObjGet("winmgmts:\\" & "localhost" & "\root\CIMV2") If (IsObj($oWMIService)) Then $oResults = $oWMIService.ExecQuery($sQuery, "WQL", $wbemFlags) If (IsObj($oResults)) Then LogMsg("+++: doQuery() returns @error = 0, Good: returning the object") Return (SetError(0, 0, $oResults)) ;;; Good: return the object Else $errstr = "" _ & "WMI Query failed." & @CRLF _ & "This is the query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") LogMsg("+++: doQuery() returns @error = 1") Return (SetError(1, 0, $errstr)) ; Error: Query faled EndIf Else $errstr = "" _ & "WMI Output" & @CRLF _ & "No WMI Objects Found for class: " & @CRLF _ & "Win32_PrinterDriver" & @CRLF _ & "using this query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") MsgBox(0, "ERROR", $errstr) ; Error: Cannot get $oWMIService object Exit (1) EndIf EndFunc ;==>doQuery Func LogMsg($msg, $lnum = @ScriptLineNumber) ConsoleWrite("+++:" & $lnum & ": " & $msg & @CRLF) EndFunc ;==>LogMsg Parsing the returned $oPrinters object shows 5 printers:
      +++:15: FIRST LOOP +++:18: +++: isObj($oP) = 1 +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft XPS Document Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft Office Document Image Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Fax<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG7100 series Printer WS<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG6100 series Printer WS<== +++:24: +++: Found 5 printers Parsing it again, shows no printers:
      +++:26: SECOND LOOP +++:29: +++: isObj($oP) = 1 +++:35: +++: Found 0 printers  
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning guys
      I was trying to not open another post, writing here my little issue, but seems that no one cares about, and so, I'm opening another post
      What I'm trying to do, is detect the event close sent from the virtual keyboard.
      Why?
      Because, I have an application which, when I set the focus on a textbox, if the virtual keyboard does not exist, then it is created, else, it's not created
      But, everytime I try to close the virtual keyboard, the focus remains on the textbox, and another $EN_FOCUS event it's launched and detected from my WM_COMMAND, and so, the virtual keyboard is opened again. 
      How can I solve this little "issue"? 
      I was trying to detect the event sent from the virtual keyboard, storing the handle of it in a variable, and setting:
      GUISetOnEvent($GUI_EVENT_CLOSE, "CloseVK", $hVirtualKeyboard) without any result.
      Can someone please help me?
      Thanks  
      EDIT:
      Here I'd like to see @Melba23, @water, @Danyfirex...
       
    • zetaimmersion
      By zetaimmersion
      I have 2 items (a field box and a bypass checkbox). every time the box is checked i need the field to become writable. unchecked is read only displaying some text.
      this is as far as i got as I am stuck at making it read/write toggle
      #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <EditConstants.au3> #include <WindowsConstants.au3> $hGUI = GUICreate("Test", 500, 500) Global $hCombo = GUICtrlCreateInput("", 10, 10, 200, 20, BitOR($ES_AUTOHSCROLL,$ES_READONLY)) GUICtrlSetBkColor($hCombo,0xe7e5e5) Global $cbox = GUICtrlCreateCheckbox ("", 40,50,10,20) GUICtrlSetState($cbox, $GUI_Unchecked) GUISetState() Global $sCurrCombo = "" While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $cbox If GUICtrlRead($cbox) <> $sCurrCombo Then $sCurrCombo = GUICtrlRead($cbox) GUICtrlSetStyle ($hCombo, $SS_LEFTNOWORDWRAP) GUICtrlSetBkColor($hCombo,0xFFFFFF) MsgBox(0, "Choice", "PLease enter the text") EndIf EndSwitch WEnd  
    • dascondor
      By dascondor
      So I having issues with this GUI/Listview. My main GUI works like it needs to but the ListView GUIs don't. The exit buttons do not work on them and om have a hard time getting them to work. And I'm trying to make the  listview GUI resizeable. But I'm not sure how to fix either of these issues any thoughts.
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <File.au3> #include <ScreenCapture.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> #include <Array.au3> #include <GuiListView.au3> #include <GuiImageList.au3> #include <ListviewConstants.au3> #include 'MultiPing.au3' Opt("GUIOnEventMode", 1) #Region ;Declares ; Reads text file for the base list of IP's Global $aBase_IPlist = _FileReadToArray_mod(".\IP_List.txt") Global $replace2 = "Second" Global $replace3 = "Thrid" ;Global $userdata1 = GUICtrlRead($data1) ;Global $userdata2 = GUICtrlRead($data2) Global $savefolder = "C:\Users\" Global $paths = "\Desktop\PingChecks" Global $1stpaths = "\~~~Store" Global $2ndpaths = "~~~" Global $results = FileExists($savefolder & @UserName & $paths) ;Global $foldercheck = FileExists($savefolder & @UserName & $paths & $1stpaths & $userdata1 & $userdata2 & $2ndpaths) ;Global $savefile = "C:\Users\" & @UserName & "\Desktop\PingChecks\~~~Store" & $userdata1 & $userdata2 & "~~~\" #EndRegion ;Declares #Region ### START Koda GUI section ### Form= $IPMonkey = GUICreate("IP Monkey", 573, 254, -1, -1) GUISetIcon("C:\Users\Dlex\Pictures\monkeyicon.ico", -1) GUISetFont(16, 800, 0, "Arial") GUISetBkColor(0xFFFFFF) GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MINIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MAXIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_RESTORE, "SpecialEvents") $data1 = GUICtrlCreateInput("1", 184, 120, 89, 32, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER)) GUICtrlSetColor(-1, 0x000000) $data2 = GUICtrlCreateInput("23", 280, 120, 89, 32, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER)) GUICtrlSetColor(-1, 0x000000) $GOButton = GUICtrlCreateButton("GO", 80, 192, 75, 25) GUICtrlSetFont(-1, 10, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0x00FF00) GUICtrlSetTip(-1, "Runs A Live Continuous Ping" & @CRLF & _ "Until Told Other Wise") GUICtrlSetOnEvent(-1, "GOButtonClick") $quickscan = GUICtrlCreateButton("Quick Scan", 224, 192, 107, 25) GUICtrlSetFont(-1, 12, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFFFF00) GUICtrlSetOnEvent(-1, "quickscanClick") GUICtrlSetTip(-1, "Quickly Scans, Then Saves" & @CRLF & _ "Results In Your 'PingChecks' " & @CRLF & _ "Folder Under Your Store Number Folder") Global $exitbutton = GUICtrlCreateButton("Exit", 416, 192, 75, 25) GUICtrlSetFont(-1, 12, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFF0000) GUICtrlSetTip(-1, "What Do You Think This Button Does?") GUICtrlSetOnEvent(-1, "exitbuttonClick") $titlebar = GUICtrlCreateLabel("IP Monkey", 16, 120, 107, 28) GUICtrlSetColor(-1, 0x000000) $Pic1 = GUICtrlCreatePic("C:\Users\Dlex\Pictures\monkeyicon-0.jpg", 16, 16, 100, 100) GUICtrlSetOnEvent(-1, "Pic1Click") $infobutton = GUICtrlCreateButton("?", 536, 8, 27, 25) GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFF8000) GUICtrlSetTip(-1, "Unsure what to do?" & @CRLF & _ "This will get give you " & @CRLF & _ "the help for IP Monkey") GUICtrlSetOnEvent(-1, "infobuttonClick") $Whatstorelabel = GUICtrlCreateLabel("What Store?", 208, 56, 130, 28) GUICtrlSetColor(-1, 0x000000) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### #Region ;ping gui ; ------ pinger GUI ------------------- Global $StopPing = 0 Local $Win_X = 1200, $Win_Y = 880 ; dimension of window Global $PingGui = GUICreate("IP Monkey", $Win_X, $Win_Y, -1, -1) GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") Global $listview = GUICtrlCreateListView("", 10, 10, $Win_X - 20, $Win_Y - 40) GUICtrlSetFont(-1, 8) $button1 = GUICtrlCreateLabel("Hit Exit To Quit", 10, $Win_Y - 25, $Win_X - 20, 20, -1,$ES_CENTER) GUICtrlSetFont(-1, 10, 800) GUICtrlSetTip(-1, "exit") GUICtrlSetOnEvent(-1, 'SpecialEvents') GUICtrlSetStyle($listview, $LVS_ICON) ; + $LVS_NOLABELWRAP) GUISetState(@SW_HIDE) ; hidden at startup ; --------- end of pinger gui ------------- #EndRegion ;ping gui ; Generate colored square images $hImage = _GUIImageList_Create(30, 30) _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFFFF00, 30, 30)) ; yellow _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFF0000, 30, 30)) ; red _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0x00FF00, 30, 30)) ; green _GUICtrlListView_SetImageList($listview, $hImage, 0) While 1 Sleep(100) WEnd Func exitbuttonClick() MsgBox(0,'0','0') Exit EndFunc ;==>exitbuttonClick Func GOButtonClick() $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) ; pass the wanted new octet replace_And_Go($userdata1, $userdata2) ; generate a list of new IP and Go EndFunc ;==>GOButtonClick Func infobuttonClick() EndFunc ;==>infobuttonClick Func Pic1Click() EndFunc ;==>Pic1Click Func quickscanClick() $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) replace_And_Go2($userdata1, $userdata2) EndFunc ;==>quickscanClick Func SpecialEvents() Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE _button1() Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE Case @GUI_CtrlId = $GUI_EVENT_RESTORE Case @GUI_CtrlId = $GUI_EVENT_MAXIMIZE EndSelect EndFunc ;==>SpecialEvents #Region ; Main_GO/Replace_and_GO #cs ############################## second script ############################################# ; this is to ping continuously a list of IP addresses, get and display ping result "live" ; it simulates the dos "ping -t" command but performed simultaneously on many IP ; presenting the results in a ListView highlighting not responding devices with a red box #ce Func replace_And_Go($s_2, $s_3) ; Create a new array wit a new list of IP according to passed second and third octet Local $aNew_IPlist = $aBase_IPlist For $i = 0 To UBound($aNew_IPlist) - 1 $aNew_IPlist[$i][1] = StringReplace(StringReplace($aBase_IPlist[$i][1], $replace2, $s_2), $replace3, $s_3) Next GUISetState(@SW_HIDE, $IPMonkey) GUISetState(@SW_SHOW, $PingGui) ; pass the new list to the pinger Main_GO($aNew_IPlist) GUISetState(@SW_HIDE, $PingGui) GUISetState(@SW_SHOW, $IPMonkey) EndFunc ;==>replace_And_Go Func Main_GO($IPlist) HotKeySet("{esc}", "exitbuttonClick") $StopPing = 0 ; $IPlist = _FileReadToArray_mod(".\IP_List.txt") ; Reads text file for list of IP's ; ; the above command, it loads in the $IPlist array the values contained in the file IP_List.txt ; values in the file should be separated by a semicolon, something like in the following example: ; ; hostname1;192.168.0.1 ; hostname2;192.168.0.5 ; hostnameX;10.59.7.200 ; etc.... ; ; if values in the file are not separated by a semicolon, but another char is used, for example a comma, ; then just pass it as second parameter of the function: $IPlist = _FileReadToArray_mod(".\IP_List.txt", ",") ; _GUICtrlListView_BeginUpdate($listview) _GUICtrlListView_DeleteAllItems($listview) _GUICtrlListView_AddArray($listview, $IPlist) ; fill ListView _GUICtrlListView_EndUpdate($listview) While Not $StopPing ; 1 ; continuously ping addresses of the previously loaded file (IP_List.txt) Sleep(10) ; ; $IPlist is the array loaded with all the IP to be pinged (a 2d array in this case) ; | ; | 1 means the IP are in the second column of the $IPlist array (first colun is nr. 0) ; | | ; | | +--> 0 means return back an array loaded with results from all pinged addresses (responding and not responding) ; | | | if you use 1 then only responding addresses are loaded in the returned array [default] ; | | | if you use 2 then only NOT responding addresses are loaded in the returned array ; | | | In this case we do not need an array to be returned, we only need to perform all pings and pass results ; | | | directly (on the fly) to the "_refresh" callback function that will refresh the listview ; | | | ; | | | 0 means NO lookup name resolution must be performed ; | | | | ; | | | | +--> this is the callback function to be called for each pinged address each time the ping has finished ; | | | | | (see the MultiPing.au3 file for info on all passed params) ; | | | | | 6 parameters are passed to this function, but only 2 are used by the called function in this case: ; | | | | | [4] roundtrip of the responding ping or -1 if IP is down ; | | | | | [5] Index (position) of this IP within the caller's passed array ; | | | | | ; v v v v v _nPing($IPlist, 1, 0, 0, "_refresh") WEnd EndFunc ;==>Main_GO #EndRegion ; Main_GO/Replace_and_GO #Region ; QuickScan/Replace_and_GO2 Func replace_And_Go2($s_2, $s_3) ; Create a new array wit a new list of IP according to passed second and third octet Local $aNew_IPlist = $aBase_IPlist For $i = 0 To UBound($aNew_IPlist) - 1 $aNew_IPlist[$i][1] = StringReplace(StringReplace($aBase_IPlist[$i][1], $replace2, $s_2), $replace3, $s_3) Next GUISetState(@SW_HIDE, $IPMonkey) GUISetState(@SW_SHOW, $PingGui) ; pass the new list to the pinger QuickRun($aNew_IPlist) GUISetState(@SW_HIDE, $PingGui) GUISetState(@SW_SHOW, $IPMonkey) EndFunc ;==>replace_And_Go2 Func QuickRun($IPlist) $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) HotKeySet("{esc}", "_button1") Local $Win_X = 1200, $Win_Y = 880 ; dimension of window $PingGui = GUICreate("IP Monkey" & "~~~" & @UserName & "~~~" & "Store" & $userdata1 & $userdata2 & "~~~" & @MON & "." & @MDAY & "." & @YEAR & "~~~" & @HOUR & "." & @MIN, $Win_X, $Win_Y, -1, -1) GUISetOnEvent($GUI_EVENT_CLOSE, "_button1", $PingGui) $listview = GUICtrlCreateListView("", 10, 10, $Win_X - 20, $Win_Y - 40) GUICtrlSetFont(-1, 8) GUICtrlSetStyle($listview, $LVS_ICON) ; + $LVS_NOLABELWRAP) ; Generate colored square images $hImage = _GUIImageList_Create(30, 30) _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFFFF00, 30, 30)) ; yellow _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFF0000, 30, 30)) ; red _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0x00FF00, 30, 30)) ; green _GUICtrlListView_SetImageList($listview, $hImage, 0) $button1 = GUICtrlCreateButton("Exit", 10, $Win_Y - 25, $Win_X - 20, 20) GUICtrlSetTip(-1, "End of program") GUICtrlSetOnEvent(-1, "exitbuttonClick") GUISetState(@SW_SHOW) ;~ $IPlist = _FileReadToArray_mod(".\IP_List.txt") ; Reads text file for list of IP's _GUICtrlListView_BeginUpdate($listview) _GUICtrlListView_AddArray($listview, $IPlist) ; fill ListView _GUICtrlListView_EndUpdate($listview) ;While 1 ; perform Pings and update ListView by the "_refresh" callback function $aFinalResult = _nPing($IPlist, 1, 0, 0, "_refresh") ;~ _ArrayDisplay($aFinalResult) ;DirCheck() EndFunc ;==>QuickRun #EndRegion ; QuickScan/Replace_and_GO2 #Region ; Misc Funcs (network) Func _refresh($Params) ; this receive ping results and displays them in the ListView _GUICtrlListView_SetItemImage($listview, $Params[5], 0) ; set colour to Yellow Sleep(50) ; a little wait If $Params[4] = -1 Then ; Device not responding to ping _GUICtrlListView_SetItemImage($listview, $Params[5], 1) ; set colour to RED _GUICtrlListView_EnsureVisible($listview, $Params[5]) ; Position view to this item Else ; Device responds to ping _GUICtrlListView_SetItemImage($listview, $Params[5], 2) ; set colour to GREEN EndIf EndFunc ;==>_refresh Func _button1() ; Button 1 clicked ;~ $StopPing = 1 Exit EndFunc ;==>_button1 #EndRegion ; Misc Funcs (network)  
      MultiPing.au3
      IP_List.txt
    • GhostLine
      By GhostLine
      Hello guys !
      I'm stuck in something stupid (I guess), but since I've no clue on how to solve it, here I come
      I'm trying to collect the result of the query "select @@hostname" on MSSQL Server, but it doesn't work ... and I'm sure I'm connected to the database (I've successfully seen the database treeview). 

      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_UseX64=n #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include<_sql.au3> #include<array.au3> Local $aData,$iRows,$iColumns ;Server ID and credentials for tCards Global $ServerAddressT = "10.200.88.1" Global $ServerUserNameT = "user" Global $ServerPasswordT = "password" Global $DatabaseNameT = "DataBASE" ;Connect to DB _SQL_RegisterErrorHandler();register the error handler to prevent hard crash on COM error $OADODB = _SQL_Startup() If $OADODB = $SQL_ERROR Then MsgBox(0 + 16 + 262144, "Error", _SQL_GetErrMsg()) If _sql_Connect(-1, $ServerAddressT, $DatabaseNameT, $ServerUserNameT, $ServerPasswordT) = $SQL_ERROR Then     MsgBox(0 + 16 + 262144, "Error 1", _SQL_GetErrMsg())     _SQL_Close()     Exit Else     If _SQL_Execute(-1,"select @@SERVERNAME") = $SQL_ERROR then         Msgbox(0 + 16 +262144,"Error",_SQL_GetErrMsg())     Else         _ArrayDisplay(_SQL_GetTable(-1,"select @@SERVERNAME",$aData,$iRows,$iColumns)) ;~         $toto = _SQL_Execute(-1,"select @@SERVERNAME") ;~         _ArrayDisplay($toto)     EndIf EndIf