Hashtables are IEnumerable, but they don’t behave that way in PowerShell … this seems to cause all sorts of odd behavior and such, so I thought I’d write up all the examples I can think of in one place. That means this post is going to be a little bit rambling, so please bear with me.
It turns out that in the case of Hashtables, PowerShell does NOT enumerate them into the pipeline. Instead, it passes the entire Hashtable object. Of course, nobody realizes this … because the ouput cmdlets unwrap them (what?!).
The first bug is in Add-Member, which doesn’t work on Hashtables until you’ve already used the Hashtable.
NOT ONLY does Add-Member not work the first time, it’s not just a matter of calling it twice: you just have to try to access something in the hashtable before you can use Add-Member on it:
Here’s another buggy manifestation, in the Formatting cmdlets. This time, the Format-* cmdlets unroll the hashtable … to make it look like it’s being enumerated the way it should be.
Clearly, the Format-* cmdlets have magic code that unwraps hashtables. Which just leads to even more confusion: $table looks the same (in the console output) as $table.GetEnumerator() ... but it doesn’t behave the same way, EXCEPT to the format cmdlets.
In PowerShell 2.0, the PowerShell team is adding another special feature based on hashtables (which appears at first to be based on IEnumerables):
Jeffrey Snover gave an example of splatting in his PDC presentation. Splatting is where a collection is unwrapped so that you can take an array of values and pass one to each parameter of a cmdlet or function. But in Jeffrey Snover’s demo, he splatted a hashtable. Basically, the hashtable keys are matched up to parameter names as though they had been specified by name. That made me wonder why splatting can’t work with custom objects, but after investigating a bit, I’m actually frustrated with the inconsistency of how hashtables are treated in Posh.
The new splatting feature seems to only work with simple arrays and hashtables … adding yet another scenario where the hashtable is being treated specially (even though it doesn’t need to be: if they just splatted IEnumerable, we could work with List
You know what would be cool? If I could splat any object (like a custom PSObject that I have added members to), and have it’s property names matched to parameter names as though all the parameters had ValueFromPipelineByPropertyName set.
You know what would be really cool? If I could specify that I want pipeline objects splatted, forcing ALL parameters to be treated as ValueFromPipelineByPropertyName, without needing to use: ForEach-Object { Test-Splatting @_ } … maybe a syntax like: Get-HashTablesToSplat | Test-Splatting @@ …
8 Nov
The VSTS 2008 TFS Power Tools made their October Release (yes, in November) ... and it’s packed full of yummy goodness.
searchcs for searching checkins/date/user/path/comments, etc.I think you can see that some of this will work with CodePlex, and some wont, but I’m most interested in the shell extension and PowerShell cmdlets! I wonder if they should implement a PSProvider…
This week is Microsoft’s PDC, and I, regrettably, am not there. So I’m following along from a distance, watching the keynotes live from the main site and reading a lot about Microsoft Azure Services Platform and in it’s various incarnations … and trying to follow some of the best coverage:
Oh, and don’t forget, you can watch video of every presentation 24 hours after it finishes on channel9.msdn.com
I wrote yesterday about the WPF Snap-To Behavor that I created, and showed you how simple it is, but I skipped over where the magic happens, so I thought I’d go through how I created the Native Behaviors collection class, because there are a few cool tricks in here that I wanted to share with WPF developers at large (even if you’re not interested in hooking the Window Procedure).
The framework for Native Bahaviors is made up of just two classes, the first of which is basically 3 lines of code.
NativeBehavior is the abstract base class for behaviors, and consists of just definitions for the mandatory abstract GetHandlers() method (where you return an IEnumerable collection of mappings from Window Messages to your delegate methods) and the two optional (virtual) methods AddTo and RemoveFrom which are called when your behavior is initially added to a window (generally before the Window is initialized).
NativeBehaviors is an ObservableCollection of NativeBehaviors, obviously
. But it’s ever so much more than that. First of all, it has the NativeBehaviors attached property, but it also has the code for actually hooking a WPF window to get the Window Messages, and a WndProc which processes each message against the mappings retrieved from the various NativeBehaviors that have been registered.
Lets start with the attached dependency property. There’s a very clever (and problematic) trick in the way this property is exposed. If you look at this code, you’ll see I create a private NativeBehavior dependency property, and then create public Get/Set accessors for “Behavior” which just call the NativeBehavior property. The reason for this is that if the dependency property is public, or if the public accessors even have the same name … the XAML parser finds the dependency property and uses it directly (bypassing the get/set accesors), which means you have to have an extra element in your XAML markup to initialize the NativeBehaviors collection, or you get something like this screenshot.
So instead, we hide the dependency property, and supply a getter which is backed by the dependency property. I should not that although this works great in the .Net Framework, it’s not recognized properly by all of the tools (including Resharper 4.1 and even Expression Blend), so you may have to fiddle with things.
There’s a little more to it in the actual class source code, I’m glossing over the simplest parts, and leaving out all the XML documentation comments too. We override the CollectionChanged event so that we can hook new Behaviors as they arrive, and we make sure to hook the WndProc whenever the Target Window is set:
And finally, the last part of the puzzle is my actual WndProc implementation, which has a minor drawback in that we can hypothetically have multiple behaviors which process the same window message … and may each return a different value (which we cannot reconcile). For now I’m just returning the last (non-zero) result (in actuality, all of the behaviors I’ve written thus far return zero).
That pretty much covers the framework. The actual behaviors can be fairly simple like my Snap-To behavior (which is actually too simple), or extremely complex like my latest behavior, which is a port Joe Castro’s custom Window ‘Chrome’ to my behavior framework, and I’m hoping some of you will choose to write new ones and submit them as patches to the CodePlex project (for now, I’m just piggybacking it on the PoshConsole project). But in any case, the latest code is available via subversion on CodePlex, and you can download today’s snapshot here.
There are many desirable behaviors for Windows applications that are just much harder to do than they should be with the tools that Microsoft has provided in the .Net Framework. In WPF, many of these behaviors are even harder to create than in Windows Forms because the necessary hooks take a bit more work to write (thanks to the fact that there’s no window handles, so dropping down to “Native” code is harder. Luckily, WPF Attached Properties give us a whole new way to reuse these behaviors once they’re written.
I’ve started working on a few classes I’m calling NativeBehaviors, because they rely on intercepting the native Window Message processing, and I’ve put together a simple framework to let me write them, which I thought I would share. The first one I wrote is a SnapToBehavior, which implements a feature that people seem to be constantly re-implementing in apps. Basically, it makes a window snap to the screen edge when it gets close (and prevents them from being moved off-screen). I’ve also written a Global HotkeysBehavior which lets you register Hotkeys that work whenever your app is running (even if another app is active) so you can create a Hotkey to hide your app and show it, or whatever.
In the rest of this article I’ll show you how to achieve this in WPF using my base NativeBehavior class, and how to use it on a Window. Since some of you won’t really care how it works, let’s start with:
Step 1. Add a reference to the Huddled.Wpf.Interop library.
Step 2. Add my Xml namespace to your root Window element
Step 3. Paste three lines from below….
I should point out the “SnapDistance” property of the SnapToBehavior is actually a WPF “Thickness” which lets you specify the distance from the screen edge as a single number to use on all sides, or as a separate number for each side: Left, Top, Right, Bottom. And that’s pretty much all there is to know.
The implementation of the SnapToBehavior is actually ridiculously simple, given the NativeBehavior framework. I simply created a SnapToBehavior class which derives from NativeBehavior, and implemented the single mandatory method:
When my new behavior is added to the Behaviors collection, my handler will be registered, and whenever the WM_WINDOWPOSCHANGING message arrives, it will be called. Now I defined a DependencyProperty for the SnapDistance, so that you could set that in XAML. It’s extremely simple, and VisualStudio has a built-in snippet for dependency properties, but here’s the code:
Once I have that, the last piece of the puzzle is to actually handle the window position changing message (think of it as an event, if you’re not used to Win32 message-based programming).
The basics of handling WM_WINDOWPOSCHANGING is that you get a structure passed in which has the proposed position of the Window, (including it’s z-index related to other apps) and you can basically tweak that however you like. Obviously there are lots of possibilities for this single message: always-on-bottom windows, undraggable windows, etc., but in our case we’re just concerned about how close we are to the edge.
We use the SystemParameters class to get the VirtualScreenLeft, VirtualScreenTop, and VirtualScreenWidth and VirtualScreenHeight which define the rectangle we’ll use for snapping. In the case of non-rectangular arrangements of multiple monitors this isn’t quite sufficient, but for our example anything more would be a distraction. Then we just check to see if the proposed position is within the “SnapDistance” of any of the edges, and if so, we change the position to be against the edge. That’s really all there is to it.
If you look at the code example below you’ll see I have to “Marshal” the WindowPosition structure in and out of an IntPtr which is passed in the WindowMessage … that’s the downside of intercepting window messages that the framework doesn’t already translate for us, but in this particular case, it’s actually fairly trivial.
If you’d like, you can download the current Huddled Interop for WPF library right now, or you can check out the source from CodePlex SVN or just download the most recent commit (You are only interested in the “Huddled” project which is in the “trunk”, not the “trunk-3.5”). The source is licensed freely under the BSD or GPL v2 (and a few other licenses, see the top of the source code files).
Either way you’ll get not just the SnapToBehavior but also the global HotkeysBehavior, and the Native Behaviors framework which I’ll write more about later, but for now, in case you want to try to use it, here’s an example using both the SnapTo and HotkeysBehavior (you can find this in the GlobalHotkeys demo project, which includes some sample code for handling hotkey conflicts). Enjoy.
As you may know, I was one of the first developers who jumped on board and started working on an alternative PowerShell host (actually, I’m also the first to create a WPF-based host, and the first to create one that was open source … but enough about me).
Recently I’ve picked back up on that project, and am just about ready to release what I hope will be the last “pre-release” of PoshConsole before I declare it to be “beta” quality and start doing more regular releases. 
The coolest features of PoshConsole, the ones that are really revolutionary, involve exposing the WPF surface to scripts and cmdlets so that you can actually have graphical output in the console — not popups, and not just for fun… but stuff like putting bar graphs behind the size columns in Get-ChildItem for folders, and the memory columns in Get-Process, etc… anyway.
So I’ve been writing a few scripts to show off the possibilities of PoshConsole, and was thinking about even posting them on the PoshCode.org PowerShell Script Repository, but I wanted a way to make clear that they’d only work in PoshConsole.
A little investigation later, and it was clear that PowerShell has a built in feature for this: #requires -ShellId PoshConsole … except, it doesn’t work. Actually, it doesn’t work for two reasons:
#requires -ShellId AnythingThe ShellId is a read-only property of the RunspaceConfiguration, so to implement it in your PowerShell host you have to create your own RunspaceConfiguration class inheriting from the abstract base class. The problem is, there are some expensive side-effects:
So … to sum up: PowerShell ignores #require -ShellId, and I can’t find another host (including Microsoft’s “Graphical PowerShell” and the latest and greatest PowerShell Plus Professional) that bothers to set the ShellId. Can anyone tell me a reason why I should bother with this?
Oh, and, can anyone give me some information about why Add-PSSnapin might be failing when I do set the ShellId?
ShellId IS too big a burden.After further investigation, it turns out that the reason Add-PSSnapin fails is because it uses a method AddPsSnapIn which is part of the RunspaceConfiguration (that you had to create yourself to set the ShellId), and you can’t implement that method (in fact, you can’t seem to override it with “new” either, I’ll have to look into that a little more).
In any case, the method has to return a PSSnapInInfo object, and since there are no public constructors for PSSnapinInfo objects, you’re sore-out-of-luck. It appears you would literally have to reverse engineer the whole “PSSnapin” system and create your own cmdlets and functionality around it to try to keep your host compatible with the main PowerShell. No wonder nobody’s done this…
I guess I’ll just go back to using Microsoft.PowerShell as my ShellId, I don’t know what I was thinking.
To those of you who are not software developers: feel free to skip this post 
A while ago I wrote a little class for calling console apps from a .Net application, and I’ve been using it in several of my apps (most notably in PoshConsole) and it works great, but since the only place I’ve really published it is in PoshConsole, I thought I’d write it up here, and share it with you …
Basically, it’s a slick invisible event-based wrapper around the Windows native console. What I mean is, it calls AllocConsole when it’s instantiated to create a native console, and hides the console window so it doesn’t show up. This allows you to run any console app you need to from within your app without having it popup a black window
Note this doesn’t let you run graphical consoles like EDIT.COM, but it can handle interactive apps like cmd.exe, batch files, or ftp.exe). All you really have to do is create one of my NativeConsole objects, handle its WriteOutputLine and WriteErrorLine events … and use its WriteInput method to send input or commands to the console app.
You can check out how it works in my WPF-based PoshConsole, and you can get the latest version of it from that project as well (it’s in \trunk\Huddled\Interop\NativeConsole.cs) but for now, here’s the single file source code, with a more liberal set of licenses than I allow for PoshConsole. (more…)
I recently decided to bite the bullet and try using code-generating ORM in my projects instead of manually writing my own data access layer (DAL) with custom SQL and everything … and felt that after careful research into the current state of Linq-to-SQL and ADO Entities, etc. I should use NHibernate …
Everything went ok at first, my first “pretend” project worked, and I feel like my design is definitely more flexible, and using ORM allows me to be more agile with regards to changing customer requirements, because I have less work to do to adjust the data-access layer of my app. However, I’m now trying to apply this to my first real-world problem, one which I consider actually rather trivial, and which I have in fact written a custom DAL for this in the past, but I cannot figure out if it’s even possible to do this in NHibernate.
I’m hoping someone can help me figure out the mappings for this, but failing that, I’d accept suggestions for a alternate design for the database that will make it work for NHibernate. Let me show you my current design and explain it a bit.
First, a basic overview of the application. This is a statistics app, and uses the generic terms of Model, Factor and Level to talk about experiments. For the sake of this example, lets talk about experiments on photocopiers
. A Factor is a variable, in the sense of photocopiers, something like paper size or color. Each Factor has a set of Levels which represent the possible values for it — to use our previous example, sizes like ’8.5 × 11” Letter’ and ‘Tabloid’ or colors like “White” and “Ivory.”
The most important thing to understand is that in our application, all of the Models in a specific instance of the database are presumed to be experiments of the same basic type, so all of the Factors could apply to any experiment model. However, in a given experiment, not all of them will be used, and of those which are used, not all of the possible Levels will be used.
As you can see, the database design is fairly simple, there is one table for each basic type of data, and a fourth table which essentially stores the specific makeup of a given Model. The idea is that when you create an experiment Model, you choose a few Factors and for each of those you choose a few Levels. We simply store which levels you’re interested in for this experiment, since we can trivially determine the Factors based on that. For the sake of completeness, here’s some pesudo-code of the database setup script (leaving out constraints and such, for the sake of clarity).
create table [Factor] (
[Id] int IDENTITY not null,
[Name] varchar(250) not null,
primary key ([Id])
)
create table [Level] (
[Id] int IDENTITY not null,
[Name] varchar(250) not null,
[Factor] int not null,
primary key ([Id])
)
create table [Model] (
[Id] int IDENTITY not null,
[Name] varchar(250) not null,
primary key ([Id])
)
create table [ModelLevels] (
[Model] int not null,
[Level] int not null
)
The C# classes are equally simple, but remarkably different. In an object-oriented design we model collections, rather than belonging. So while the database stores which Factor a Level belongs to, in the application we want to represent which Levels are in a Factor.
The firs major problem is that what I would like is to be able to represent the “Factor” object as a derived type of List<Level>, like this:
This would allow me to iterate the levels as foreach(Level lev in aFactorVariable){...}, and other such niceties of grammar. But NHibernate doesn’t seem to have any idea how to deal with this, so I’ve resigned myself to representing the levels as an IList<Level> member of the Factor class, like this:
This brings us to our second problem. I can’t find any way to explain to NHibernate the relationship between a Model and a Factor. I need my Model to be represented something like this:
However, I can’t find a way to explain to NHibernate how to determine which Factors should load into the Model (based on the ModelContents table which maps Levels). I could create a view or a stored procedure in the database which shows the Model-to-Factors mapping, but I can’t see how to make NHibernate handle the updates by adding the Levels to this ModelContents table. I could hypothetically use SQL Server’s updatable views and INSTEAD OF triggers, but I’m not honestly sure it would work, and I don’t particularly like that it would lock me into SQL Server.
If someone can riddle me that one, I have one other issue: that is, how do I limit the Factor object that is based on a specific Model so that it only has Levels in it which belong to that specific model (that is, that are present in the ModelContents table for this model)? Of course, the idea is for the user interface to present to the user an “Add Level” dialog which shows them all the Levels which exist for that Factor, and allows adding them to the model (as well as adding new Levels), but lets tackle one problem at a time, shall we?
I’m going to post this question (and this url) to the various Alt.Net and NHibernate discussion groups, and I’ll post back here any answers I get which seem to lead in the right direction …
I can post my current NHibernate mappings if anyone wants to see them, but there’s nothing special about them, and they certainly don’t work correctly as I’ve described above.
I have a problem with my laptop where I connect to my home network and my work network, and my school network … and I have to use different proxy settings for Windows internet connection settings (which are used by virtually all .Net apps, including PowerShell) by default…
Of course, there are a lot of different apps that can manage those settings (and more) automatically using Windows NLA to trigger. However, I have an extra special requirement: when I plug in at work or at home, I want to run Synergy on the laptop as a client … but the name and ip of the host is different, of course — so I need to stop synergy and restart it with a different server name … something I can easily accomplish from a script or batch file … but changing proxies is a bit trickier.
I thought it would a simple call to a .Net library method, but after much searching, the only way of setting or retrieving Internet options seems to be through the old WinInet API, using InternetSetOptions (or InternetQueryOption to read them). Of course, to use these, you have to map the INTERNET_PER_CONN_OPTION_LIST and INTERNET_PER_CONN_OPTION structures to C#, and do whole lot of marshalling and manual memory management.
I did find some C# mappings for the Option structure on PInvoke.net but not for the others. I actually started writing them all by hand and then found a “recipe” in the (see the examples link) C# 3.0 Cookbook for retrieving Internet settings which had versions of all the structures I needed, as well as definitions for the flags I wanted. So… without further ado, let me share the code with you … (more…)
23 Apr
Microsoft is announcing a big new software + services product and platform this week (well, today, and tomorrow, apparently). It’s called Live Mesh (how much do you suppose mesh.com set them back?) and it’s primarily a synchronization platform — updates shared files across multiple devices (PC, Laptop, handheld, Mac … yes, they said Mac OS X support is coming). They have some of FolderShare in there, and some of Groove and some of FeedSync … initially, this looks like a folder sync and backup service (see their Mesh help files), but it’s designed to become so much more…
At the core is this concept that a single user has a “mesh” of devices, applications, and data that they regularly use. The Mesh Service persists the relationship between these various resources and authorizes access to them … The Mesh Platform means that ultimately, (down the road) customers will license applications and content to their mesh instead of to a specific computer, device, or application. Microsoft actually envisions apps running seamlessly across multiple devices “from the mesh” ... using Remote Desktop and the mesh software to enable that connectivity regardless of your network topology (meaning it can punch through firewalls because you’re running the client software on all the devices). That platform part could really transform the industry if they actually deliver on this cross-platform support for OS X … are they going to deliver a remote desktop server for OS X?
The most interesting part of this platform concept is that they’re trying to extend their OS and Application -based dominance to the web by making the web a part of this “combined experience and storage platform” and trying to reduce the pressure on consumers to choose between local storage and “storage in the cloud.” Thus, an important part of The Mesh Platform is the fact that each mesh object (be it a document, a picture, a song, or a blog post) can be dealt with in different ways on different platforms — so you might have a folder on your computer containing Word documents … which are transformed into blog posts via the mesh and the concept of synchronized feeds. This could revolutionize web development, if it’s done right. Imagine: a mesh object can be a range of cells in an Excel spreadsheet ... which could be published to the web … and edited … and synchronized … and the whole time you have explicit control over the location and custody of the data, and you have built-in support for groups, group memberships, group permissions and ownership, etc.
To sum up … Live Mesh will not just be another folder sync service ...
Am I interested? Maybe … I need to see some licensing and terms of service information which isn’t really available at the moment (since the whole thing is in a closed beta).
Some screenshots of the client portion of Live Mesh are on CNet, and webware has some analysis of the app portion as well — they seem to say that it will will include full Remote Desktop access to a Windows “Live desktop.”