#------------------------------------------------------------------------ # Source File Information (DO NOT MODIFY) # Source ID: 0f108260-d3b3-4fa7-b8c4-bef26d7f1442 # Source File: Test-DGV-with-DataTable-In-Debug-Mode-with-Retry-Button.psf #------------------------------------------------------------------------ #region File Recovery Data (DO NOT MODIFY) <#RecoveryData: MgkAAB+LCAAAAAAABAC9llmPozgQx98j5Tu05pXp5gwEqaclbkgghCRAwhshhnAnxpyfftM9o5mV Vntq1faLy5br5yqX/vbrDkR1B+Aohyh8egyatK6+faFfyC9v89nT06sN0yStwkJNC7AJS/B2AA16 ljXvuU/R9fl92yE8F+DZqJ5lcG6TZ6u+gO+LO4Dg+Cy2CNXVy62JX/E/ePtgqDUs37jYC8j1Wij6 XhAkW5aE700UJN4rUEdlghvfMAKn5OLk8g5XSERS7JIuzNDdkIZhWec3TPaaQEeqnXY0rVjzmTaQ uaZRKJeMCJu6I4dvV/4RHwVinVHDEld0s1SbfbNAwvqaImTI3GLKnVzFYe7c4Wl73OQ0GdqZot7m s1XuQ1CsiW6YbivU51JRS8rdqqeFzgXWKgCCDfNjLxFBTWjQ8cn2XgR3dz1cNqUj7DdEbGXUtRU3 kDbns+i0DO27cZCr0yXXZQ2sHUer9oWl3EY93O9O2EQ/TiaWl2M4VPmpRwOhlHZOrSbR7TeMaO31 RmaovYMT89m5X+0pMbmfpaHwXdbSjdB1GFw1tEnTFIffEbUXY+klk8T6SAm2OKmXKZdOxhGJjkkO Zbr1ws5KHuh8PjNIVwnLq0+bt3TPXNlMNxZbJ8VqovFrDrOP0tqJEko33D6S8HI9sdKFBHd5udau IxrMyRknGSzS7CAH85kraEbCJztToR1UciMrA/ykhT6OuXw80uM2SHKCG1COmihRNdhJ2wPs3G7C rstzfPOJNOHuPXgvEWM+E3YdcYqIRUdhrZ0CdaO659V1c9DwLt6YQGekdbTf+YQ9rBDjeoPEYByM JmcXwT53b9T9vNFV+bCrLeDOZw2TsELbV/SeG706gLu1b/mozqh0vHN3bCvyQ+GlMNU9rQW3QW+L 0ZRUcbUK8MM6qA6NcKWjQDdMTuwe9QbrsSot3q2YdnJkBxKGSdekoFB2qSzhAbCB3LOgXaxOoh9f UQNkT80WhRqfrnRMyqbgV2qFI19pj/NZmnuZWDe0txAQNuwv29CeiJsuMV7fNqvrfWVhWWjIO8zb sBLfyHIS2gm1lfPiGgnR0WdHlBBkzp4v4yNvVJpNoeZ72sA69tgTGmVadaxtSbYavJDgXWFrwRFn xlsXmOlkBRMFlSU7wJZFCMtg4d9tT2FNnMTJ+ewiG0R0YxZnY+mPsLG1uOX5PZ8FvrhiC6Xgl8ok GPRObGls8pQGZp55yWWG3mRnYWmaKbXRa+bELneFMJ91XLHjb4xRUckSx3pvMttt4sUNrd4avIXU oSdXj8wf5YcivOIfgvEhHULTgPJcpKD5sH/NjG/7sUGgfJFTCCJUw3EPYJdGoPn65P2QOeaFeO9f n6S2QC0E3yrQIhgWX5+27cNntAbjoc5B9e1M0PEi5mKSvCyIkA5f8Z+UP6H+gG1h/SB+DtIKqzAB JajQi9CiugzRA/iLTP9TMk2eY3q5YMMLzTKAXvwFuWyiGhbp+b/Ex3HhIlqwJE8zgFjyfxvfZzBe /LS61H3z8l5g/+nW/jXx/QH9HBAM+7RKPqUUj2XxKTFJNQT/P+in+V1VXvHf/5HefgN0/GprMgkA AA==#> #endregion <# .NOTES -------------------------------------------------------------------------------- Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2019 v5.6.167 Generated on: 18.08.2019 21:04 Generated by: Frank A.(Drew) Easton Organization: Easton Family -------------------------------------------------------------------------------- .DESCRIPTION GUI script generated by PowerShell Studio 2019 #> #---------------------------------------------- #region Application Functions #---------------------------------------------- #endregion Application Functions #---------------------------------------------- # Generated Form Function #---------------------------------------------- function Show-Test-DGV-with-DataTable-In-Debug-Mode-with-Retry-Button_psf { #---------------------------------------------- #region Import the Assemblies #---------------------------------------------- [void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') [void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') #endregion Import Assemblies #---------------------------------------------- #region Generated Form Objects #---------------------------------------------- [System.Windows.Forms.Application]::EnableVisualStyles() $formTestDGVDataTableTest = New-Object 'System.Windows.Forms.Form' $buttonRetryLoadingData = New-Object 'System.Windows.Forms.Button' $datagridview1 = New-Object 'System.Windows.Forms.DataGridView' $buttonOK = New-Object 'System.Windows.Forms.Button' $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState' #endregion Generated Form Objects #---------------------------------------------- # User Generated Script #---------------------------------------------- # Add-Type -AssemblyName Microsoft.VisualBasic # # $global:PowerShellHostName = $Host.Name $global:languageMode = $ExecutionContext.SessionState.LanguageMode.ToString().ToUpper() # # function Get-ScriptPathAndName { <# .SYNOPSIS Get-ScriptDirectory returns the proper location of the script. .OUTPUTS System.String .NOTES Returns the correct path within a packaged executable. #> [OutputType([string])] param () if ($hostinvocation -ne $null) { $hostinvocation.MyCommand.path } else { $script:MyInvocation.MyCommand.Path } } # # function Get-ScriptDirectory { <# .SYNOPSIS Get-ScriptDirectory returns the proper location of the script. .OUTPUTS System.String .NOTES Returns the correct path within a packaged executable. #> [OutputType([string])] param () if ($hostinvocation -ne $null) { Split-Path $hostinvocation.MyCommand.path } else { Split-Path $script:MyInvocation.MyCommand.Path } } # # [string]$scriptNameAndPath = Get-ScriptPathAndName [string]$scriptPath = Get-ScriptDirectory # [boolean]$global:sapienExportedScriptFile = $false # $global:scriptNameOnly = Split-Path -Path $scriptNameAndPath -Leaf # If ($global:scriptNameOnly.EndsWith(".Export.ps1")) { $global:sapienExportedScriptFile = $true } # $scriptFilenameExtensionONLY = $global:scriptNameOnly.ToUpper().Substring($($global:scriptNameOnly.LastIndexOf(".")) + 1) # # If (-not $global:languageMode.Equals("FULLLANGUAGE") -and $global:PowerShellHostName.ToUpper().Equals("CONSOLEHOST")) { # This will ONLY kick in if the *.Export.ps1 file is being run in a PowerShell console # It will be the LAST error message that is thrown Write-Error -Message "You are NOT running in `"FullLanguage`" mode and this script-Form will NOT work!" Pause Exit } # [boolean]$global:isStandaloneExecutable = $false # If ($global:PowerShellHostName.ToUpper().Equals("PRIMALSCRIPTHOSTIMPLEMENTATION") -and -not $scriptFilenameExtensionONLY.Equals("EXE")) { # This is the indicator that this is running in Debug Mode either in PrimalScript or PowerShell Studio $global:isStandaloneExecutable = $true } # $formTestDGVDataTableTest_Load = { [int]$global:timesThrough = 0 [int]$global:timesThroughWithoutErrors = 0 [int]$global:timesThroughWithErrors = 0 # [boolean]$global:isConversionToDataTableBroken = $false # [int]$global:conversionFirstBrokeAtTimeThrough = -1 # $buttonRetryLoadingData.Focus() # $formTestDGVDataTableTest.Show() # loadDataIntoDataGridView } # # function loadDataIntoDataGridView() { $buttonRetryLoadingData.Enabled = $false $datagridview1.DataSource = $null # $global:timesThrough++ # # This Start-Sleep call is here so that an End-User can see that this function IS running... Start-Sleep -Seconds 1 # [string]$message = "" # [collections.arraylist]$dataToDisplay = @(Get-ChildItem c:\Windows | Select-Object name, fullname, length, mode) # $message += toTheNthDegreeText -value $global:timesThrough $message += " time through" $message += "`n`n" $message += "`$dataToDisplay.GetType(): `"{0}`"" -f $dataToDisplay.GetType() $message += "`n`n" $message += "`$dataToDisplay.Count: `"{0:N0}`"" -f $dataToDisplay.Count $message += "`n`n" $message += "This is BEFORE the call to the ConvertTo-DataTable()" # # Place a Breakpoint at the next possible line of execution in PowerShell Studio after this line # The breakpoint MUST be AT or BEFORE the ConvertTo-DataTable() call # Write-Host "" Write-Host $message -ForegroundColor 'Green' # [void][System.Windows.Forms.MessageBox]::Show($message, "Original object info for: `"`$dataToDisplay`"") $message = "" # $dataToDisplayAsDataTable = ConvertTo-DataTable -InputObject $dataToDisplay # # When I put the value: "$dataToDisplayAsDataTable.Count" into the Watch panel for evaluation I got unexpected results # I NOW KNOW that the property .Count does NOT exist for a DataTable nor does .Length but I did not expect it to cause any errors in a script when added to the Watch panel # BUT the following method DOES exist and should NOT cause this. # You can also put this: "$dataToDisplayAsDataTable.GetType()" in the Watch panel and then set a breakpoint AT of BEFORE the ConvertTo-DataTable call # $message += toTheNthDegreeText -value $global:timesThrough $message += " time through" $message += "`n`n" $message += "`$dataToDisplayAsDataTable.GetType(): `"{0}`"" -f $dataToDisplayAsDataTable.GetType() $message += "`n`n" $message += "`$dataToDisplayAsDataTable.Rows.Count: `"{0:N0}`"" -f $dataToDisplayAsDataTable.Rows.Count $message += "`n`n" $message += "`$dataToDisplayAsDataTable.Columns.Count: `"{0:N0}`"" -f $dataToDisplayAsDataTable.Columns.Count # $message += "`n`n" $message += "This is AFTER the call to the ConvertTo-DataTable()" # $message += "`n`n" If ($dataToDisplayAsDataTable -is [System.Data.DataTable]) { $global:timesThroughWithoutErrors++ $global:isConversionToDataTableBroken = $false # $message += "The above object IS the expected type: `"System.Data.DataTable`"" $message += "`n`n" $message += "The `$datagridview1 will be FILE and WORK AS EXPECTED and desired. :-)" $neededForegroundColor = 'Green' } Else { $global:timesThroughWithErrors++ $global:isConversionToDataTableBroken = $true If ($global:conversionFirstBrokeAtTimeThrough -eq -1) { $global:conversionFirstBrokeAtTimeThrough = $global:timesThrough } # $message += "The above object is NOT the expected type! It is: `"{0}`" expected was `"System.Data.DataTable`"" -f $dataToDisplayAsDataTable.GetType() $message += "`n`n" $message += "The `$datagridview1 will be MESSED UP and WILL NOT work as expected and desired. :-(" $neededForegroundColor = 'Red' } # If ($global:timesThrough -gt 1) { $message += "`n`n" If ($global:timesThroughWithErrors -eq 0) { $message += "`nHave you tried setting a breakpoint AT or BEFORE the ConvertTo-DataTable() call?" $message += "`nYou also have to have something in the Watch panel where the `$datagridview1 has to be evaluated." $message += "`n(Putting either or both of these values `$dataToDisplayAsDataTable.Rows.Count and `$dataToDisplayAsDataTable.Columns.Count in the Watch panel will NOT cause this problem!)" $message += "`n(BUT `$dataToDisplayAsDataTable.Count THIS WILL! so does `$dataToDisplayAsDataTable.GetType())" } Else { If ($global:timesThroughWithoutErrors -eq 0) { If ($global:scriptNameOnly.EndsWith(".Export.ps1")) { $message += "Well I have NEVER SEEN this work with this script as an EXPORTed version of this file." } ElseIf ($global:scriptNameOnly.EndsWith(".Run.ps1")) { $message += "I have NEVER SEEN this happen in the RUN mode!" } Else { $message += "If you have a variable for the `$datagridview1 in the Watch panel that would explain that this a never worked not evem once!" } } Else { If (-not $global:isConversionToDataTableBroken -and $global:conversionFirstBrokeAtTimeThrough -ne -1) { $message += "Hey the conversion to DataTable IS WORKING again! GREAT!" } Else { $message += "I don't think that you will ever see this work again until this underlying problem is fixed" } } } } # [void][System.Windows.Forms.MessageBox]::Show($message, "Results of ConvertTo-DataTable") # Write-Host "" Write-Host $message -ForegroundColor $neededForegroundColor $message = "" # Update-DataGridView -DataGridView $datagridview1 -Item $dataToDisplayAsDataTable # $buttonRetryLoadingData.Enabled = $true $buttonRetryLoadingData.Focus() } # # function toTheNthDegreeText() { param ( [parameter(Mandatory = $true)] [int]$value ) [string]$suffix = "" [string]$result = "{0:N0}" -f $value # If ($result.EndsWith("11") -or $result.EndsWith("12") -or $result.EndsWith("13")) { $suffix = "th" } Else { If ($result.EndsWith("1")) { $suffix = "st" } elseif ($result.EndsWith("2")) { $suffix = "nd" } elseif ($result.EndsWith("3")) { $suffix = "rd" } else { $suffix = "th" } } # $result += $suffix # return $result } # # #region Control Helper Functions function Update-DataGridView { <# .SYNOPSIS This functions helps you load items into a DataGridView. .DESCRIPTION Use this function to dynamically load items into the DataGridView control. .PARAMETER DataGridView The DataGridView control you want to add items to. .PARAMETER Item The object or objects you wish to load into the DataGridView's items collection. .PARAMETER DataMember Sets the name of the list or table in the data source for which the DataGridView is displaying data. .PARAMETER AutoSizeColumns Resizes DataGridView control's columns after loading the items. #> Param ( [ValidateNotNull()] [Parameter(Mandatory = $true)] [System.Windows.Forms.DataGridView] $DataGridView, [ValidateNotNull()] [Parameter(Mandatory = $true)] $Item, [Parameter(Mandatory = $false)] [string] $DataMember, [System.Windows.Forms.DataGridViewAutoSizeColumnsMode] $AutoSizeColumns = 'None' ) $DataGridView.SuspendLayout() $DataGridView.DataMember = $DataMember # if ($null -eq $Item) { $DataGridView.DataSource = $null } elseif ($Item -is [System.Data.DataSet] -and $Item.Tables.Count -gt 0) { $DataGridView.DataSource = $Item.Tables[0] } elseif ($Item -is [System.ComponentModel.IListSource]` -or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView]) { $DataGridView.DataSource = $Item } else { $array = New-Object System.Collections.ArrayList # if ($Item -is [System.Collections.IList]) { $array.AddRange($Item) } else { $array.Add($Item) } $DataGridView.DataSource = $array } # if ($AutoSizeColumns -ne 'None') { $DataGridView.AutoResizeColumns($AutoSizeColumns) } # #$DataGridView.AutoSizeRowsMode = 'AllCellsExceptHeaders' # # foreach ($Column in $DataGridView.Columns) { If ($Column.Name.ToUpper().Equals("LENGTH")) { # This sets the alignment to the right side $Column.DefaultCellStyle.Alignment = 'MiddleRight' # This formats to Currency $Column.DefaultCellStyle.Format = "d" # This will AutoSize these columns and they CANNOT be changed by the End-User #$Column.AutoSizeMode = 'DisplayedCells' } } # $DataGridView.ResumeLayout() } # function ConvertTo-DataTable { <# .SYNOPSIS Converts objects into a DataTable. .DESCRIPTION Converts objects into a DataTable, which are used for DataBinding. .PARAMETER InputObject The input to convert into a DataTable. .PARAMETER Table The DataTable you wish to load the input into. .PARAMETER RetainColumns This switch tells the function to keep the DataTable's existing columns. .PARAMETER FilterWMIProperties This switch removes WMI properties that start with an underline. .EXAMPLE $DataTable = ConvertTo-DataTable -InputObject (Get-Process) #> [OutputType([System.Data.DataTable])] param ( $InputObject, [ValidateNotNull()] [System.Data.DataTable] $Table, [switch] $RetainColumns, [switch] $FilterWMIProperties ) # if ($null -eq $Table) { $Table = New-Object System.Data.DataTable } # if ($null -eq $InputObject) { $Table.Clear() return @( ,$Table) } # if ($InputObject -is [System.Data.DataTable]) { $Table = $InputObject } elseif ($InputObject -is [System.Data.DataSet] -and $InputObject.Tables.Count -gt 0) { $Table = $InputObject.Tables[0] } else { if (-not $RetainColumns -or $Table.Columns.Count -eq 0) { #Clear out the Table Contents $Table.Clear() # #Empty Data if ($null -eq $InputObject) { return } # $object = $null #find the first non null value foreach ($item in $InputObject) { if ($null -ne $item) { $object = $item break } } # # All null then empty if ($null -eq $object) { return } # #Get all the properties in order to create the columns foreach ($prop in $object.PSObject.Get_Properties()) { #filter out WMI properties if (-not $FilterWMIProperties -or -not $prop.Name.StartsWith('__')) { #Get the type from the Definition string $type = $null # if ($null -ne $prop.Value) { try { $type = $prop.Value.GetType() } catch { Out-Null } } # # -and [System.Type]::GetTypeCode($type) -ne 'Object') if ($null -ne $type) { [void]$table.Columns.Add($prop.Name, $type) } else { #Type info not found [void]$table.Columns.Add($prop.Name) } } } # if ($object -is [System.Data.DataRow]) { foreach ($item in $InputObject) { $Table.Rows.Add($item) } return @( ,$Table) } } else { $Table.Rows.Clear() } # foreach ($item in $InputObject) { $row = $table.NewRow() # if ($item) { foreach ($prop in $item.PSObject.Get_Properties()) { if ($table.Columns.Contains($prop.Name)) { if (-not [string]::IsNullOrEmpty($prop.Value)) { $row.Item($prop.Name) = $prop.Value If ($error[0]) { "`$item: `"$item`"" "`$prop.Name: `"$($prop.Name)`"" "`$prop.Value: `"$($prop.Value)`"" } } } } } [void]$table.Rows.Add($row) } } # return @( ,$Table) } #endregion $buttonRetryLoadingData_Click={ loadDataIntoDataGridView } # --End User Generated Script-- #---------------------------------------------- #region Generated Events #---------------------------------------------- $Form_StateCorrection_Load= { #Correct the initial state of the form to prevent the .Net maximized form issue $formTestDGVDataTableTest.WindowState = $InitialFormWindowState } $Form_Cleanup_FormClosed= { #Remove all event handlers from the controls try { $buttonRetryLoadingData.remove_Click($buttonRetryLoadingData_Click) $formTestDGVDataTableTest.remove_Load($formTestDGVDataTableTest_Load) $formTestDGVDataTableTest.remove_Load($Form_StateCorrection_Load) $formTestDGVDataTableTest.remove_FormClosed($Form_Cleanup_FormClosed) } catch { Out-Null <# Prevent PSScriptAnalyzer warning #> } } #endregion Generated Events #---------------------------------------------- #region Generated Form Code #---------------------------------------------- $formTestDGVDataTableTest.SuspendLayout() # # formTestDGVDataTableTest # $formTestDGVDataTableTest.Controls.Add($buttonRetryLoadingData) $formTestDGVDataTableTest.Controls.Add($datagridview1) $formTestDGVDataTableTest.Controls.Add($buttonOK) $formTestDGVDataTableTest.AcceptButton = $buttonOK $formTestDGVDataTableTest.AutoScaleDimensions = '6, 13' $formTestDGVDataTableTest.AutoScaleMode = 'Font' $formTestDGVDataTableTest.ClientSize = '678, 449' $formTestDGVDataTableTest.FormBorderStyle = 'FixedDialog' $formTestDGVDataTableTest.MaximizeBox = $False $formTestDGVDataTableTest.MinimizeBox = $False $formTestDGVDataTableTest.Name = 'formTestDGVDataTableTest' $formTestDGVDataTableTest.StartPosition = 'CenterScreen' $formTestDGVDataTableTest.Text = 'Test-DGV-with-DataTable-In-Debug-Mode-with-Retry-Button' $formTestDGVDataTableTest.add_Load($formTestDGVDataTableTest_Load) # # buttonRetryLoadingData # $buttonRetryLoadingData.Anchor = 'Bottom, Left' $buttonRetryLoadingData.AutoSize = $True $buttonRetryLoadingData.CausesValidation = $False $buttonRetryLoadingData.Location = '32, 413' $buttonRetryLoadingData.Name = 'buttonRetryLoadingData' $buttonRetryLoadingData.Size = '106, 24' $buttonRetryLoadingData.TabIndex = 1 $buttonRetryLoadingData.Text = 'Retry loading data' $buttonRetryLoadingData.UseCompatibleTextRendering = $True $buttonRetryLoadingData.UseVisualStyleBackColor = $True $buttonRetryLoadingData.add_Click($buttonRetryLoadingData_Click) # # datagridview1 # $datagridview1.AllowUserToAddRows = $False $datagridview1.AllowUserToDeleteRows = $False $datagridview1.ColumnHeadersHeightSizeMode = 'AutoSize' $datagridview1.Location = '32, 27' $datagridview1.MultiSelect = $False $datagridview1.Name = 'datagridview1' $datagridview1.ReadOnly = $True $datagridview1.SelectionMode = 'FullRowSelect' $datagridview1.Size = '634, 380' $datagridview1.TabIndex = 1 $datagridview1.TabStop = $False # # buttonOK # $buttonOK.Anchor = 'Bottom, Right' $buttonOK.DialogResult = 'OK' $buttonOK.Location = '591, 414' $buttonOK.Name = 'buttonOK' $buttonOK.Size = '75, 23' $buttonOK.TabIndex = 2 $buttonOK.Text = '&OK' $buttonOK.UseCompatibleTextRendering = $True $buttonOK.UseVisualStyleBackColor = $True $formTestDGVDataTableTest.ResumeLayout() #endregion Generated Form Code #---------------------------------------------- #Save the initial state of the form $InitialFormWindowState = $formTestDGVDataTableTest.WindowState #Init the OnLoad event to correct the initial state of the form $formTestDGVDataTableTest.add_Load($Form_StateCorrection_Load) #Clean up the control events $formTestDGVDataTableTest.add_FormClosed($Form_Cleanup_FormClosed) #Show the Form return $formTestDGVDataTableTest.ShowDialog() } #End Function #Call the form Show-Test-DGV-with-DataTable-In-Debug-Mode-with-Retry-Button_psf | Out-Null