Converting from HTML output to GridView

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
cstewart28
Posts: 12
Joined: Mon Jan 12, 2015 1:24 pm

Converting from HTML output to GridView

Post by cstewart28 »

I'm trying to convert a script that outputs in HTML just fine, but I want to put it in GridView. The goal is to read a cvs file, then to and try to connect to it, if the web site does not work, then it gives the error response. I built the WinForm (First time), and put in a text field to hold the filename, and then when the buttonckeckcameras is clicked, it should put the output in the datagrid. All of a sudden I start to get an error:

MainForm.psf (76): ERROR: At Line: 76 char: 35
ERROR: + if (![string]::IsNullOrWhiteSpace <<<< ($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory }
ERROR: + CategoryInfo : InvalidOperation: (IsNullOrWhiteSpace:String) [], RuntimeException
ERROR: + FullyQualifiedErrorId : MethodNotFound
ERROR:
You selected the file: C:\temp\Cameras.csv
ERROR: += : The '+=' operator failed: Item has already been added. Key in dictionary: 'ResponseLength' Key being added: 'ResponseLength'.
ERROR:
MainForm.psf (116): ERROR: At Line: 116 char: 13
ERROR: + $Result += <<<< [Management.Automation.PSObject] @{
ERROR: + CategoryInfo : InvalidOperation: (System.Collections.Hashtable:PSObject) [], RuntimeException
ERROR: + FullyQualifiedErrorId : OperatorFailed
ERROR:
ERROR: += : The '+=' operator failed: Item has already been added. Key in dictionary: 'ResponseLength' Key being added: 'ResponseLength'.
ERROR:
MainForm.psf (116): ERROR: At Line: 116 char: 13
ERROR: + $Result += <<<< [Management.Automation.PSObject] @{
ERROR: + CategoryInfo : InvalidOperation: (System.Collections.Hashtable:PSObject) [], RuntimeException
ERROR: + FullyQualifiedErrorId : OperatorFailed
ERROR:
ERROR: += : The '+=' operator failed: Item has already been added. Key in dictionary: 'ResponseLength' Key being added: 'ResponseLength'.
ERROR:

MainForm.psf (116): ERROR: At Line: 116 char: 13
ERROR: + $Result += <<<< [Management.Automation.PSObject] @{
ERROR: + CategoryInfo : InvalidOperation: (System.Collections.Hashtable:PSObject) [], RuntimeException
ERROR: + FullyQualifiedErrorId : OperatorFailed
ERROR:

Not sure why I'm getting this error.


Below is the button action.

Code: Select all

$buttonCheckCameras_Click= {
	#TODO: Place custom script here
	$data = Import-Csv $CSVFileName.Text
	$buttonCheckCameras.Text = "Checking Camera's, Please Wait"
	
	Foreach ($item in $data)
	{
		$name = $item.name
		$address = $item.ip
		$username = $item.username
		$password = $item.password
		$time = try
		{
			$Request = $null
			$result1 = Measure-Command { $Request = Invoke-WebRequest -Uri $address }
			$result1.TotalMilliseconds
		}
		catch
		{
			$Request = $_.Exception.Response
			$time = -1
		}
		$Result += [Management.Automation.PSObject] @{
			Time = Get-Date
			Uri = $address
			Name = $name
			StatusCode = [int] $Request.StatusCode;
			StatusDescription = $Request.StatusDescription;
			ResponseLength = $Request.RawContentLength;
			TimeTaken = $time;
		}
	}
	#Fillin Datagrid
	$row = @("$($Entry.name)", "$($Entry.uri)", "$($Entry.StatusCode)", "$($Entry.StatusDescription)", "$($Entry.timetaken)")
	$datagridview.Rows.Add($row)
}
Here is the original code that works just fine.

Code: Select all

function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect)
{ 
    Add-Type -AssemblyName System.Windows.Forms
    $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openFileDialog.Title = $WindowTitle
    if (![string]::IsNullOrWhiteSpace($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory }
    $openFileDialog.Filter = $Filter
    if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
    $openFileDialog.ShowHelp = $true    # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE.
    $openFileDialog.ShowDialog() > $null
    if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
}

$filePath = Read-OpenFileDialog -WindowTitle "Select Camera CSV File" -InitialDirectory 'C:\' -Filter "CSV files (*.csv)|*.csv"
if (![string]::IsNullOrEmpty($filePath)) { Write-Host "You selected the file: $filePath" }
else { "You did not select a file." }

$csv = Import-Csv $filePath 
$Result = @()

Foreach($item in $csv)
{
	$name = $item.name
	$address = $item.ip
	$username = $item.username
	$password = $item.password
	$time = try
	{
		$Request = $null
		$result1 = Measure-Command {$Request = Invoke-WebRequest -Uri $address }
		$result1.TotalMilliseconds
	}
	catch
	{
	$Request = $_.Exception.Response
	$time = -1
	}
	$Result += [Management.Automation.PSObject] @{
		Time = Get-Date
		Uri	= $address
		Name = $name
		StatusCode = [int] $Request.StatusCode;
		StatusDescription = $Request.StatusDescription;
		ResponseLength = $Request.RawContentLength;
		TimeTaken = $time;
		}	
}
#Prepare Outut in HTML
if ($Result -ne $null)
{ 
    $Outputreport = "<HTML>
					<TITLE>Camera Availability Report</TITLE>
					<BODY background-color:peachpuff>
					<font color =""#99000"" face=""Microsoft Taile"">
					<H2> Camera Availability Report </H2></font>
					<Table border=1 cellpadding=5 cellspacing=5>
					<TR bgcolor=gray align=center>
					<TD><B>Camera ID</B></TD>
					<TD><B>IP Address</B></TD>
					<TD><B>Status Code</B></TD>
					<TD><B>Status Description</B></TD>
					<TD><B>Time Taken(ms)</B></TD</TR>" 
    
	Foreach($Entry in $Result) 
    { 
        if($Entry.StatusCode -ne "200") 
        { 
            $Outputreport += "<TR bgcolor=red>" 
        } 
        else 
        { 
            $Outputreport += "<TR>" 
        } 
        $Outputreport += "<TD>$($Entry.name)</TD>
						  <TD>$($Entry.uri)</TD>
						  <TD align=center>$($Entry.StatusCode)</TD>
						  <TD align=center>$($Entry.StatusDescription)</TD>
						  <TD align=left>$($Entry.timetaken)</TD></TR>" 
    } 
    $Outputreport += "</Table></BODY></HTML>" 
}
$OutputReport | Out-File C:\temp\CameraAvailability.htm
Invoke-Expression C:\Temp\CameraAvailability.htm
Last edited by cstewart28 on Tue Jan 13, 2015 9:10 am, edited 2 times in total.

User avatar
SAPIEN Support Forums
Posts: 945
Joined: Wed Dec 03, 2014 2:26 pm

Confering from HTML output to GridView

Post by SAPIEN Support Forums »

This is an automated post. A real person will respond soon.

Thank you for posting, cstewart28.

Here are some hints to help you get an accurate and complete answer to your question.

Ask in the best forum: If you asked in the wrong forum, just copy your question to the right forum.

Anticipate follow-up questions!

Did you remember to include the following?
  • 1. Product, version and build
    2. 32 or 64 bit product
    3. Operating system, e.g. Windows 7 64 bit.
    4. Attach a screenshot, if applicable
    5. Attach logs, crash reports, etc., in a ZIP file
If not, please take a moment to edit your original post or reply to this one.

*** Make sure you do not post any licensing information ***

jvierra
Posts: 14543
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Converting from HTML output to GridView

Post by jvierra »

Here is how to do this easily with objects. The function can be tested independently at a command prompt until it returns the objects as you like them to be built.

[powershell
function Get-CameraData{
Param($csvfile)
Import-Csv $csvfile |
ForEach-Object{
$item=$_
Try {
$timetaken=(Measure-Command { $Request=Invoke-WebRequest -Uri $item.ip }).TotalMilliseconds
}
Catch {
$Request=@{
StatusDescription=$_.Exception.Message
RawContentLength=0
StatusCode=-1
}
$timetaken=-1
}
[PSCustomObject]@{
Time=[datetime]::Now
Uri = $item.ip
Name = $item.name
Username = $item.username
Password = $item.password
StatusCode=$Request.StatusCode
StatusDescription=$Request.StatusDescription
ResponseLength=$Request.RawContentLength
TimeTaken = $timetaken
}
}
}
[/powershell]

Call into function
PowerShell Code
Double-click the code block to select all.
# code to call function from button
$buttonCheckCameras_Click = {
    $buttonCheckCameras.Text = "Checking Camera's, Please Wait"
    $cameradata = Get-CameraData $CSVFileName.Text
    $datagridview.DataSource = [System.Collections.ArrayList]$cameradata
}
This separates the Forms dependent pieces making it easier to test and debug outside of a form. After the function is working you can just call it in the button click and assign the object as the data source for the control.

User avatar
cstewart28
Posts: 12
Joined: Mon Jan 12, 2015 1:24 pm

Re: Converting from HTML output to GridView

Post by cstewart28 »

Thank you, however the information is not displayed.
Attachments
CameraCheckApp.png
CameraCheckApp.png (33.12 KiB) Viewed 2958 times

jvierra
Posts: 14543
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Converting from HTML output to GridView

Post by jvierra »

What do you get when you run the function at a command prompt - in PowerShell CLI.

User avatar
cstewart28
Posts: 12
Joined: Mon Jan 12, 2015 1:24 pm

Re: Converting from HTML output to GridView

Post by cstewart28 »

It works from the command line.

Thanks again

User avatar
cstewart28
Posts: 12
Joined: Mon Jan 12, 2015 1:24 pm

Re: Converting from HTML output to GridView

Post by cstewart28 »

How could I add a status bar or strip based on this so it progress each time one if the items are checked?

jvierra
Posts: 14543
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Converting from HTML output to GridView

Post by jvierra »

cstewart28 wrote:It works from the command line.

Thanks again
If you see it then it should work in the datagridview. Be sure to use the datagridview and be sure that you re no getting errors that you are not paying attention to in the output Window.

jvierra
Posts: 14543
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Converting from HTML output to GridView

Post by jvierra »

cstewart28 wrote:How could I add a status bar or strip based on this so it progress each time one if the items are checked?
Search the blog for posts on how to use the progressbar control.

User avatar
cstewart28
Posts: 12
Joined: Mon Jan 12, 2015 1:24 pm

Re: Converting from HTML output to GridView

Post by cstewart28 »

>> Building (CameraStatus) Project...
>> Merging 'Startup.pss' ...
>> Merging 'MainForm.psf' ...
>> Merging 'Globals.ps1' ...
>> Writing 'CameraStatus.Run.ps1' ...
>> Platform: V2 64Bit (STA)
You selected the file: C:\temp\Cameras.csv

No error is coming up..

Locked