Posts Tagged ‘Development’

So, the Windows PowerShell 2.0 Software Development Kit is basically a collection of samples, and it has been released separately from the Windows Platform SDK for a change, making the download a tiny 2.35MB …

There are lots of examples in there in C# (no other languages), and honestly, some of them ought to make it into PSCX or some other project where people could grab pre-compiled versions ;)

  • A Template for creating PSProviders, and a sample PSProvider (for Access databases).
  • A sample of participating in Transactions (a set of “transacted comment” cmdlets for creating comments that go along with a transaction).
  • Example cmdlets: Select-Object, Select-String, Get-Process, Stop-Process
  • Dealing with issues with Serialization in PowerShell
  • PowerShell Eventing:
    • Deriving from ObjectEventRegistrationBase to create Register-FileSystemEvent
    • Receiving notifications from PowerShell Events on remote computers.
    • Hosting APIs, including (among others):
    • Restricted runspaces
    • Runspace pools
    • Remote runspaces (and remote runspace pools)
    • Running commands in parallel or sequentially
    • Calling Cmdlets and passing parameters
  • Reproducing the default PowerShell.exe output

Honestly, if you’re a developer that’s been wondering about learning to code cmdlets, or host PowerShell as a scripting engine, now’s the time.

Microsoft has been very busy this year … and in these last couple of months before the general availability of Windows 7, they’re trying very hard to crank out the tools necessary to encourage development of Windows 7 applications.

The first tool out of the gate, of course, was the Windows API Code Pack for the .Net framework. A nice library that makes it simple to write applications that take advantage of new Windows Vista and Windows 7 features like Libraries, Task panes and jump lists. Of course, that library has a major problem: it’s got an ugly and confusing license. Rather than using one of the standard Microsoft Open Source Licenses, the team used a license from the dark ages that features the vague “Excluded Licenses” clause and other ugly terminology.

More recently, Microsoft has announced a Platform Update for Vista which is intended to allow Vista to run most applications designed for Windows 7. The Platform Update is a set of runtime libraries which includes the Windows Ribbon control; Automation Manager Library; DirectX updates for hardware acceleration; DirectCompute for hardware-accelerated parallel computing support; the XPS printing library; the Windows Automation API; and the Windows Portable Devices Platform, which standardizes data transfers across apps and portable devices. This important package will be made available through Windows Update (and applications will be able to prompt you to download it) and it is in public beta with more information on the Windows Team blog. A couple of pieces of that will be made available for Windows XP; particularly the Automation API, which allows accessibility tools and test automation tools to access Windows user interface in a consistent way — this will mean that the next release of WASP will work flawlessly across Windows XP, Vista, and Windows 7.

Also in the works is the Remote Desktop Connection 7.0 (RDC7) client for Windows XP and Windows Vista to allow these older clients to take advantage of all new server features in Windows 7 and Windows Server 2008, including multi-monitor support and media redirection. There’s more information about that on the Remote Desktop team blog.

And finally, the release candidate for the Windows Management Framework (WMF) is also available. The WMF will include WinRM (Microsoft’s implementation of the WS-Management spec), PowerShell 2.0, and BITS for Server 2008, Windows Vista, Server 2003, and of course, Windows XP. This means that if you’re on Vista, or still using Windows XP, you can now upgrade from the PowerShell 2.0 CTP 3 to this release candidate and expect remoting to work!

All of these should be seeing final releases in the very near future, and some of them possibly by the time Windows 7 is released to the public.

Reblog this post [with Zemanta]

[new] Updated to PowerBoots 0.1

An introduction to PowerBoots

Please excuse me if I start by just copying the basic ideas of the Shoes Tutorial, but I figured that since PowerBoots is inspired by Shoes, that was as good a place as any to start. PowerBoots (or just “Boots”) is a PowerShell 2.0 module with functions for writing Windows Presentation Framework (WPF) applications in the PowerShell scripting language. You should get the latest version of PowerBoots before continuing, and install it by putting the “PowerBoots” folder in one of your “Modules” folders (list them by typing $Env:PSMODULEPATH in PowerShell v2).

Don’t forget to start PowerShell.exe with the STA parameter (This is no longer required in PowerBoots 0.1).

Did I hear someone ask what is WPF? It was introduced as part of .Net 3.0 (and vastly improved in .Net 3.5), so you can expect to find it preinstalled on computers from Vista on, and of course you can download and install it on XP if it’s not already installed. The only thing you really need to know about WPF for the purposes of this tutorial is that it is the new GUI toolkit for .Net, and that it is container based — you put elements into other elements to control the layout, rather like HTML and Java Swing… you can pick up the rest as we go along.

A simple Boots program


New-BootsWindow -SizeToContent WidthAndHeight -Content (
   Button -Content "Push Me"
)

 

The parenthesis ( and ) are a container, so the button is “in” the Window. You can also pass a ScriptBlock instead, which works basically the same way. Of course, this is a bit uglier than the Shoes syntax, so lets see if we can’t clean it up some. The -Content parameter is positional, so the first non-named argument you pass will be used for that. The same is true for the -Children parameter of panels, and in fact, each of the other similar parameters: Items, Blocks, and Inlines.

We have used a function New-BootsWindow which has an alias Boots. Boots takes all the same parameters as the Window function mentioned previously, but it uses slightly more useful defaults, and has a few other major benefits as well, the first of which is that it automatically “shows” the window, and the second is that it supports an -Async parameter which allows the window to come out in a new thread so that you can continue using PowerShell while the window remains alive and responsive. There is one catch: New-BootsWindow cannot take it’s content on the pipeline (the old function, now renamed “Out-BootsWindow” can take pipeline content, but is a script function, and requires -STA mode) — you have to specify it as a ScriptBlock. So now that we know this, we can rewrite our first example like this:


Boots { Button -Content "Push Me" }
 

Just for the record, the simplest Boots program would just be a simple popup dialog to put some text in a Window, like: Boots { $msg }

We can put controls in a stack


Boots {
   StackPanel {
      Button "A bed of clams"
      Button "A coalition of cheetas"
      Button "A gulp of swallows"
   }
}
 

StackPanels are awesome. So are WrapPanels. Try that code with a WrapPanel instead of a StackPanel and see what the difference is. This brings up another point: those positional parameters we mentioned earlier: Content, Children, Items, Blocks, and Inlines, are also set to accept the value from the pipeline. Not only that, but they are intelligent about whether or not the content model accepts multiple items! So we can actually rewrite that script like this, and get the same results:


Boots { "A bed of clams", "A coalition of cheetas", "A gulp of swallows" | Button | StackPanel }
 

Now we’re really onto something! Read the rest of this entry »

Someone asked on the PowerShell Newsgroup about writing Advanced Functions, and specifically:

looking for a … guide to putting together an advanced function that is visible and usable every time I start Powershell. By visible I mean that when I do a ‘get-command’ I want my [advanced function]s to be listed alongside all the regular cmdlets. What makes that possible? ... what do I need to do to make that happen? Whats the difference between an [advanced function] and a module?

There are lots of articles on the Microsoft PowerShell team blog about both topics, but it seems there’s not really been any sort of step-by-step written, so I posted this to the newsgroup, and since the person who asked the original question said he found it useful, I figured I’d share it here…

Read the rest of this entry »

Awhile back I wrote a series of posts about WPF From PowerShell From PowerShell” which were about how you could load XAML in previous PowerShell 2 CTPs to create WPF user interfaces … a few people have mentioned loading XAML in PowerBoots, and a couple of people have posted other samples showing XAML even since I published the most recent release, so I figure it’s time to point out that you really can load that XAML into Boots, and get all the threading and other support.

Just for fun, I’m going to rehash an earlier post about updating windows to show how you can go about this using PowerBoots, and hopefully show that it’s a little easier (and a lot more async). Compare and contrast the code in this article with that one, just for fun.

This works with any version of PowerShell

Unlike the original article, most this code (except where explicitly mentioned) works on either PowerShell v2 with PowerBoots, or PowerShell 1.0 with PoshWPF, a snapin that is part of the PowerBoots module but is also released separately… Also, unlike those previous posts, this does not require you to be running PowerShell.exe with the -STA switch, since the New-BootsWindow cmdlet takes care of threading for us.

Read the rest of this entry »

WPF uses a concept called “Attached Properties” to handle certain things, like when you put controls into a DockPanel. Basically, anything you put inside a DockPanel has a property “Dock” which you can set … but because the property is actually defined by the DockPanel, it doesn’t show up in PowerBoots, so you can’t just say -Dock "Bottom" when you create the child items … at least, not yet.

I’m still thinking about the best way for me to expose this in PowerBoots, because the problem is that attached properties can get attached several ways, and not just on direct children of an element. So I wanted to show you a way that you can do it for now so you can at least use the DockPanel effectively:

Boots {
   DockPanel -LastChildFill $true {
      DockPanel -LastChildFill $true {
         Button "OK" -Padding "2,0,2,0" |
            ForEach-Object { $_.SetValue(
               [System.Windows.Controls.DockPanel]::DockProperty,
               [System.Windows.Controls.Dock]::Right)
               $_
            }
         TextBox -HorizontalAlignment Stretch
      } | ForEach-Object { $_.SetValue(
               [System.Windows.Controls.DockPanel]::DockProperty,
               [System.Windows.Controls.Dock]::Bottom)
               $_
            }
      TextBox -AcceptsReturn $true -minWidth 300 -minHeight 200
   }
}

A better way …

Here’s what I’m thinking about for the next release of PowerBoots (you can take this and use it now, if you like it, but I’m really looking for, uhm … better ideas). Basically, I have written a function: Set-AttachedProperty, which takes an attached property and a value, and passes through the element on the pipeline. You may want to use this in conjunction with the module I published awhile back for creating type accelerators, because it lets you run a line like this:

Add-Accelerator DockPanel System.Windows.Controls.DockPanel

Which will let you substitute [DockPanel] for [System.Windows.Controls.DockPanel] … and of course, you can use it for all the types you want to use attached properties from, and it’s a real lifesaver if you need to use a bunch of them. Of course, in this particular example, we really only need to use a single attached property, so it’s enough to define that property ahead of time:

$DockProperty = [System.Windows.Controls.DockPanel]::DockProperty

Then you can use the Set-AttachedProperty function through an alias sap, and rewrite that huge block above like this:

Boots {
   DockPanel -LastChildFill $true {
      DockPanel -LastChildFill $true {
         Button "OK" -Padding "2,0,2,0" | sap $DockProperty Right
         TextBox -HorizontalAlignment Stretch
      } | sap $DockProperty Bottom
      TextBox -AcceptsReturn $true -minWidth 300 -minHeight 200
   }
}

Pretty slick, right? And it will even print out the list of values in the error message if you invoke it with an invalid value against an enum property like dock: sap $DockProperty "" … The problem I have with it is that you have to predefine your $DockProperty variable, and you can’t just define it against the root class. So I’m trying to find a way to tweak the dynamic property generation to make it so that the pipe into | sap $DockProperty Bottom can just be a parameter to the original element: -Dock Bottom … if I can’t find that, in the worst case scenario, I’ll just add an -AttachedProperties parameter with a hashtable of $DockProperty,“Bottom” or something … what do you think?

In any case, here’s the sap function, for now, and remember to use it as part of the pipeline:


function Set-AttachedProperty {
[CmdletBinding()]
PARAM(
   [Parameter(Position=0,Mandatory=$true)
   [System.Windows.DependencyProperty]
   $Property
,
   [Parameter(Mandatory=$true,ValueFromPipeline=$true)
   $Element
)
DYNAMICPARAM {
   $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
   $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter
   $Param1.Name = "Value"
   # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) )
   $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) )
   $Param1.ParameterType = $Property.PropertyType
           
   $paramDictionary.Add("Value", $Param1)
   
   return $paramDictionary
}
PROCESS {
   $Element.SetValue($Property, $Param1.Value)
   $Element
}
}

New-Alias sap Set-AttachedProperty
 

Announcing the release of PowerBoots 0.1

This release of PowerBoots is the most exciting release software I’ve cranked out in awhile. It finally has almost all of the features that I have thought of so far (we’re still missing proper support for attached properties).

  • You can create pretty much any WPF element, including ones I haven’t thought of adding yet (use Add-BootsFunction to add a new assembly or a single type).
  • You can create graphical user interfaces from PowerShell 1.0 all the way to the latest PowerShell 2.0 CTP.
  • You can create your WPF GUIs -Async in their own threads, or inline in PoshConsole, or as synchronous dialogs that return values when they close.
  • You can capture screenshots of your UIs (eg: generate .jpg charts from Visifire). You can even do so without displaying them!
  • You can take advantage of XAML Data Templates to generate graphical representations of any objects in the PowerShell pipeline.
  • You can add to, or modify your running GUIs from the command line.

You can read the “and much much more” between the lines right?

Read the rest of this entry »

I’ve finally finished the first public release of PoshWpf, and was getting ready to ship it as part of a new release of my PowerBoots module. The idea is that I need PoshWpf itself to be a stand-alone module so that it can be used in production with PowerShell 1.0, until such time as PowerShell 2.0 goes gold, and we can get that into production use, so we can use PowerBoots. PowerBoots is a script module, and it uses dynamic parameters, so most of it can’t really be done in v1, but you can use PoshWpf as a snapin, including the New-PowerBoots cmdlet, to do asynchronous multi-threaded UIs like my “ping monitor demo.”

So I need to update the .psd1 Module Metadata file for PowerBoots to include PoshWpf … I read up on Oisin Grehan’s blog about the possible properties in the module manifest, and decide that I could do this by packaging PoshWpf as a NestedModule in PowerBoots. There’s not a whole lot of point in distributing PoshWpf as it’s own module — Version 1 users will need to install it as a Snapin anyway, since PowerShell 1.0 doesn’t support modules, and I expect PowerShell 2.0 users to use it with PowerBoots.

Nested Modules

So I open up the PowerBoots.psd1 file, and add the line: NestedModules="PoshWpf" and fire up PowerShell and run Import-Module PowerBoots … and get this Error:
Import-Module : The module to process ‘PowerBoots’, listed in module manifest ‘C:\Users\Joel\Documents\WindowsPowerShell\Modules\PowerBoots\PowerBoots.psd1’ was not processed because no valid module was found in any module directory.

Now, I have no idea what that’s supposed to mean, except that I know the way that the PowerBoots.psm1 script gets parsed is that the PowerBoots.psd1 metadata includes a line: ModuleToProcess="PowerBoots.psm1" … I don’t know why the error doesn’t say “.psm1”, and I don’t know why that would be the error when what I added was the PoshWpf line, but I comment my line out and everything works, so I decide that maybe I need to say “PoshWpf.dll” (following the example that works of loading the PowerBoots script by specifying the full extension).

So I move PoshWpf.dll from it’s subdirectory right into the PowerBoots folder, and I change my line to: NestedModules="PoshWpf.dll" and fire up PowerShell and run Import-Module PowerBoots … and get this Error: Import-Module : An item with the same key has already been added.

Wow, I’m two for two: two attempts to load my module, two completely incomprehensible errors.

Read the rest of this entry »

Once I started playing with the new ability, introduced in PowerBoots 0.0.4 to easily add support for new graphical controls to PowerBoots, I found all sorts of fun widgets out there in open-source land. I’ll write about a few of them in the future, but for now I’m just going to stick with Visifire. After playing with a few examples, I finally got around to actually trying to create the graphs I needed at work which were the main source of motivation for trying to do Visifire from PowerShell anyway …

The problem was, half of the need we have for graphs is to throw them up on a web-server … so I needed a way to take the WPF window, and capture the controls and visuals as an image. Basically, render the WPF control to a bitmap image, instead of to the screen. To cut a long story short, I figured it out of course — why else would I be writing this? (get it here).

Out-BootsImage

So the new version of PowerBoots includes the Out-BootsImage function (aliased as BootsImage and “obi”), which basically is designed to take the filename of an image, and a boots visual element, and create a screenshot. It can generate bmp, gif, jpg, png, tiff, and even Microsoft’s new wdp format, or it can output to clipboard.

It’s late, so I’m not going to write any more about this … the bottom line is, if you have been looking for a (free) way to generate graphs and charts to image files in PowerShell, this will work for you: go grab Visifire, check out their gallery for inspiration, and start churning out graphs! Just for fun, here are the samples from the help documentation (except, this is the actual script I ran, including the upload code) with screen-shots …

Important note

When producing images of Visifire charts using this method, it is absolutely critical that you must specify -Animation $false because otherwise you will consistenly produce images of empty charts (since by default Visifire animates all of the bars onto the screen right after the SourceInitialized event that I use to capture the image). Oh, and if you need to remove the Visifire.com watermark, there is a -watermark $false parameter on the Chart element, which turns it off.


$credential = Get-Credential

Chart -Width 200 -Height 150 -Theme Theme3 -Watermark $false -Animation $false (
   DataSeries $(
      1..(Get-Random -min 3 -max 6) | ForEach-Object  {
         DataPoint -YValue (Get-Random 100)
      }
   )
) | Out-BootsImage VisiFire-BootsImage.jpg |ForEach-Object {
   Send-FTP HuddledMasses.org $credential -LocalFile $_ -Remotefile "$imgPath/$($_.Name)"
   [Windows.Clipboard]::SetText( "!http://huddledmasses.org/images/PowerBoots/$($_.Name)!" )
}

StackPanel -Margin "10,5,10,5" $(
   Label "Please enter your name:"
   StackPanel -Orientation Horizontal $(
      TextBox -OutVariable global:textbox -Width 150 -On_KeyDown {
         if($_.Key -eq "Return") {
            Write-Output $textbox[0].Text
            $BootsWindow.Close()
         }
      }
      Button "Ok" -Padding "5,0,5,0" -Margin "2,0,0,0" -On_Click {
         Write-Output $textbox[0].Text
         $BootsWindow.Close()
      }
   )
) | Out-BootsImage BootsImage-Screenshot.jpg | ForEach-Object {
   Send-FTP HuddledMasses.org $credential -LocalFile $_ -Remotefile "$imgPath/$($_.Name)"
   [Windows.Clipboard]::SetText( "!http://huddledmasses.org/images/PowerBoots/$($_.Name)!" )
}
 

This is the fourth release of the PowerBoots module for PowerShell 2 (Download7z). PowerBoots is a framework for creating WPF GUIs from PowerShell, and this latest release brings a couple of bug fixes and two new features.

Now with tab completion

The biggest change in PowerBoots 0.0.4 is that tab-completion for parameters works in the shell.

Behind the scenes what has happened is that I’ve discovered that in the current CTP3 release of PowerShell 2, Dynamic Parameter sets are not handled correctly for aliases, and the Get-Command for aliases of functions doesn’t return the same set of parameters as it does on the function itself. The result is that Tab-Completion for dynamic parameters doesn’t work on aliases (neither the built-in tab completion, nor MoW’s PowerTab). I wrote up a bug against that, but I also found that I can work around it by creating hundreds of functions (all pointed at the same script-block), instead of hundreds of aliases (all pointed at the same function).

PowerBoots produces functions instead aliases

This means the PowerBoots commands show up by default when you run Get-Command. Incidentally, this means that the first time you run Get-Command after you Import-Module PowerBoots you incur a huge penalty (17 seconds on my machine) while Get-Command caches all the dynamic parameter information about the functions. NOTE: because of the DynamicParam bug, I’ve ditched aliases altogether for this particular project and am generating two functions for each element/type in PowerBoots: the full New-Namespace.Type version, and a “Type” alias when possible. Trust me when I say: “it’s worth it” ... with the backing scriptblock, there’s virtually no difference between the two approches in terms of resources (other than the aforementions hit on Get-Command).

Now with more controls

The second big change (and the one which I hope will have the biggest long-term impact) is that you can now import your own WPF control libraries into PowerBoots. This means that you can, for example, go get the open source Visifire charting library, extract their WPFVisifire.Charts library into your PowerShell folder, and use it like so:


Add-BootsContentProperty 'DataPoints', 'Series'
Add-BootsFunction -Assembly "~\Documents\WindowsPowershell\Libraries\WPFVisifire.Charts.dll"

Chart -Width 200 -Height 150 -Theme Theme3 (
  DataSeries $(
      DataPoint -YValue (Get-Random 100)
      DataPoint -YValue (Get-Random 100)
      DataPoint -YValue (Get-Random 100)
      DataPoint -YValue (Get-Random 100)
  )
) | Boots -Title "Sample, Theme 3"
 
Read the rest of this entry »
Search My Content