lib/events/MainForm.ps1

#######################################################################################################################################################
# WARNING: DO NOT EDIT THIS FILE AS IT IS GENERATED AND WILL BE OVERWRITTEN ON THE NEXT UPDATE! #
# #
# Generated via psake on: 2026-07-04T04:53:52.131Z #
# Version: 2026.7.4.17 #
# Copyright Fortigi (C) 2024-2026 #
#######################################################################################################################################################
#requires -Version 7.0

$Script:MainForm.Definition.Add_Closed({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.State = "Closed"
            $Script:MainForm.Definition.Close()
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Definition.Add_Closing({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.State = "Closing"
            Save-FormMeasurements
            if (Test-LogFormIsVisible) {
                $Script:LogForm.Definition.Close()
            }
            if (Test-SqlHistoryFormOpen) {
                $Script:SqlHistoryForm.Definition.Close()
            }
            if (Test-SqlSchemaFormIsVisible) {
                $Script:SqlSchemaForm.Definition.Close()
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Definition.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {
            $_ | Show-EventInfo

            $ControlPressed = [System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Control
            $ShiftPressed = [System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Shift

            if ($EventArgs.Key -eq [System.Windows.Input.Key]::F5) {
                if ($null -ne $Script:Webview.Object -and $Script:Webview.Object.IsKeyboardFocusWithin) {
                    "F5 key at MainForm level - WebView2 has focus, deferring to Monaco" | Write-LogOutput -LogType VERBOSE
                }
                else {
                    "F5 key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                    $EventArgs.Handled = $true

                    "Triggering Execute Query from F5 key press (MainForm)" | Write-LogOutput -LogType VERBOSE
                    $Script:MainForm.Elements.ButtonExecuteQuery.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                }
            }
            elseif ($EventArgs.Key -eq [System.Windows.Input.Key]::S -and $ControlPressed -and -not $ShiftPressed) {
                "Ctrl+S key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                "Triggering Save Query from Ctrl+S key press (MainForm)" | Write-LogOutput -LogType VERBOSE
                $Script:MainForm.Elements.ButtonSaveQuery.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
            }
            elseif ($EventArgs.Key -eq [System.Windows.Input.Key]::C -and $ControlPressed -and -not $ShiftPressed) {
                "Ctrl+C detected at MainForm level - allowing to pass through to focused control" | Write-LogOutput -LogType VERBOSE
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Definition.Add_Loaded({
        try {
            $_ | Show-EventInfo

            if ($Script:AppConfig.LogFormOpen) {
                Open-LogForm
            }

            if ($null -ne ($Script:MainForm.Definition | Get-FormPositionConfig)) {
                $Position = $Script:MainForm.Definition | Get-FormPositionConfig
                "Main form position: {0}" -f $Position | Write-LogOutput -LogType DEBUG
                $Script:MainForm.Definition.Left = [Int]::Abs($Position.Split("x")[0])
                $Script:MainForm.Definition.Top = [Int]::Abs($Position.Split("x")[1])
            }
            if ($null -ne ($Script:MainForm.Definition | Get-FormSizeConfig)) {
                $Size = $Script:MainForm.Definition | Get-FormSizeConfig
                "Main form size: {0}" -f $Size | Write-LogOutput -LogType DEBUG
                $Script:MainForm.Definition.Width = [Int]::Abs($Size.Split("x")[0])
                $Script:MainForm.Definition.Height = [Int]::Abs($Size.Split("x")[1])
            }

            if ($null -eq $Script:Webview.Object) {
                "Failed to find WebView2 control." | Write-LogOutput -LogType ERROR
                return
            }

            $Script:Webview.UserDataFolder = Join-Path $Env:TEMP -ChildPath "OmadaSqlTroubleshooter"
            if (-not (Test-Path -Path $Script:Webview.UserDataFolder)) {
                New-Item -Path $Script:Webview.UserDataFolder -ItemType Directory | Out-Null
            }

            $Script:Webview.EdgeWebview2RuntimePath = Join-Path $Script:RunTimeConfig.ModuleFolder -ChildPath "bin\Webview2Runtime"
            if (!(Test-Path ($Script:WebView.EdgeWebview2RuntimePath ) -PathType Container)) {
                $Script:Webview.EdgeWebview2RuntimePath = Join-Path ([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData)) -ChildPath "OmadaSqlTroubleShooter\bin\Webview2Runtime"
            }
            if ((Test-Path -Path $Script:Webview.EdgeWebview2RuntimePath -PathType Container) -and (Test-Path -Path (Join-Path $Script:Webview.EdgeWebview2RuntimePath -ChildPath "msedgewebview2.exe") -PathType Leaf)) {
                $Script:Webview.Environment = [Microsoft.Web.WebView2.Core.CoreWebView2Environment]::CreateAsync($Script:Webview.EdgeWebview2RuntimePath, $Script:Webview.UserDataFolder).GetAwaiter().GetResult()
            }
            else {
                $Script:Webview.Environment = [Microsoft.Web.WebView2.Core.CoreWebView2Environment]::CreateAsync($null, $Script:Webview.UserDataFolder).GetAwaiter().GetResult()
            }

            if (-not (Test-Path $Script:WebView2UserProfilePath -PathType Container)) { New-Item -ItemType Directory -Force -Path $Script:WebView2UserProfilePath | Out-Null }

            $Script:Webview.Object.EnsureCoreWebView2Async($Script:Webview.Environment).GetAwaiter().OnCompleted({
                    "EnsureCoreWebView2Async OnCompleted script" | Write-LogOutput -LogType DEBUG
                    if ($null -eq $Script:Webview.Object.CoreWebView2) {
                        $Script:MainForm.Definition.Dispatcher.Invoke([System.Action] {
                                $Message = "WebView2 environment initialization failed. If this system does not have the Webview2 Runtime installed, please download the fixed version from https://developer.microsoft.com/en-us/microsoft-edge/webview2/ and extract the cab file to folder '{0}'" -f $Script:Webview.EdgeWebview2RuntimePath
                                $Message | Write-LogOutput -LogType ERROR
                            })
                        return
                    }
                    $HtmlFile = Join-Path  $Script:RunTimeConfig.ModuleFolder -ChildPath "Monaco\index.html"
                    if ([System.IO.File]::Exists($HtmlFile)) {
                        $Script:Webview.Object.Dispatcher.Invoke([System.Action] {
                                $Script:Webview.Object.Source = New-Object System.Uri($HtmlFile)
                                "Webiew source set to: {0}" -f $HtmlFile | Write-LogOutput -LogType DEBUG
                            })
                    }
                    else {
                        $Script:MainForm.Definition.Dispatcher.Invoke([System.Action] {
                                "Monaco HTML file not found at: {0}" -f $HtmlPath | Write-LogOutput -LogType ERROR
                            })
                    }
                    Test-ConnectionButton

                    if ($Script:AppConfig.SqlSchemaFormOpen) {
                        Open-SqlSchemaForm
                    }
                    Update-QueryList
                    Set-EditorValue

                    $Script:Webview.Object.add_PreviewKeyDown({
                            param(
                                $EventSender,
                                $EventArgs
                            )
                            try {
                                $_ | Show-EventInfo

                                if ($EventArgs.Key -eq [System.Windows.Input.Key]::S -and ([System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Control)) {
                                    "Ctrl+S key intercepted in WebView2 (PreviewKeyDown)" | Write-LogOutput -LogType DEBUG

                                    $EventArgs.Handled = $true

                                    $Script:MainForm.Definition.Dispatcher.Invoke([System.Action] {
                                            "Triggering Save Query from Ctrl+S key press" | Write-LogOutput -LogType DEBUG
                                            $Script:MainForm.Elements.ButtonSaveQuery.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                                        })
                                }
                            }
                            catch {
                                $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
                            }
                        })

                    $Script:Webview.Object.CoreWebView2.add_WebMessageReceived({
                            param(
                                $EventSender,
                                $EventArgs
                            )
                            try {
                                $_ | Show-EventInfo
                                "CoreWebView2.add_WebMessageReceived" | Write-LogOutput -LogType DEBUG

                                $message = $EventArgs.TryGetWebMessageAsString()
                                "WebView2 message received: {0}" -f $message | Write-LogOutput -LogType DEBUG

                                if ($message) {
                                    $messageObj = $message | ConvertFrom-Json -ErrorAction SilentlyContinue
                                    if ($messageObj -and $messageObj.type -eq 'executeQuery') {
                                        "Execute Query requested from Monaco Editor via {0}" -f $messageObj.key | Write-LogOutput -LogType DEBUG

                                        $Script:MainForm.Definition.Dispatcher.Invoke([System.Action] {
                                                $Script:MainForm.Elements.ButtonExecuteQuery.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                                            })
                                    }
                                    elseif ($messageObj -and $messageObj.type -eq 'saveQuery') {
                                        "Save Query requested from Monaco Editor via {0}" -f $messageObj.key | Write-LogOutput -LogType DEBUG

                                        $Script:MainForm.Definition.Dispatcher.Invoke([System.Action] {
                                                $Script:MainForm.Elements.ButtonSaveQuery.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                                            })
                                    }
                                }
                            }
                            catch {
                                $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
                            }
                        })

                    $Script:MainForm.State = "Open"
                })
        }
        catch {
            "WebView2 initialization failed: {0}" -f $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Definition.Add_LocationChanged({
        try {
            $_ | Show-EventInfo -LogType VERBOSE2

            $ActionId = [System.Guid]::NewGuid().ToString()

            if (!$Script:MainForm.Definition.IsVisible -or $Script:MainForm.Definition.Left -lt 0 -or $Script:MainForm.Definition.Top -lt 0) {
                "MainForm is not suitable for processing. Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:MainForm.Definition.Left, $Script:MainForm.Definition.Top, $Script:MainForm.Definition.Width , $Script:MainForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                return
            }

            "MainForm Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:MainForm.Definition.Left, $Script:MainForm.Definition.Top, $Script:MainForm.Definition.Width , $Script:MainForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
            if ((Test-LogFormIsVisible) -and -not $Script:LogForm.PositionManager.Synchronizing) {
                if ($Script:LogForm.Definition.Left -lt 0 -or $Script:LogForm.Definition.Top -lt 0) {
                    "LogForm is not suitable for processing. Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:MainForm.Definition.Left, $Script:MainForm.Definition.Top, $Script:MainForm.Definition.Width , $Script:MainForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                    return
                }
                "LogForm Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:LogForm.Definition.Left, $Script:LogForm.Definition.Top, $Script:LogForm.Definition.Width , $Script:LogForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                $Script:LogForm.PositionManager.Synchronizing = $true
                $Script:MainForm.Definition.Dispatcher.Invoke({
                        $Script:LogForm.Definition.Left = [Int]::Abs($Script:MainForm.Definition.Left) + [Int]::Abs($Script:LogForm.PositionManager.PositionOffSetLeft)
                        $Script:LogForm.Definition.Top = [Int]::Abs($Script:MainForm.Definition.Top) + [Int]::Abs($Script:LogForm.PositionManager.PositionOffSetTop)
                        "LogForm Position: {0}x{1}, Dimensions: {2}x{3}, PositionManagerOffSet: {4}x{5} (Id:{6})" -f $Script:LogForm.Definition.Left, $Script:LogForm.Definition.Top, $Script:LogForm.Definition.Width , $Script:LogForm.Definition.Height, $Script:LogForm.PositionManager.PositionOffSetLeft, $Script:LogForm.PositionManager.PositionOffSetTop, $ActionId | Write-LogOutput -LogType VERBOSE2
                        $Script:LogForm.PositionManager.Synchronizing = $false
                    }, [System.Windows.Threading.DispatcherPriority]::Render)
            }
            if ((Test-SqlSchemaFormIsVisible) -and -not $Script:SqlSchemaForm.PositionManager.Synchronizing) {
                $_ | Show-EventInfo -LogType VERBOSE2
                if ($Script:SqlSchemaForm.Definition.Left -lt 0 -or $Script:SqlSchemaForm.Definition.Top -lt 0) {
                    "SqlSchemaForm is not suitable for processing. Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:SqlSchemaForm.Definition.Left, $Script:SqlSchemaForm.Definition.Top, $Script:SqlSchemaForm.Definition.Width , $Script:SqlSchemaForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                    return
                }
                "SqlSchemaForm Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:SqlSchemaForm.Definition.Left, $Script:SqlSchemaForm.Definition.Top, $Script:SqlSchemaForm.Definition.Width , $Script:SqlSchemaForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                $Script:SqlSchemaForm.PositionManager.Synchronizing = $true
                $Script:MainForm.Definition.Dispatcher.Invoke({
                        $Script:SqlSchemaForm.Definition.Left = [Int]::Abs($Script:MainForm.Definition.Left) - [Int]::Abs($Script:SqlSchemaForm.PositionManager.PositionOffSetLeft)
                        $Script:SqlSchemaForm.Definition.Top = [Int]::Abs($Script:MainForm.Definition.Top) - [Int]::Abs($Script:SqlSchemaForm.PositionManager.PositionOffSetTop)
                        "SqlSchemaForm Position: {0}x{1}, Dimensions: {2}x{3}, PositionManagerOffSet: {4}x{5} (Id:{6})" -f $Script:SqlSchemaForm.Definition.Left, $Script:SqlSchemaForm.Definition.Top, $Script:SqlSchemaForm.Definition.Width, $Script:SqlSchemaForm.Definition.Height, $Script:SqlSchemaForm.PositionManager.PositionOffSetLeft, $Script:SqlSchemaForm.PositionManager.PositionOffSetTop, $ActionId | Write-LogOutput -LogType VERBOSE2
                        $Script:SqlSchemaForm.PositionManager.Synchronizing = $false
                    }, [System.Windows.Threading.DispatcherPriority]::Render)
            }
        }
        catch {
            "WebView2 initialization failed: {0}" -f $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.ButtonConnect.Add_Click({
        try {
            $_ | Show-EventInfo

            if ($Script:MainForm.Elements.ButtonConnectText.Text -eq "_Connect") {
                $Script:RunTimeConfig.ReconnectStatus = 2
                if (Test-OmadaConnection) {
                    Test-ConnectionSettings
                }
                if ($Script:ConnectionStatus) {
                    Update-QueryList -ForceRefresh
                    Update-DataConnectionList
                }
            }
            else {
                Set-SqlConnectionState -Status $false
            }
        }
        catch {
            Restore-MainFormFocus
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonExecuteQuery.Add_Click({
        try {
            $_ | Show-EventInfo

            $Script:RunTimeData.StopWatch = [System.Diagnostics.Stopwatch]::StartNew()

            $Script:PopupWindowExecuteQuery = Show-PopupWindow -Message "Executing Query..."

            $Script:MainForm.Elements.ButtonSaveQuery.IsEnabled = $false
            $Script:MainForm.Elements.ButtonExecuteQuery.IsEnabled = $false
            $Script:MainForm.Elements.ButtonShowOutput.IsEnabled = $false
            $Script:MainForm.Elements.ButtonSaveOutputFile.IsEnabled = $false
            Start-Sleep -Milliseconds 100

            if (!(Test-ConnectionRequirements) -or [string]::IsNullOrWhiteSpace($Script:AppConfig.CurrentSqlQuery.DoId)) {
                "Omada Url not set or Query not selected, cannot retrieve data!" | Write-LogOutput -LogType WARNING
                if ($null -ne $Script:PopupWindowExecuteQuery) {
                    $Script:PopupWindowExecuteQuery.Close()
                }
                Restore-MainFormFocus
            }
            else {
                "Execute" | Write-LogOutput
                Invoke-ExecuteQuery
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonNewQuery.Add_Click({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.Elements.ButtonSaveQuery.IsEnabled = $false
            $Script:MainForm.Elements.ButtonNewQuery.IsEnabled = $false

            if (!(Test-ConnectionRequirements)) {
                "Omada Url not set or Query not selected, cannot retrieve data!" | Write-LogOutput -LogType WARNING
                Set-SqlConnectionState -Status $false
            }
            else {

                if ($Script:MainForm.Elements.ButtonNewQuery.Text -eq "Delete") {
                    "Delete query query" | Write-LogOutput
                }
                else {

                    "Save query new query" | Write-LogOutput

                    Invoke-SaveEditorValue -NewQuery
                }
            }
        }
        catch {
            Set-SqlConnectionState -Status $false
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonOpenOutputFile.Add_Click({
        try {
            $_ | Show-EventInfo
            "Open outputfile: {0}" -f $Script:RunTimeConfig.OutputFileName | Write-LogOutput
            & $Script:RunTimeConfig.OutputFileName

        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonRefreshQueries.Add_Click({
        try {
            $_ | Show-EventInfo

            try {
                "Force update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList -ForceRefresh
            }
            catch {
                if ($_.Exception.Response.StatusCode -eq "NotFound") {
                    "SQL Troubleshooting Object not found or OData endpoint for SQL Troubleshooting is not found. Is it enable for OData? Please check the data object type properties!" | Write-LogOutput -LogType ERROR -ErrorObject $_
                }
                else {
                    $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
                }
            }
        }
        catch {
            "WebView2 initialization failed: {0}" -f $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonReset.Add_Click({
        try {
            $_ | Show-EventInfo
            "Reset" | Write-LogOutput -LogType LOG
            Reset-Application -ResetEditor
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonSaveOutputFile.Add_Click({
        try {
            $_ | Show-EventInfo
            Save-QueryResultToFile -QueryResult $Script:RunTimeData.QueryResult
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonSaveQuery.Add_Click({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.Elements.ButtonSaveQuery.IsEnabled = $false
            $Script:MainForm.Elements.ButtonExecuteQuery.IsEnabled = $false

            if (!(Test-ConnectionRequirements) -or [string]::IsNullOrWhiteSpace($Script:AppConfig.CurrentSqlQuery.DoId)) {
                "Omada Url not set or Query not selected, cannot retrieve data!" | Write-LogOutput -LogType WARNING
            }
            else {
                "Save query" | Write-LogOutput
                Invoke-SaveEditorValue
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonShowHistory.Add_Click({
        try {
            $_ | Show-EventInfo
            "Show history form" | Write-LogOutput -LogType DEBUG
            Open-SqlHistoryForm
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonShowLog.Add_Click({
        try {
            $_ | Show-EventInfo
            if (Test-LogFormIsVisible) {
                "_Hide" | Write-LogOutput -LogType DEBUG
                $Script:LogForm.Definition.Close()
            }
            else {
                "Show log" | Write-LogOutput -LogType DEBUG
                Open-LogForm
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }

    })
$Script:MainForm.Elements.ButtonShowOutput.Add_Click({
        try {
            $_ | Show-EventInfo
            "Show output" | Write-LogOutput
            $ColumnOrder = @($Script:MainForm.Elements.DataGridQueryResult.Columns | Sort-Object -Property DisplayIndex | ForEach-Object { "{0}" -f $_.Header })
            Show-QueryResultGridView -Rows $Script:RunTimeData.QueryResult.d.rows -Title ("{0} - {1}" -f $Form.Text, $Script:AppConfig.CurrentSqlQuery.FullName) -ColumnOrder $ColumnOrder
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ButtonShowSqlSchema.Add_Click({
        try {
            $_ | Show-EventInfo
            if (Test-SqlSchemaFormIsVisible) {
                "Hide log" | Write-LogOutput -LogType DEBUG
                $Script:SqlSchemaForm.Definition.Close()
            }
            else {
                "Show schema" | Write-LogOutput -LogType DEBUG
                Open-SqlSchemaForm
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.CheckboxMyUpdatedQueries.Add_Checked({
        try {
            $_ | Show-EventInfo

            if (!(Test-ConnectionRequirements)) {
                "Connection not ready" | Write-LogOutput -LogType DEBUG
                return
            }

            $true | Set-ConfigProperty -Property "MyUpdatedQueriesOnly"
            if ($Script:ConnectionStatus) {

                $Script:RunTimeData.RestMethodParam.Uri = "{0}/actusersettingsdlg.aspx?HIDEBACKARRICON=1" -f $Script:AppConfig.BaseUrl
                $Script:RunTimeData.RestMethodParam.Body = $null
                $Script:RunTimeData.RestMethodParam.Method = "GET"
                $Result = Invoke-OmadaPSWebRequestWrapper

                if ($Result -match [regex]("identityUserName:.\S+")) {
                    $Match = $Matches[0]
                    $IdentityUserName = $Match.Split(":")[1].Trim().TrimStart("'").TrimEnd(",").TrimEnd("'")
                    if (![string]::IsNullOrWhiteSpace($IdentityUserName)) {
                        $IdentityUserName | Set-ConfigProperty -Property "IdentityUserName"
                    }
                }
                else {
                    if (!$Script:AppConfig.MyCreatedQueriesOnly) {
                        $null | Set-ConfigProperty -Property "IdentityUserName"
                    }
                }
                "Force update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList -ForceRefresh
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.CheckboxMyUpdatedQueries.Add_Unchecked({
        try {
            $_ | Show-EventInfo
            $false | Set-ConfigProperty -Property "MyUpdatedQueriesOnly"
            if (!$Script:AppConfig.MyCreatedQueriesOnly) {
                $null | Set-ConfigProperty -Property "IdentityUserName"
            }
            if ($Script:ConnectionStatus) {
                "Force update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList -ForceRefresh
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.CheckboxMyCreatedQueries.Add_Checked({
        try {
            $_ | Show-EventInfo
            if (!(Test-ConnectionRequirements)) {
                "Connection not ready" | Write-LogOutput -LogType DEBUG
                return
            }

            $true | Set-ConfigProperty -Property "MyCreatedQueriesOnly"
            if ($Script:ConnectionStatus) {
                $Script:RunTimeData.RestMethodParam.Uri = "{0}/actusersettingsdlg.aspx?HIDEBACKARRICON=1" -f $Script:AppConfig.BaseUrl
                $Script:RunTimeData.RestMethodParam.Body = $null
                $Script:RunTimeData.RestMethodParam.Method = "GET"
                $Result = Invoke-OmadaPSWebRequestWrapper

                if ($Result -match [regex]("identityUserName:.\S+")) {
                    $Match = $Matches[0]
                    $IdentityUserName = $Match.Split(":")[1].Trim().TrimStart("'").TrimEnd(",").TrimEnd("'")
                    if (![string]::IsNullOrWhiteSpace($IdentityUserName)) {
                        $IdentityUserName | Set-ConfigProperty -Property "IdentityUserName"
                    }
                }
                else {
                    if (!$Script:AppConfig.MyUpdatedQueriesOnly) {
                        $null | Set-ConfigProperty -Property "IdentityUserName"
                    }
                }
                "Force update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList -ForceRefresh
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.CheckboxMyCreatedQueries.Add_Unchecked({
        try {
            $_ | Show-EventInfo
            $false | Set-ConfigProperty -Property "MyCreatedQueriesOnly"
            if (!$Script:AppConfig.MyUpdatedQueriesOnly) {
                $null | Set-ConfigProperty -Property "IdentityUserName"
            }
            if ($Script:ConnectionStatus) {

                "Force update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList -ForceRefresh
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.CheckboxSavePassword.Add_Checked({
        try {
            $_ | Show-EventInfo

            $true | Set-ConfigProperty -Property "SavePassword"
            $Script:RunTimeConfig.SavePassword = $true
            if ($null -ne $Script:MainForm.Elements.TextBoxPassword.Password) {
                $Script:MainForm.Elements.TextBoxPassword.Password | Set-ConfigProperty -Property "Password"
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.CheckboxSavePassword.Add_Unchecked({
        try {
            $_ | Show-EventInfo
            $false | Set-ConfigProperty -Property "SavePassword"
            $Script:RunTimeConfig.SavePassword = $false
            $null | Set-ConfigProperty -Property "Password"
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.Add_GotFocus({
        try {
            $_ | Show-EventInfo
            if ($null -eq $Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem) {
                $Script:RunTimeConfig.AuthenticationSet = $false
            }
            else {
                $Script:RunTimeConfig.AuthenticationSet = $true
                if($Script:AppConfig.LastAuthentication -in @("Browser-InPrivate","WebView2-InPrivate")){
                    $Script:RunTimeData.RestMethodParam.InPrivate = $true
                    $Script:RunTimeData.RestMethodParam.AuthenticationType = $Script:AppConfig.LastAuthentication.Replace("-InPrivate","")
                }
                else{
                    $Script:RunTimeData.RestMethodParam.InPrivate = $false
                    $Script:RunTimeData.RestMethodParam.AuthenticationType = $Script:AppConfig.LastAuthentication
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.Add_SelectionChanged({
        try {
            $_ | Show-EventInfo

            Set-AuthenticationOption
            "Changed authentication option to: {0}" -f $Script:AppConfig.LastAuthentication | Write-LogOutput -LogType DEBUG

            if ($null -eq $Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem) {
                $Script:RunTimeConfig.AuthenticationSet = $false
            }
            else {
                $Script:RunTimeConfig.AuthenticationSet = $true
                if($Script:AppConfig.LastAuthentication -in @("Browser-InPrivate","WebView2-InPrivate")){
                    $Script:RunTimeData.RestMethodParam.InPrivate = $true
                    $Script:RunTimeData.RestMethodParam.AuthenticationType = $Script:AppConfig.LastAuthentication.Replace("-InPrivate","")
                }
                else{
                    $Script:RunTimeData.RestMethodParam.InPrivate = $false
                    $Script:RunTimeData.RestMethodParam.AuthenticationType = $Script:AppConfig.LastAuthentication
                }
            }

            if ($Script:RunTimeConfig.AuthenticationSet -and ![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxURL.Text)) {
                Set-OmadaUrl
            }
            Test-ConnectionButton
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.Add_LostFocus({
        try {
            $_ | Show-EventInfo

            if ($null -eq $Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem) {

                Set-AuthenticationOption
                "Changed authentication option to: {0}" -f $Script:AppConfig.LastAuthentication | Write-LogOutput -LogType DEBUG

                if ($Script:RunTimeConfig.AuthenticationSet -and ![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxURL.Text)) {
                    Set-OmadaUrl
                }
                Test-ConnectionButton
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }

    })
$Script:MainForm.Elements.ComboBoxSelectDataConnection.Add_DropDownOpened({
        try {
            $_ | Show-EventInfo

        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.ComboBoxSelectDataConnection.Add_SelectionChanged({
        try {
            $_ | Show-EventInfo

            $PsCallStack = Get-PSCallStack

            if (-not $PsCallStack[1].Command -eq "Update-DataConnectionList" -and ($Script:MainForm.Elements.ComboBoxSelectDataConnection.Items | Measure-Object).Count -le 0) {
                Update-DataConnectionList
            }

            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content) -and $Script:MainForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content -ne " - " -and $Script:MainForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content -ne " - 0") {
                $Script:MainForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content | Set-ConfigProperty -Property "CurrentDataConnection"
                $Script:MainForm.Elements.TextBlockStatusBarDatabaseName | Set-TextBlockText -Text $Script:AppConfig.CurrentDataConnection.DisplayName

                if (Test-SqlSchemaFormIsVisible) {
                    Get-SqlSchemaObject
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.ComboBoxSelectQuery.Add_DropDownOpened({
        try {
            $_ | Show-EventInfo

            Update-QueryList

        }
        catch {
            if ($_.Exception.Response.StatusCode -eq "NotFound") {
                "SQL Troubleshooting Object not found or OData endpoint for SQL Troubleshooting is not found. Is it enable for OData? Please check the data object type properties!" | Write-LogOutput -LogType ERROR -ErrorObject $_
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
            }
        }

    })

$Script:MainForm.Elements.ComboBoxSelectQuery.Add_SelectionChanged({
        try {
            $_ | Show-EventInfo

            $Script:RunTimeData.CurrentSqlQuery.FullName = $Script:MainForm.Elements.ComboBoxSelectQuery.SelectedItem.Content
            if (($Script:MainForm.Elements.ComboBoxSelectQuery.Items | Measure-Object).Count -ge 0 -and ![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.ComboBoxSelectQuery.SelectedItem.Content)) {
                if (Test-SqlHistoryFormOpen) {
                    $Script:SqlHistoryForm.Definition.Close()
                }
                Set-EditorValue
                Set-SqlQueryFunctionState -Status $true
            }

        }
        catch {
            if ($_.Exception.Response.StatusCode -eq "NotFound") {

                "SQL Troubleshooting Object not found for OData endpoint for SQL Troubleshooting is not found. Is it enable for OData? Please check the data object type properties!" | Write-LogOutput -LogType ERROR -ErrorObject $_
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
            }
        }

    })
$Script:MainForm.Elements.DataGridQueryResult.ContextMenu.Add_Opened({
        try {
            $_ | Show-EventInfo
            Update-DataGridQueryResultContextMenuState
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemCopy.Add_Click({
        try {
            $_ | Show-EventInfo
            Copy-DataGridToClipboard
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemCopyWithHeader.Add_Click({
        try {
            $_ | Show-EventInfo
            Copy-DataGridToClipboard -IncludeHeader
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemCopyAsSqlArray.Add_Click({
        try {
            $_ | Show-EventInfo
            Copy-DataGridToClipboard -OutputFormat "SqlArray"
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemCopyAsPowerShellArray.Add_Click({
        try {
            $_ | Show-EventInfo
            Copy-DataGridToClipboard -OutputFormat "PowerShellArray"
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemSelectAll.Add_Click({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.Elements.DataGridQueryResult.SelectAll()
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemSaveAs.Add_Click({
        try {
            $_ | Show-EventInfo
            $Script:MainForm.Elements.ButtonSaveOutputFile.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemSaveSelectedAs.Add_Click({
        try {
            $_ | Show-EventInfo
            Save-QueryResultToFile -QueryResult (Get-DataGridSelectedQueryResult) -IsSelection
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:DataGridQueryResultMenuItemViewSelected.Add_Click({
        try {
            $_ | Show-EventInfo
            $SelectedQueryResult = Get-DataGridSelectedQueryResult
            $ColumnOrder = @($SelectedQueryResult.d.rows | Select-Object -First 1 | ForEach-Object { $_.PSObject.Properties.Name })
            Show-QueryResultGridView -Rows $SelectedQueryResult.d.rows -Title ("{0} - {1} (Selection)" -f $Form.Text, $Script:AppConfig.CurrentSqlQuery.FullName) -ColumnOrder $ColumnOrder
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.DataGridQueryResult.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArguments
        )
        try {
            $_ | Show-EventInfo

            $ControlPressed = [System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Control
            $ShiftPressed = [System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Shift

            if ($EventArguments.Key -eq [System.Windows.Input.Key]::C -and $ControlPressed -and $ShiftPressed) {
                "Ctrl+Shift+C key intercepted at DataGrid level - copying values with headers" | Write-LogOutput -LogType VERBOSE
                $Script:DataGridQueryResultMenuItemCopyWithHeader.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.MenuItem]::ClickEvent))
                $EventArguments.Handled = $true
            }
            elseif ($EventArguments.Key -eq [System.Windows.Input.Key]::C -and $ControlPressed -and -not $ShiftPressed) {
                "Ctrl+C key intercepted at DataGrid level - copying values only" | Write-LogOutput -LogType VERBOSE
                $Script:DataGridQueryResultMenuItemCopy.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.MenuItem]::ClickEvent))
                $EventArguments.Handled = $true
            }
            elseif ($EventArguments.Key -eq [System.Windows.Input.Key]::P -and $ControlPressed -and $ShiftPressed) {
                "Ctrl+Shift+P key intercepted at DataGrid level - copying values only as PowerShell array" | Write-LogOutput -LogType VERBOSE
                $Script:DataGridQueryResultMenuItemCopyAsPowerShellArray.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.MenuItem]::ClickEvent))
                $EventArguments.Handled = $true
            }
            elseif ($EventArguments.Key -eq [System.Windows.Input.Key]::S -and $ControlPressed -and $ShiftPressed) {
                "Ctrl+Shift+S key intercepted at DataGrid level - copying values only as Sql array" | Write-LogOutput -LogType VERBOSE
                $Script:DataGridQueryResultMenuItemCopyAsSqlArray.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.MenuItem]::ClickEvent))
                $EventArguments.Handled = $true
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.DataGridQueryResult.AddHandler(
    [System.Windows.UIElement]::PreviewMouseLeftButtonDownEvent,
    [System.Windows.Input.MouseButtonEventHandler] {
        param(
            $EventSender,
            $EventArguments
        )
        try {
            if ($EventArguments.OriginalSource -is [System.Windows.Controls.Primitives.Thumb]) {
                return
            }

            $VisualElement = $EventArguments.OriginalSource
            $ColumnHeader = $null
            while ($null -ne $VisualElement) {
                if ($VisualElement -is [System.Windows.Controls.Primitives.DataGridColumnHeader]) {
                    $ColumnHeader = $VisualElement
                    break
                }
                $VisualElement = [System.Windows.Media.VisualTreeHelper]::GetParent($VisualElement)
            }

            if ($null -eq $ColumnHeader -or $null -eq $ColumnHeader.Column) {
                return
            }

            $_ | Show-EventInfo

            $ControlPressed = [bool]([System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Control)
            $ShiftPressed = [bool]([System.Windows.Input.Keyboard]::Modifiers -band [System.Windows.Input.ModifierKeys]::Shift)

            Select-DataGridColumnCells -DataGrid $Script:MainForm.Elements.DataGridQueryResult -Column $ColumnHeader.Column -ControlPressed $ControlPressed -ShiftPressed $ShiftPressed
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    }
)

$Script:MainForm.Elements.DataGridQueryResult.Add_AutoGeneratingColumn({
        param(
            $EventSender,
            $EventArguments
        )
        try {
            $Private:HeaderTemplate = [System.Windows.Markup.XamlReader]::Parse(
                '<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><TextBlock Text="{Binding}" TextTrimming="CharacterEllipsis"/></DataTemplate>'
            )
            $EventArguments.Column.HeaderTemplate = $Private:HeaderTemplate
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.DataGridQueryResult.Add_LoadingRow({
        param(
            $EventSender,
            $EventArguments
        )
        $_ | Show-EventInfo

        try {
            $EventArguments.Row.Header = ($EventArguments.Row.GetIndex() + 1).ToString()
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.TextBoxAppIdUri.Add_LostFocus({
        try {
            $_ | Show-EventInfo
            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxAppIdUri.Text)) {

                "Password set to: {0}" -f "***********" | Write-LogOutput -LogType DEBUG
                if ($Script:RunTimeData.RestMethodParam.ContainsKey("EntraApplicationIdUri")) {
                    if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxAppIdUri.Text)) {
                        "Set App Id Uri: {0}" -f $Script:MainForm.Elements.TextBoxAppIdUri.Text | Write-LogOutput -LogType DEBUG
                        $Script:MainForm.Elements.TextBoxAppIdUri.Text | Set-ConfigProperty -Property "EntraApplicationIdUri"
                        $Script:RunTimeData.RestMethodParam.EntraApplicationIdUri = $Script:MainForm.Elements.TextBoxAppIdUri.Text
                    }
                }
                "App Id Uri set" | Write-LogOutput -LogType VERBOSE
                Test-ConnectionButton
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxAppIdUri.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {

            $_ | Show-EventInfo

            if ($EventArgs.Key -in ([System.Windows.Input.Key]::Enter, [System.Windows.Input.Key]::Return)) {
                "Enter/Return key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                if ($Script:MainForm.Elements.TextBoxUrl.IsEnabled -and $Script:MainForm.Elements.TextBoxUrl.Text -like "http*") {
                    "Triggering connect" | Write-LogOutput -LogType VERBOSE
                    Test-ConnectionButton
                    if ($Script:MainForm.Elements.ButtonConnect.IsEnabled) {
                        "Executing connection" | Write-LogOutput -LogType VERBOSE
                        $Script:MainForm.Elements.ButtonConnect.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                    }
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.TextBoxEntraIdTenantId.Add_LostFocus({
        try {
            $_ | Show-EventInfo
            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxEntraIdTenantId.Text)) {

                "Password set to: {0}" -f "***********" | Write-LogOutput -LogType DEBUG
                if ($Script:RunTimeData.RestMethodParam.ContainsKey("EntraIdTenantId")) {
                    if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxEntraIdTenantId.Text)) {
                        "Set App Id Uri: {0}" -f $Script:MainForm.Elements.TextBoxEntraIdTenantId.Text | Write-LogOutput -LogType DEBUG
                        $Script:MainForm.Elements.TextBoxEntraIdTenantId.Text | Set-ConfigProperty -Property "EntraIdTenantId"
                        $Script:RunTimeData.RestMethodParam.EntraIdTenantId = $Script:MainForm.Elements.TextBoxEntraIdTenantId.Text
                    }
                }
                "Tenant Id set" | Write-LogOutput -LogType VERBOSE
                Test-ConnectionButton
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxEntraIdTenantId.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {

            $_ | Show-EventInfo

            if ($EventArgs.Key -in ([System.Windows.Input.Key]::Enter, [System.Windows.Input.Key]::Return)) {
                "Enter/Return key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                if ($Script:MainForm.Elements.TextBoxUrl.IsEnabled -and $Script:MainForm.Elements.TextBoxUrl.Text -like "http*") {
                    "Triggering connect" | Write-LogOutput -LogType VERBOSE
                    Test-ConnectionButton
                    if ($Script:MainForm.Elements.ButtonConnect.IsEnabled) {
                        "Executing connection" | Write-LogOutput -LogType VERBOSE
                        $Script:MainForm.Elements.ButtonConnect.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                    }
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxPassword.Add_LostFocus({
        try {
            $_ | Show-EventInfo
            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxUserName.Text)) {

                "Password set to: {0}" -f "***********" | Write-LogOutput -LogType DEBUG
                if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxUserName.Text) -and ![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxPassword.Password)) {
                    "Create/Update credential with username {0}" -f $Script:MainForm.Elements.TextBoxUserName.Text | Write-LogOutput -LogType DEBUG
                    $Script:MainForm.Elements.TextBoxUserName.Text | Set-ConfigProperty -Property "UserName"
                    if ($Script:RunTimeConfig.SavePassword) {
                        $Script:MainForm.Elements.TextBoxPassword.Password | Set-ConfigProperty -Property "Password"
                    }
                    else {
                        $null | Set-ConfigProperty -Property "Password"
                    }

                    if (!$Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                        $Script:RunTimeData.RestMethodParam.Add("Credential", $null)
                    }
                    $Script:RunTimeData.RestMethodParam.Credential = [System.Management.Automation.PSCredential]::new($Script:AppConfig.UserName, ($Script:MainForm.Elements.TextBoxPassword.Password | ConvertTo-SecureString -AsPlainText -Force))
                }
                "Password set" | Write-LogOutput -LogType VERBOSE
                Test-ConnectionButton
            }
            if ([string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxPassword.Password)) {
                if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                    "Clear credential because password is empty" | Write-LogOutput -LogType DEBUG
                    $Script:RunTimeData.RestMethodParam.Credential = $null
                    if ($Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem.Content -ne "OAuth") {
                        $Script:RunTimeData.RestMethodParam.Remove("Credential")
                    }
                }
                if ($Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem.Content -ne "OAuth") {
                    "Password cannot be empty!" | Write-LogOutput -LogType VERBOSE
                }
                else {
                    "Password is empty, so it is not used for authentication" | Write-LogOutput -LogType VERBOSE
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxPassword.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {

            $_ | Show-EventInfo

            if ($EventArgs.Key -in ([System.Windows.Input.Key]::Enter, [System.Windows.Input.Key]::Return)) {
                "Enter/Return key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                if ($Script:MainForm.Elements.TextBoxUrl.IsEnabled -and $Script:MainForm.Elements.TextBoxUrl.Text -like "http*") {
                    "Triggering connect" | Write-LogOutput -LogType VERBOSE
                    Test-ConnectionButton
                    if ($Script:MainForm.Elements.ButtonConnect.IsEnabled) {
                        "Executing connection" | Write-LogOutput -LogType VERBOSE
                        $Script:MainForm.Elements.ButtonConnect.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                    }
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.TextBoxURL.Add_GotFocus({
        try {
            $_ | Show-EventInfo
            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxURL.Text) -and $Script:MainForm.Elements.TextBlockUrl.Text -like "http*.omada.cloud" -and $Script:MainForm.Elements.TextBlockUrl.Text -ne $Script:CurrentUrl) {
                $Script:CurrentUrl = $Script:MainForm.Elements.TextBlockUrl.Text
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxURL.Add_LostFocus({
        $_ | Show-EventInfo

        try {
            Set-OmadaUrl
            Test-ConnectionButton
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

$Script:MainForm.Elements.TextBoxURL.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {

            $_ | Show-EventInfo

            if ($EventArgs.Key -in ([System.Windows.Input.Key]::Enter, [System.Windows.Input.Key]::Return)) {
                "Enter/Return key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                "Triggering connect" | Write-LogOutput -LogType VERBOSE
                Set-OmadaUrl
                Test-ConnectionButton

                if ($Script:MainForm.Elements.ButtonConnect.IsEnabled) {
                    "Executing connection" | Write-LogOutput -LogType VERBOSE
                    $Script:MainForm.Elements.ButtonConnect.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:MainForm.Elements.TextBoxUserName.Add_LostFocus({
        try {
            $_ | Show-EventInfo
            if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxUserName.Text)) {

                $Script:MainForm.Elements.TextBoxUserName.Text | Set-ConfigProperty -Property "UserName"
                "Username set to: {0}" -f $Script:AppConfig.UserName | Write-LogOutput -LogType DEBUG
                if (![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxUserName.Text) -and ![string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxPassword.Password)) {
                    "Create/Update credential with username {0}" -f $Script:MainForm.Elements.TextBoxUserName.Text | Write-LogOutput -LogType DEBUG
                    $Script:MainForm.Elements.TextBoxUserName.Text | Set-ConfigProperty -Property "UserName"
                    if (!$Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                        $Script:RunTimeData.RestMethodParam.Add("Credential", $null)
                    }
                    $Script:RunTimeData.RestMethodParam.Credential = [System.Management.Automation.PSCredential]::new($Script:AppConfig.UserName, ($Script:MainForm.Elements.TextBoxPassword.Password | ConvertTo-SecureString -AsPlainText -Force))
                }
                "Username set!" | Write-LogOutput
                Test-ConnectionButton
            }
            if ([string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxUserName.Text)) {
                if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                    "Clear credential because username is empty" | Write-LogOutput -LogType DEBUG
                    $Script:RunTimeData.RestMethodParam.Credential = $null
                    if ($Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem.Content -ne "OAuth") {
                        $Script:RunTimeData.RestMethodParam.Remove("Credential")
                    }
                }
                if ($Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem.Content -ne "OAuth") {
                    "Username cannot be empty!" | Write-LogOutput -LogType VERBOSE
                }
                else {
                    "Username is empty, so it is not used for authentication" | Write-LogOutput -LogType VERBOSE
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }

    })

$Script:MainForm.Elements.TextBoxUserName.Add_PreviewKeyDown({
        param(
            $EventSender,
            $EventArgs
        )
        try {

            $_ | Show-EventInfo

            if ($EventArgs.Key -in ([System.Windows.Input.Key]::Enter, [System.Windows.Input.Key]::Return)) {
                "Enter/Return key intercepted at MainForm level" | Write-LogOutput -LogType VERBOSE

                $EventArgs.Handled = $true

                if ($Script:MainForm.Elements.TextBoxUrl.IsEnabled -and $Script:MainForm.Elements.TextBoxUrl.Text -like "http*") {
                    "Triggering connect" | Write-LogOutput -LogType VERBOSE
                    Test-ConnectionButton
                    if ($Script:MainForm.Elements.ButtonConnect.IsEnabled) {
                        "Executing connection" | Write-LogOutput -LogType VERBOSE
                        $Script:MainForm.Elements.ButtonConnect.RaiseEvent([System.Windows.RoutedEventArgs]::new([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent))
                    }
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })