lib/events/MainFormTabContent.ps1

#######################################################################################################################################################
# WARNING: DO NOT EDIT THIS FILE AS IT IS GENERATED AND WILL BE OVERWRITTEN ON THE NEXT UPDATE! #
# #
# Generated via psake on: 2026-08-13T03:34:33.263Z #
# Version: 2026.8.13.57 #
# Copyright Fortigi (C) 2024-2026 #
#######################################################################################################################################################
#requires -Version 7.0

$Script:MainForm.Elements.ButtonConnect.Add_Click({
        param($ClickSender, $ClickArgs)
        try {
            $_ | Show-EventInfo

            $OwningConnectTab = $Script:Tabs | Where-Object { $_.Elements.ButtonConnect -eq $ClickSender } | Select-Object -First 1
            if ($null -ne $OwningConnectTab -and $OwningConnectTab.Id -ne $Script:ActiveTabId) {
                Set-ActiveTabContext -TabSession $OwningConnectTab
            }

            if ($Script:MainForm.Elements.ButtonConnectText.Text -eq "_Connect") {
                $Script:RunTimeConfig.ReconnectStatus = 2

                $InteractiveAuthTypes = @("Browser", "WebView2", "Browser-InPrivate", "WebView2-InPrivate")
                $IsInteractiveAuth = $Script:MainForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem.Content -in $InteractiveAuthTypes

                if ($IsInteractiveAuth -and $Script:InteractiveLoginInProgress) {
                    "Another tab is completing sign-in, please wait and try again." | Write-LogOutput -LogType WARNING
                    return
                }

                $SiblingTabs = @()
                if ($IsInteractiveAuth) {
                    $Script:InteractiveLoginInProgress = $true
                    $CurrentTabId = $Script:ActiveTabId
                    $SiblingTabs = @($Script:Tabs | Where-Object { $_.Id -ne $CurrentTabId })
                    foreach ($Sibling in $SiblingTabs) {
                        $Sibling.Elements.ButtonConnect.IsEnabled = $false
                    }
                }

                try {
                    if (Test-OmadaConnection) {
                        Test-ConnectionSettings
                    }
                    if ($Script:ConnectionStatus) {
                        Update-QueryList -ForceRefresh
                        Update-DataConnectionList
                    }
                }
                finally {
                    if ($IsInteractiveAuth) {
                        $Script:InteractiveLoginInProgress = $false
                        $ReturnToTab = Get-ActiveTabSession
                        foreach ($Sibling in $SiblingTabs) {
                            Set-ActiveTabContext -TabSession $Sibling
                            Test-ConnectionButton
                        }
                        if ($null -ne $ReturnToTab) {
                            Set-ActiveTabContext -TabSession $ReturnToTab
                        }
                    }
                }
            }
            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
                }
                elseif ([string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxDisplayName.Text)) {
                    "The Display name cannot be empty. Enter a name before saving the query." | Write-LogOutput -LogType WARNING
                    $Script:MainForm.Elements.ButtonNewQuery.IsEnabled = $true
                }
                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
            }
            elseif ([string]::IsNullOrWhiteSpace($Script:MainForm.Elements.TextBoxDisplayName.Text)) {
                "The Display name cannot be empty. Enter a name before saving the query." | Write-LogOutput -LogType WARNING
                $Script:MainForm.Elements.ButtonSaveQuery.IsEnabled = $true
                $Script:MainForm.Elements.ButtonExecuteQuery.IsEnabled = $true
            }
            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"
            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"
            $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

                Get-SqlSchemaObject
            }

            $ActiveTab = Get-ActiveTabSession
            if ($null -ne $ActiveTab) {
                Update-TabHeaderTitle -TabSession $ActiveTab
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })

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

            if (-not $Script:ConnectionStatus) {
                "Not connected; skipping query list refresh." | Write-LogOutput -LogType DEBUG
                return
            }

            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
            }

            $ActiveTab = Get-ActiveTabSession
            if ($null -ne $ActiveTab) {
                Update-TabHeaderTitle -TabSession $ActiveTab
            }
        }
        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.TextBoxDisplayName.Add_TextChanged({
        try {
            $_ | Show-EventInfo -LogType VERBOSE2

            $ActiveTab = Get-ActiveTabSession
            if ($null -ne $ActiveTab) {
                Update-TabHeaderTitle -TabSession $ActiveTab
            }
        }
        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:AppConfig.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 $_
        }
    })