lib/events/SqlHistoryForm.ps1

#######################################################################################################################################################
# WARNING: DO NOT EDIT THIS FILE AS IT IS GENERATED AND WILL BE OVERWRITTEN ON THE NEXT UPDATE! #
# #
# Generated via psake on: 2025-12-04T03:09:22.387Z #
# Version: 2025.12.4.2 #
# Copyright Fortigi (C) 2024-2025 #
#######################################################################################################################################################
#requires -Version 7.0

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

        $Script:MainForm.Elements.ButtonShowHistory.IsEnabled = $false

        Invoke-LoadSqlHistoryData
        $Script:SqlHistoryForm.State = "Open"
        Restore-MainFormFocus
    })

$Script:SqlHistoryForm.Definition.Add_Closing({
        $_ | Show-EventInfo
        Save-FormMeasurements
        $Script:SqlHistoryForm.State = "Closing"
        if ($Script:MainForm.State -eq "Open") {
            $false | Set-ConfigProperty -Property "SqlHistoryFormOpen"
        }
    })

$Script:SqlHistoryForm.Definition.Add_Closed({
        $_ | Show-EventInfo
        $Script:SqlHistoryForm.State = "Closed"
        $Script:MainForm.Elements.ButtonShowHistory.IsEnabled = $true
        Restore-MainFormFocus
    })
$Script:SqlHistoryForm.Elements.ButtonExportHistory.Add_Click({

        param (
            $Sender,
            $EventArgs
        )

        try {
            $_ | Show-EventInfo

            $SaveFileDialog = New-Object Microsoft.Win32.SaveFileDialog
            $SaveFileDialog.Title = "Export SQL History"
            $SaveFileDialog.Filter = "JSON Files (*.json)|*.json|CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
            $SaveFileDialog.DefaultExt = ".json"
            $SaveFileDialog.FileName = "SQL_History_$((Get-Date).ToString('yyyyMMdd_HHmmss'))"

            $Result = $SaveFileDialog.ShowDialog()

            if ($Result -eq $true) {
                $FilePath = $SaveFileDialog.FileName
                $Extension = [System.IO.Path]::GetExtension($FilePath).ToLower()

                $HistoryData = $Script:SqlHistoryForm.Elements.DataGridHistory.ItemsSource

                if ($null -eq $HistoryData -or $HistoryData.Count -eq 0) {
                    "No history data to export" | Write-LogOutput -LogType WARNING
                    return
                }

                switch ($Extension) {
                    ".csv" {
                        $HistoryData | Export-Csv -Path $FilePath -NoTypeInformation -Encoding UTF8
                    }
                    ".json" {
                        $HistoryData | ConvertTo-Json -Depth 3 | Set-Content -Path $FilePath -Encoding UTF8
                    }
                    default {

                        $TextContent = @()
                        $TextContent += "SQL Query History Export - Generated: $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))"
                        $TextContent += "=" * 80
                        $TextContent += ""

                        foreach ($Item in $HistoryData) {
                            $TextContent += "Change Date: $($Item.ChangeDate.ToString('yyyy-MM-dd HH:mm:ss'))"
                            $TextContent += "Changed By: $($Item.ChangedBy)"
                            $TextContent += "Change Type: $($Item.ChangeType)"
                            $TextContent += "Object: $($Item.SqlObjectName)"
                            $TextContent += "DoId: $($Item.DoId)"
                            $TextContent += ""
                            $TextContent += "Old Value:"
                            $TextContent += "-" * 40
                            $TextContent += $Item.OldValue
                            $TextContent += ""
                            $TextContent += "New Value:"
                            $TextContent += "-" * 40
                            $TextContent += $Item.NewValue
                            $TextContent += ""
                            $TextContent += "=" * 80
                            $TextContent += ""
                        }

                        $TextContent | Set-Content -Path $FilePath -Encoding UTF8
                    }
                }

                "SQL history exported to: $FilePath" | Write-LogOutput

                $OpenResult = [System.Windows.MessageBox]::Show(
                    "SQL history has been exported successfully.`n`nWould you like to open the exported file?",
                    "Export Complete",
                    [System.Windows.MessageBoxButton]::YesNo,
                    [System.Windows.MessageBoxImage]::Information
                )

                if ($OpenResult -eq [System.Windows.MessageBoxResult]::Yes) {
                    Start-Process $FilePath
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }
    })
$Script:SqlHistoryForm.Elements.ButtonRestoreQuery.Add_Click({
        param (
            $Sender,
            $EventArgs
        )

        try {
            $_ | Show-EventInfo

            $SelectedItem = $Script:SqlHistoryForm.Elements.DataGridHistory.SelectedItem

            if ($null -eq $SelectedItem) {
                "No history item selected" | Write-LogOutput -LogType WARNING
                return
            }

            $Result = [System.Windows.MessageBox]::Show(
                "Are you sure you want to restore this query version?`n`nChanged by: $($SelectedItem.ChangedBy)`nChange date: $($SelectedItem.ChangeDate.ToString('yyyy-MM-dd HH:mm:ss'))",
                "Confirm Query Restore",
                [System.Windows.MessageBoxButton]::YesNo,
                [System.Windows.MessageBoxImage]::Question
            )

            if ($Result -eq [System.Windows.MessageBoxResult]::Yes) {
                try {

                    if ($null -ne $Script:Webview.Object.CoreWebView2) {

                        $ScriptToExecute = "editor.setValue('{0}');" -f ($SelectedItem.OldValue -replace "`n", "\n" -replace "`r", "\r" -replace "`t", "\t" -replace "'", "\'")
                        Push-ToEditor -ScriptToExecute $ScriptToExecute
                        $Script:RunTimeData.CurrentQueryText = $SelectedItem.OldValue
                        "Query restored to editor!" | Write-LogOutput
                    }
                    "Query restored from history: {0}" -f $SelectedItem.ChangeDate.ToString('yyyy-MM-dd HH:mm:ss') | Write-LogOutput

                    $Script:SqlHistoryForm.Definition.Close()
                }
                catch {
                    "Failed to restore query from history" | Write-LogOutput -LogType ERROR -ErrorObject $_
                }
            }
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }

    })
$Script:SqlHistoryForm.Elements.DataGridHistory.Add_SelectedCellsChanged({
        param (
            $Sender,
            $EventArgs
        )

        try {
            $_ | Show-EventInfo
            $SelectedItem = $Sender.SelectedItem

            if ($null -eq $SelectedItem) {
                $Script:SqlHistoryForm.Elements.TextBoxOldValue.Text = ""
                $Script:SqlHistoryForm.Elements.TextBoxNewValue.Text = ""
                $Script:SqlHistoryForm.Elements.TextBoxDoId.Text = ""
                $Script:SqlHistoryForm.Elements.TextBoxObjectName.Text = ""
                $Script:SqlHistoryForm.Elements.TextBoxChangedBy.Text = ""
                $Script:SqlHistoryForm.Elements.TextBoxChangeDate.Text = ""
                $Script:SqlHistoryForm.Elements.RichTextBoxOldDiff.Document.Blocks.Clear()
                $Script:SqlHistoryForm.Elements.RichTextBoxNewDiff.Document.Blocks.Clear()
                $Script:SqlHistoryForm.Elements.ButtonRestoreQuery.IsEnabled = $false
                return
            }

            $Script:SqlHistoryForm.Elements.TextBoxOldValue.Text = $SelectedItem.OldValue
            $Script:SqlHistoryForm.Elements.TextBoxNewValue.Text = $SelectedItem.NewValue
            $Script:SqlHistoryForm.Elements.TextBoxDoId.Text = $SelectedItem.DoId
            $Script:SqlHistoryForm.Elements.TextBoxObjectName.Text = $SelectedItem.SqlObjectName
            $Script:SqlHistoryForm.Elements.TextBoxChangedBy.Text = $SelectedItem.ChangedBy
            $Script:SqlHistoryForm.Elements.TextBoxChangeDate.Text = $SelectedItem.ChangeDate.ToString("yyyy-MM-dd HH:mm:ss")

            $Script:SqlHistoryForm.Elements.ButtonRestoreQuery.IsEnabled = $true

            Invoke-GenerateDiffView -OldValue $SelectedItem.OldValue -NewValue $SelectedItem.NewValue

            "Selected history item: {0} - {1}" -f $SelectedItem.ChangeDate, $SelectedItem.ChangedBy | Write-LogOutput -LogType DEBUG
        }
        catch {
            $_.Exception.Message | Write-LogOutput -LogType ERROR -ErrorObject $_
        }

    })