lib/events/events.ps1

#######################################################################################################################################################
# WARNING: DO NOT EDIT THIS FILE AS IT IS GENERATED AND WILL BE OVERWRITTEN ON THE NEXT UPDATE! #
# #
# Generated via psake on: 2025-01-13T01:31:24.204Z #
# Version: 2025.1.13.2 #
# Copyright Fortigi (C) 2025 #
#######################################################################################################################################################

#requires -Module OmadaWeb.PS
#requires -Version 7.0

$Script:RunTimeConfig.Logging.AppLogObject.add_CollectionChanged({

        try {
            Update-LogWindow
        }
        catch {
            Write-Host $_
        }
    })
$Script:MainWindowForm.Definition.Add_Closed({
        $_ | Show-EventInfo

        $Script:MainWindowForm.State = "Closed"
        $Script:MainWindowForm.Definition.Close()
    })

$Script:MainWindowForm.Definition.Add_Closing({
        $_ | Show-EventInfo
        $Script:MainWindowForm.State = "Closing"
        Save-WindowMeasurements
        if (Test-LogWindowOpen) {
            $Script:LogWindowForm.Definition.Close()
        }
        if (Test-SqlSchemaWindowOpen) {
            $Script:SqlSchemaWindowForm.Definition.Close()
        }
    })

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

            if ($Script:AppConfig.LogWindowFormOpen) {
                Open-LogWindow
            }

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

            if ($Null -eq $Script:Webview.Object) {
                [System.Windows.MessageBox]::Show("Failed to find WebView2 control.", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::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()
            }

            $Script:Webview.Object.EnsureCoreWebView2Async($Script:Webview.Environment).GetAwaiter().OnCompleted({
                    if ($Null -eq $Script:Webview.Object.CoreWebView2) {
                        $Script:MainWindowForm.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
                                [System.Windows.MessageBox]::Show($Message, "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::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:MainWindowForm.Definition.Dispatcher.Invoke([System.Action] {
                                [System.Windows.MessageBox]::Show("Monaco HTML file not found at: $HtmlPath", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
                            })
                    }
                    Test-ConnectionSettings

                    if ($Script:AppConfig.SqlSchemaWindowFormOpen) {
                        Open-SqlSchemaWindow
                    }
                    $Script:MainWindowForm.State = "Open"
                })

        }
        catch {
            [System.Windows.MessageBox]::Show("WebView2 initialization failed: $($_.Exception.Message)", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
        }
    })

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

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

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

        "MainWindow Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:MainWindowForm.Definition.Left, $Script:MainWindowForm.Definition.Top, $Script:MainWindowForm.Definition.Width , $Script:MainWindowForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
        if (Test-LogWindowOpen -and -not $Script:LogWindowForm.PositionManager.Synchronizing) {
            if ($Script:LogWindowForm.Definition.Left -lt 0 -or $Script:LogWindowForm.Definition.Top -lt 0) {
                "LogWindowForm is not suitable for processing. Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:MainWindowForm.Definition.Left, $Script:MainWindowForm.Definition.Top, $Script:MainWindowForm.Definition.Width , $Script:MainWindowForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                return
            }
            "LogWindow Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:LogWindowForm.Definition.Left, $Script:LogWindowForm.Definition.Top, $Script:LogWindowForm.Definition.Width , $Script:LogWindowForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
            $Script:LogWindowForm.PositionManager.Synchronizing = $true
            $Script:MainWindowForm.Definition.Dispatcher.Invoke({
                    $Script:LogWindowForm.Definition.Left = [Int]::Abs($Script:MainWindowForm.Definition.Left) + [Int]::Abs($Script:LogWindowForm.PositionManager.PositionOffSetLeft)
                    $Script:LogWindowForm.Definition.Top = [Int]::Abs($Script:MainWindowForm.Definition.Top) + [Int]::Abs($Script:LogWindowForm.PositionManager.PositionOffSetTop)
                    "LogWindow Position: {0}x{1}, Dimensions: {2}x{3}, PositionManagerOffSet: {4}x{5} (Id:{6})" -f $Script:LogWindowForm.Definition.Left, $Script:LogWindowForm.Definition.Top, $Script:LogWindowForm.Definition.Width , $Script:LogWindowForm.Definition.Height, $Script:LogWindowForm.PositionManager.PositionOffSetLeft, $Script:LogWindowForm.PositionManager.PositionOffSetTop, $ActionId | Write-LogOutput -LogType VERBOSE2
                    $Script:LogWindowForm.PositionManager.Synchronizing = $false
                }, [System.Windows.Threading.DispatcherPriority]::Render)
        }
        if (Test-SqlSchemaWindowOpen -and -not $Script:SqlSchemaWindowForm.PositionManager.Synchronizing) {
            $_ | Show-EventInfo -LogType VERBOSE2
            if ($Script:SqlSchemaWindowForm.Definition.Left -lt 0 -or $Script:SqlSchemaWindowForm.Definition.Top -lt 0) {
                "SqlSchemaWindowForm is not suitable for processing. Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:SqlSchemaWindowForm.Definition.Left, $Script:SqlSchemaWindowForm.Definition.Top, $Script:SqlSchemaWindowForm.Definition.Width , $Script:SqlSchemaWindowForm.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
                return
            }
            "SqlSchemaWindow Position: {0}x{1}, Dimensions: {2}x{3} (Id:{4})" -f $Script:SqlSchemaWindow.Definition.Left, $Script:SqlSchemaWindow.Definition.Top, $Script:SqlSchemaWindow.Definition.Width , $Script:SqlSchemaWindow.Definition.Height, $ActionId | Write-LogOutput -LogType VERBOSE2
            $Script:SqlSchemaWindowForm.PositionManager.Synchronizing = $true
            $Script:MainWindowForm.Definition.Dispatcher.Invoke({
                    $Script:SqlSchemaWindowForm.Definition.Left = [Int]::Abs($Script:MainWindowForm.Definition.Left) - [Int]::Abs($Script:SqlSchemaWindowForm.PositionManager.PositionOffSetLeft)
                    $Script:SqlSchemaWindowForm.Definition.Top = [Int]::Abs($Script:MainWindowForm.Definition.Top) - [Int]::Abs($Script:SqlSchemaWindowForm.PositionManager.PositionOffSetTop)
                    "SqlSchemaWindow Position: {0}x{1}, Dimensions: {2}x{3}, PositionManagerOffSet: {4}x{5} (Id:{6})" -f $Script:SqlSchemaWindowForm.Definition.Left, $Script:SqlSchemaWindowForm.Definition.Top, $Script:SqlSchemaWindowForm.Definition.Width, $Script:SqlSchemaWindowForm.Definition.Height, $Script:SqlSchemaWindowForm.PositionManager.PositionOffSetLeft, $Script:SqlSchemaWindowForm.PositionManager.PositionOffSetTop, $ActionId | Write-LogOutput -LogType VERBOSE2
                    $Script:SqlSchemaWindowForm.PositionManager.Synchronizing = $false
                }, [System.Windows.Threading.DispatcherPriority]::Render)
        }
    })

$Script:MainWindowForm.Elements.ButtonExecuteQuery.Add_Click({
        $_ | Show-EventInfo
        try {
            $Script:RunTimeData.StopWatch = [System.Diagnostics.Stopwatch]::StartNew()

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

            $Script:MainWindowForm.Elements.ButtonSaveQuery.IsEnabled = $False
            $Script:MainWindowForm.Elements.ButtonExecuteQuery.IsEnabled = $False
            $Script:MainWindowForm.Elements.ButtonExecuteQuery | Set-ButtonContent -Content "Executing..."
            $Script:MainWindowForm.Elements.ButtonShowOutput.IsEnabled = $False
            $Script:MainWindowForm.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
            }
            else {
                "Execute query" | Write-LogOutput
                Invoke-SaveAndExecuteQuery
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR
        }
    })
$Script:MainWindowForm.Elements.ButtonNewQuery.Add_Click({
        $_ | Show-EventInfo
        $Script:MainWindowForm.Elements.ButtonSaveQuery.IsEnabled = $False
        $Script:MainWindowForm.Elements.ButtonExecuteQuery.IsEnabled = $False
        try {
            if (!(Test-ConnectionRequirements)) {
                "Omada Url not set or Query not selected, cannot retrieve data!" | Write-LogOutput -LogType WARNING
            }
            else {

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

                    "Save query new query" | Write-LogOutput

                    Invoke-SaveQuery -NewQuery
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR
        }
    })
$Script:MainWindowForm.Elements.ButtonOpenOutputFile.Add_Click({
        $_ | Show-EventInfo
        "Open outputfile: {0}" -f $Script:RunTimeConfig.OutputFileName | Write-LogOutput
        & $Script:RunTimeConfig.OutputFileName
    })
$Script:MainWindowForm.Elements.ButtonRefreshQueries.Add_Click({
        $_ | 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
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR
            }
        }
    })
$Script:MainWindowForm.Elements.ButtonReset.Add_Click({
        $_ | Show-EventInfo
        "Reset" | Write-LogOutput -LogType LOG
        Reset-Application -ResetEditor
    })
$Script:MainWindowForm.Elements.ButtonSaveOutputFile.Add_Click({
        $_ | Show-EventInfo

        $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
        $SaveFileDialog.Filter = "Json files (*.json) | *.json | Csv files (*.csv) | *.csv | CliXml files (*.xml) | *.xml | Text files (*.txt) | *.txt | All files (*.*) | *.*"
        $SaveFileDialog.Title = "Save Output File"
        if (![string]::IsNullOrWhiteSpace($Script:AppConfig.LastOutputFolder)) {
            $SaveFileDialog.InitialDirectory = $Script:AppConfig.LastOutputFolder
        }
        if ([string]::IsNullOrWhiteSpace($Script:AppConfig.LastOutputFolder)) {
            ".json" | Invoke-ConfigSetting -Property "LastExtension"
        }
        $SaveFileDialog.DefaultExt = $Script:AppConfig.LastExtension
        $InvalidFileNameChars = [System.IO.Path]::GetInvalidFileNameChars()
        $SaveFileDisplayName = $Script:MainWindowForm.Elements.TextBoxDisplayName.Text
        if (![string]::IsNullOrWhiteSpace($SaveFileDisplayName)) {
            $SaveFileDisplayName = ($SaveFileDisplayName.ToCharArray() | ForEach-Object {
                    if ($InvalidFileNameChars -contains $_) {
                        "_"
                    }
                    $_
                }) -Join ""
        }
        else {
            $SaveFileDisplayName = "Output"
        }
        $SaveFileDialog.FileName = "SqlQuery_{0}_{1}_{2}_{3}_Output{4}" -f $Script:AppConfig.CurrentSqlQuery.DoId, $SaveFileDisplayName, $Script:AppConfig.CurrentDataConnection.DisplayName, [system.uri]::New($Script:AppConfig.BaseUrl).Host, $Script:AppConfig.LastExtension
        if ($SaveFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
            $Script:RunTimeConfig.OutputFileName = $SaveFileDialog.FileName
            "Save outputfile: {0}" -f $Script:RunTimeConfig.OutputFileName | Write-LogOutput

            if ($Null -eq $Script:RunTimeConfig.OutputFileName) {
                return
            }
            elseif ($Script:RunTimeConfig.OutputFileName -like "*.json") {
                $Script:RunTimeData.QueryResult | ConvertTo-Json -Depth 15 | Set-Content $Script:RunTimeConfig.OutputFileName -Encoding UTF8
            }
            elseif ($Script:RunTimeConfig.OutputFileName -like "*.csv") {
                $Script:RunTimeData.QueryResult.d.rows | Export-Csv -Path $Script:RunTimeConfig.OutputFileName -Delimiter ";" -NoTypeInformation -Encoding UTF8
            }
            elseif ($Script:RunTimeConfig.OutputFileName -like "*.xml") {
                $Script:RunTimeData.QueryResult | Export-Clixml -Path $Script:RunTimeConfig.OutputFileName -Depth 15
            }
            else {
($Script:RunTimeData.QueryResult.d.rows | Format-Table -AutoSize | Out-String -Width 10000000).Trim() | Set-Content $Script:RunTimeConfig.OutputFileName -Encoding UTF8
            }

            "Output file saved!" | Write-LogOutput -LogType DEBUG
            Split-Path $Script:RunTimeConfig.OutputFileName | Invoke-ConfigSetting -Property "LastOutputFolder"
            [System.IO.Path]::GetExtension($Script:RunTimeConfig.OutputFileName) | Invoke-ConfigSetting -Property "LastExtension"
            $Script:MainWindowForm.Elements.ButtonOpenOutputFile.IsEnabled = $True
        }
        else {
            "File was not saved!" | Write-LogOutput -LogType DEBUG
        }
    })
$Script:MainWindowForm.Elements.ButtonSaveQuery.Add_Click({
        $_ | Show-EventInfo
        $Script:MainWindowForm.Elements.ButtonSaveQuery.IsEnabled = $False
        $Script:MainWindowForm.Elements.ButtonExecuteQuery.IsEnabled = $False
        try {
            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-SaveQuery
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR
        }
    })


$Script:MainWindowForm.Elements.ButtonShowLog.Add_Click({
        $_ | Show-EventInfo
        if (Test-LogWindowOpen) {
            "Hide log" | Write-LogOutput -LogType DEBUG
            $Script:LogWindowForm.Definition.Close()
        }
        else {
            "Show log" | Write-LogOutput -LogType DEBUG
            Open-LogWindow
        }

    })
$Script:MainWindowForm.Elements.ButtonShowOutput.Add_Click({
        $_ | Show-EventInfo
        "Show output" | Write-LogOutput
        $Script:RunTimeData.QueryResult.d.rows | ConvertTo-Json -Depth 10 | Invoke-SanitizeJsonKeys | ConvertFrom-Json -Depth 10 | Out-GridView -Title ("{0} - {1}" -f $Form.Text, $Script:AppConfig.CurrentSqlQuery.FullName)
    })
$Script:MainWindowForm.Elements.ButtonShowSqlSchema.Add_Click({
        $_ | Show-EventInfo
        if (Test-SqlSchemaWindowOpen) {
            "Hide log" | Write-LogOutput -LogType DEBUG
            $Script:SqlSchemaWindowForm.Definition.Close()
        }
        else {
            "Show schema" | Write-LogOutput -LogType DEBUG
            Open-SqlSchemaWindow
        }
    })
$Script:MainWindowForm.Elements.CheckboxMyQueries.Add_Checked({
        $_ | Show-EventInfo

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

        $True | Invoke-ConfigSetting -Property "MyQueriesOnly"

        $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 | Invoke-ConfigSetting -Property "IdentityUserName"
            }
        }
        else {
            $null | Invoke-ConfigSetting -Property "IdentityUserName"
        }
        "Force update query list" | Write-LogOutput -LogType DEBUG
        Update-QueryList -ForceRefresh
    })

$Script:MainWindowForm.Elements.CheckboxMyQueries.Add_Unchecked({
        $_ | Show-EventInfo
        $False | Invoke-ConfigSetting -Property "MyQueriesOnly"
        $null | Invoke-ConfigSetting -Property "IdentityUserName"
        "Force update query list" | Write-LogOutput -LogType DEBUG
        Update-QueryList -ForceRefresh
    })
$Script:MainWindowForm.Elements.ComboBoxSelectAuthenticationOption.Add_GotFocus({
        $_ | Show-EventInfo
        if ($null -eq $Script:MainWindowForm.Elements.ComboBoxSelectAuthenticationOption.SelectedItem) {
            $Script:RunTimeConfig.AuthenticationSet = $false
        }
        else {
            $Script:RunTimeConfig.AuthenticationSet = $true
        }
    })

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

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

        if ($Script:RunTimeConfig.AuthenticationSet -and ![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxURL.Text)) {
            Set-OmadaUrl
        }
        Test-ConnectionSettings

    })

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

        if ($null -eq $Script:MainWindowForm.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:MainWindowForm.Elements.TextBoxURL.Text)) {
                Set-OmadaUrl
            }
            Test-ConnectionSettings
        }

    })
$Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.Add_DropDownOpened({
        $_ | Show-EventInfo
        try {
            if (($Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.Items | Measure-Object).Count -le 0) {
                Update-DataConnectionList
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR
        }
    })


$Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.Add_SelectionChanged({
        $_ | Show-EventInfo

        try {
            if (($Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.Items | Measure-Object).Count -le 0) {
                Update-DataConnectionList
            }
            if (![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content)) {
                $Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content | Invoke-ConfigSetting -Property "CurrentDataConnection"

                if (![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content) -and $Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content -ne " - ") {
                    $Script:MainWindowForm.Elements.ComboBoxSelectDataConnection.SelectedItem.Content | Invoke-ConfigSetting -Property "CurrentDataConnection"
                    $Script:MainWindowForm.Elements.TextBlockDatabaseName.Text = $Script:AppConfig.CurrentDataConnection.DisplayName

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

$Script:MainWindowForm.Elements.ComboBoxSelectQuery.Add_DropDownOpened({
        $_ | Show-EventInfo
        try {
            if (($Script:MainWindowForm.Elements.ComboBoxSelectQuery.Items | Measure-Object).Count -lt 1) {
                "Update query list" | Write-LogOutput -LogType DEBUG
                Update-QueryList
                Update-DataConnectionList

            }
        }
        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
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR
            }
        }

    })

$Script:MainWindowForm.Elements.ComboBoxSelectQuery.Add_SelectionChanged({
        $_ | Show-EventInfo
        try {
            $Script:RunTimeData.CurrentSqlQuery.FullName = $Script:MainWindowForm.Elements.ComboBoxSelectQuery.SelectedItem.Content
            if (($Script:MainWindowForm.Elements.ComboBoxSelectQuery.Items | Measure-Object).Count -ge 0 -and ![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.ComboBoxSelectQuery.SelectedItem.Content)) {
                Set-EditorValue
            }

        }
        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
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR
            }
        }

    })


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

            "Password set to: {0}" -f "***********" | Write-LogOutput -LogType DEBUG
            if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                if (![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxUserName.Text) -and ![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxPassword.Password)) {
                    "Create/Update credential with username {0}" -f $Script:MainWindowForm.Elements.TextBoxUserName.Text | Write-LogOutput -LogType DEBUG
                    $Script:MainWindowForm.Elements.TextBoxUserName.Text | Invoke-ConfigSetting -Property "UserName"
                    $Script:RunTimeData.RestMethodParam.Credential = [System.Management.Automation.PSCredential]::new($Script:AppConfig.UserName, ($Script:MainWindowForm.Elements.TextBoxPassword.Password | ConvertTo-SecureString -AsPlainText -Force))
                }
            }
            "Password set" | Write-LogOutput
            Test-ConnectionSettings
        }
        if ([string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxPassword.Password)) {
            if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                "Clear credential because password is empty" | Write-LogOutput -LogType DEBUG
                $Script:RunTimeData.RestMethodParam.Credential = $Null
            }
            "Password cannot be empty!" | Write-LogOutput
        }
    })

$Script:MainWindowForm.Elements.TextBoxURL.Add_GotFocus({
        $_ | Show-EventInfo
        try {
            if (![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxURL.Text) -and $Script:MainWindowForm.Elements.TextBlockUrl.Text -like "http*.omada.cloud" -and $Script:MainWindowForm.Elements.TextBlockUrl.Text -ne $Script:CurrentUrl) {
                $Script:CurrentUrl = $Script:MainWindowForm.Elements.TextBlockUrl.Text
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR
        }
    })

$Script:MainWindowForm.Elements.TextBoxURL.Add_LostFocus({
        $_ | Show-EventInfo
        try {
            Set-OmadaUrl
            Test-ConnectionSettings
        }
        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
            }
            else {
                $_.Exception.Message | Write-LogOutput -LogType ERROR
            }
            Reset-Application -SkipTextBoxURL
        }
    })

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

            $Script:MainWindowForm.Elements.TextBoxUserName.Text | Invoke-ConfigSetting -Property "UserName"
            "Username set to: {0}" -f $Script:AppConfig.UserName | Write-LogOutput -LogType DEBUG
            if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                if (![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxUserName.Text) -and ![string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxPassword.Password)) {
                    "Create/Update credential with username {0}" -f $Script:MainWindowForm.Elements.TextBoxUserName.Text | Write-LogOutput -LogType DEBUG
                    $Script:RunTimeData.RestMethodParam.Credential = [System.Management.Automation.PSCredential]::new($Script:AppConfig.UserName, ($Script:MainWindowForm.Elements.TextBoxPassword.Password | ConvertTo-SecureString -AsPlainText -Force))
                }
            }
            "Username set!" | Write-LogOutput
            Test-ConnectionSettings
        }
        if ([string]::IsNullOrWhiteSpace($Script:MainWindowForm.Elements.TextBoxUserName.Text)) {
            if ($Script:RunTimeData.RestMethodParam.ContainsKey("Credential")) {
                "Clear credential because username is empty" | Write-LogOutput -LogType DEBUG
                $Script:RunTimeData.RestMethodParam.Credential = $Null
            }
            "Username cannot be empty!" | Write-LogOutput -LogType DEBUG
        }

    })
$Script:Webview.Object.add_NavigationCompleted({
        $_ | Show-EventInfo
        "Set-EditorValue after loading html" | Write-LogOutput -LogType DEBUG
        Set-EditorValue


    })