Scripting Wake On Lan
I mentioned recently about wantint to be able to wake up various machines in my house remotely. My colleague introduced me to
AutoExit for Windows Home Server which works a treat. However, logging onto the Windows Home Server console is a bit, well, slow.
So, now that I do quite a bit of
remote desktop to my development machine I want a quicker, easier way of waking it up.
The solution was a .bat file that uses the very handy WoLCmd command line executable from
www.depicus.com. There's also a GUI, an ASP and a COM version. Very handy.
They even provide the .NET source to Wake-on-Lan yourself
here.
Anyway, I simply botched a bat file together next to my downloaded copy of WolCmd and created a shortcut to the batch file on my desktop. Here's the script:
echo on
wolcmd.exe <MAC-ADDRESS-HERE> <IP-ADDRESS-HERE> 255.255.255.0 7
pause
Easy.

Post By
Josh Twist
2:13 AM
30 Jun 2009
Building an Atom-based media PC for the house
I believe there's a rule that goes along the lines of:
If you have a blog, and you build a PC, you must write a review/walkthrough of the process and post it; with lots of pictures. This is mandatory and failure to comply is punishable by nail-varnishing of the eyeballs.
Now, not wanting to have my eyeballs nail varnished, I thought I better follow suit. Weirdly, this is the first time I've ever built a PC from scratch. I've pulled existing PCs to pieces and failed to put them back together hundreds of times but never started from fresh bits like this. It was exciting.

The requirements/considerations for my new PC are as follows:
- The primary purpose would be as a media PC to go with the TV in our second living room (so I can watch Grand Prix without annoying the wife)
- I'd like it to house the Blu-Ray drive I harvested from my server
- It needs to be small enough to fit on a shelf
- The secondary purpose would be as a head to Remote-Desktop in to my development PC when I fancied doing a bit of dev in another room
- The room can get bloody hot on a hot day, so cooling might be an issue
- It needs to be fairly quiet, though I'm not as fussy about most on this - background noise tends not to bother me too much
- Now that I've gone Power Nuts, I'd like it not to consume too much power either
The natural choice at the moment for any low-power small-form-factor PC is the Intel Atom of netbook/nettop fame. However, traditionally they've been underpowered in the graphics department for use as a media PC. Until the
nVidia ION came along.
I decided to opt for the Zotac IONITX A-B N330 whose highlights include:
- dual-core Atom processor
- nVidia ION graphics
- Includes external 90W power supply
- bundled WiFi (occupying the only PCI-E x1 slot)

You can read a good review of this board
here on
silentpcreview.com.
The dual core version comes with an optional fan where according to the documentation "If your system working at a torrid room,you can append a FAN to the heatsink (sic)". That's one description for the conservatory on a very hot day with the windows closed. And thus, I decided to attach the fan. It's a little noisier than I'd like and there's no way to slow it down. I suspect I may replace this at some point in the near future with a quieter model but for now, it keeps the heatsink incredibly cool (before the fan was attached, the heatsink was too hot to touch).
Anyway, I won't bore you with all the details of the build but here are the mandatory pictures of the build.

The cheesiest RAM in the world (above).



It lives! (above)

The fan, mounted by screwing into the heatsink - quite bizarre as there aren't any 'holes' (above)


The case is an
A+ Cupid-3 which was particularly suitable as it was mini-ITX and offered a full-size 5.25" drive bay to host the huuuge Blu-Ray drive. The case actually came with a 200W PSU but I removed that as the motherboard has its own external PSU and can happily power three SATA devices inside the case (I only needed two) - so if you need a 200W PSU, give me a shout :).
The case is also pretty attractive and was very easy to work with. There's still room for an extra 3.5" HDD too, which is good.
The monitor
The best part of my new computing experience has to be the 26" Samsung Syncmaster LCD TV/Monitor I picked up. 26" isn't that largest TV screen in the world but it's a big monitor. And it's a thing of beauty - I'm already addicted to using it over all my other monitors. The quality of the picture is amazing. The sound is a little weak but I'll be routing that over a hi-fi so no issue there for me.
The finished package


Here's the links to the bits I bought from the stores I used:

Post By
Josh Twist
10:26 AM
28 Jun 2009
Silverlight Validation and ViewModel
Silverlight 3 brings some improvements to Validation for users of the MVVM (Model-View-ViewModel, or just ViewModel) pattern. Specifically, most controls now have a Visual State for a control that has generated binding validation errors.
The default InvalidFocused state looks pretty cool:

And, with Silverlight's
Binding supporting
ValidatesOnExceptions (publishes a validation error if a setter throws an exception) and
NotifyOnValidationError (sends a
BindingValidationError event up tree) it's easy to use this with the ViewModel pattern.
Filling in the details
Most examples out there demonstrate how to use these capabilities so I won't go into the gritty details. However, I want to try and take that knowledge and try to apply it in a slightly more reusable way. There are two key problems I'm trying to solve.
The first problem... dealing with _your_ exceptions
The first is that it becomes difficult for us to tell if our ViewModel is in a valid state or not. Take the following very simple ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
private int _age = 1;
public int Age
{
get { return _age; }
set
{
if (value <= 0)
{
throw new Exception("Age must be greater than 0");
}
_age = value;
OnPropertyChanged("Age");
}
}
public void Save()
{
// TODO
}
// NotifyPropertyChanged implementation snipped for brevity
And the Xaml with the binding:
<TextBox Text="{Binding Path=Age, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
As you can see, this ViewModel has been designed to leverage the ValidatesOnExceptions feature of Silverlight's Binding, raising an Exception if somebody tries to set the Age property to 0 or less (the image above shows how this would look).
The problem comes when we try to 'save' the state of the ViewModel. How can we tell if it's valid or not? Following a Validation Failure we throw an exception and don't set the value of the _age property. Therefore the ViewModel itself is still actually valid.
I can think of a myriad of solutions to this ranging from leveraging some of the features in existing validation frameworks like P&P's Validation Application Block (which is a good idea in any case) to simply allowing the Age property to be set _before_ throwing the Exception. Now the object will be in an 'invalid' state and we can prevent a 'save' taking place.
We're half way there...
The second problem... dealing with binding failures
However, the solution above only works if the TwoWay binding succeeds. What if the user enters 'hello' into the Age field?

That's handy but the update never made it to the ViewModel so, as far as it knows, it's still in a valid state so we can't prevent the save taking place.
A solution?
Since the ViewModel is all about the state of the view, it seems fair that it should be aware of *all* binding and validation failures like this. After all, it might want to host that information so another part of the View can display all the current failures. A validation summary if you will - but in a ViewModel way.
Of course, being a no-code-behind zealot. I'd like to achieve this with as little code-behind as possible in the view. Step forward
Attached Behaviors.
My idea is to have an attached property called ValidationScope.Errors that can be attached to any FrameworkElement. The property would be of type IList
and would handle the BindingValidationError for the element to which it's attached (creating a ValidationScope, effectively).Then all we need to do is bind this attached property to an ObservableCollection on our ViewModel.Here's the Attached Behavior/Property:
public class ValidationScope
{
public static IList<ValidationError> GetErrors(DependencyObject obj)
{
return (IList<ValidationError>)obj.GetValue(ErrorsProperty);
}
public static void SetErrors(DependencyObject obj, IList<ValidationError> value)
{
obj.SetValue(ErrorsProperty, value);
}
// Using a DependencyProperty as the backing store for Errors. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ErrorsProperty =
DependencyProperty.RegisterAttached("Errors", typeof(IList<ValidationError>), typeof(ValidationScope),
new PropertyMetadata(null, ErrorsChanged));
public static void ErrorsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
FrameworkElement element = (FrameworkElement)obj;
element.BindingValidationError += delegate(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
{
GetErrors(obj).Add(e.Error);
}
else
{
GetErrors(obj).Remove(e.Error);
}
};
}
}
And here it is being used by our Xaml:
<Grid x:Name="LayoutRoot" Background="White" local:ValidationScope.Errors="{Binding Errors}">
<StackPanel>
<TextBlock Text="Name:" />
<TextBox Text="{Binding Path=Name, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
<TextBlock Text="Age:" />
<TextBox Text="{Binding Path=Age, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
<Button Content="Save" Click="Button_Click" />
</StackPanel>
</Grid>
Clearly, we need an 'Errors' property on our ViewModel:
private readonly ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>();
public ObservableCollection<ValidationError> Errors
{
get { return _errors; }
}
public bool IsViewStateValid()
{
return Errors.Count == 0;
}
Notice that we can easily add an IsViewStateValid method too that simply sniffs the Errors collection.And our save method?
pbulic void Save()
{
if (!this.IsViewStateValid())
{
_dialogService.DisplayValidationDialog(Errors);
}
else
{
// TODO - SaveData
}
}
In my example, I used one of Silverlight's new Child Windows to display my error dialog - passing the Errors collection so it could be used as a ViewModel for the dialog:

:)
There are other challenges ahead though.. what happens if an object's state can be rendered invalid by a combination of properties? For example, maiden name should be blank if sex == male? In that case it becomes difficult to use the practice of throwing exceptions in setters as you start a chicken/egg race. For these reasons, I'd look at patterns like the Validation Application Block and lean on their concepts when implementing a full LOB validation approach.
Having said all that - before doing any of this you should definitely check out Silverlight 3's DataForm control. You could do much worse than spend 25 minutes watching Mike Taulty's excellent screencast: DataForm control. In particular, pay attention to some of the Validation support including the CustomValidation attribute.
Finally, if you'd like the code from the example I worked up before, you can download it here. Usual disclaimers apply - this is just demoware.

Post By
Josh Twist
1:54 AM
26 Jun 2009
Exciting changes afoot in Ukadc.Diagnostics
OK, so the project went quiet for a while but
Morgan and I have been revisiting
Ukadc.Diagnostics just recently and have some exciting changes on the way.
The first one, first cut of which was checked in today was an enhancement to the existing
Token System of which we were already quite proud. Apart from being a great extensibility point (you can easily create your own PropertyReaders and register them as Tokens) they also make using listeners in System.Diagnostics easier, more fun and reach places other beers can't.
The latest enhancement is the option to add a 'format string' to your token. Take this example configuration for our very own
ConsoleTraceListener:
<add type="Ukadc.Diagnostics.Listeners.ConsoleTraceListener, Ukadc.Diagnostics"
initializeData="{DateTime}: {Id}, {Source}, {Message}" />
Unlike the ConsoleTraceListener that ships with System.Diagnostics, Ukadc.Diagnostics' version gives you control of the output thanks to Tokens. However, at present you're at the will of the system to format that {DateTime} token for you. You could use some of the more specific date-part tokens like so:
<add type="Ukadc.Diagnostics.Listeners.ConsoleTraceListener, Ukadc.Diagnostics"
initializeData="{Year}-{Month}-{Date} {Hour}:{Minute}:{Second}.{Millisecond}: {Id}, {Source}, {Message}" />
A bit messy and you still don't have enough control: 12/24 hour format, 2 or 4 digit year? Not anymore...
The new way
The new format string is applied to a token like so:
{TokenName:FormatString}
So the example above could look like so:
<add type="Ukadc.Diagnostics.Listeners.ConsoleTraceListener, Ukadc.Diagnostics"
initializeData="{DateTime:yyyy-MM-dd HH:mm:ss.fff}: {Id}, {Source}, {Message}" />
Now that's much better! And you can apply a format to any token you like (don't worry, it'll be ignored where it doesn't make any sense).
There's more in the wings too, including:
- Another improvement to the token system - more on this soon
- A new and very, very cool listener
- Some of the listeners we promised a while back
- There's even a contributor we're hoping to get involved
- And, perhaps most importantly, there's a HUGE improvement coming to the documentation.
Stay tuned.

Post By
Josh Twist
11:14 AM
25 Jun 2009
Using Binding to position a Collection of elements - Take 2
Back in October 2007 (wow, that long ago!) I blogged about how to
use binding to position a collection of elements within an ItemsControl.
I talked about how Canvas.Top and Canvas.Left wouldn't work when applied directly to the element because of that isn't the child of the ItemPanel - a contentpresenter gets in the way.
I love it when you work with a technology for a long time, think you know most there is to know and come across something so stupidly obvious you're stunned and delighted. This happened the other day.
I was aware of ItemsControl's ItemContainerStyle property that would be applied to the resulting ContentPresenters, but I'd never considered using Binding in that style. Guess what? It just totally works. Of course it does. D'oh.
Here's a much better solution to the one proposed in that
previous post:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:draw="clr-namespace:System.Drawing;assembly=System.Drawing">
<Page.Resources>
<x:Array x:Key="myArray" Type="{x:Type draw:Point}">
<draw:Point X="10" Y="20"/>
<draw:Point X="20" Y="10"/>
<draw:Point X="30" Y="50"/>
</x:Array>
</Page.Resources>
<ItemsControl ItemsSource="{Binding Source={StaticResource myArray}, Path=.}">
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Y}" />
<Setter Property="Canvas.Left" Value="{Binding X}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Fill="Red" Width="10" Height="10" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Page>
The example above is Kaxaml-ready for your delectation.

Post By
Josh Twist
1:09 AM
25 Jun 2009
Windows Search and the file scheme
Well, I've been up against this for a while now and I'm pretty delighted to have cracked it at last.
In my earlier post
Using Windows Search in your applications I had integrated search in an proof of concept.
The one thing I didn't mention at the time was how this worked fine on Windows 7 (against which I was developing) but did nothing on Windows Vista. Weird.
I spent a lot of time trying to see how Vista's search was interpreting the data store. Was the folder hidden? Did that make any difference? Was the FANCI (Not Content Indexed) bit set properly. And round in circles I went.
Until we did a search in Windows Explorer and saw that it was returning results appropriately and they had indeed been indexed!
So it had to be my query. Spot the difference, the first one doesn't work on Vista
SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE FREETEXT('powershell') AND DIRECTORY = 'C:\Users\me\Documents'
... but this one does...
SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE FREETEXT('powershell') AND DIRECTORY = 'file:C:\Users\me\Documents'
That's right. Vista requires the 'file:' scheme when specifying DIRECTORY. It's my own fault, one of the product engineers warned me that it was a bad idea to not specify the file scheme. Clearly, he was right.
You have been warned.

Post By
Josh Twist
10:50 AM
24 Jun 2009
AutoExit for Windows Home Server
Big thanks to my colleague
Stuart for putting me on this. In my previous post
A developer's roundabout way of fixing some issues with a wireless router I mentioned that my next task was to:
"My next 'job' is to create a UI that gets the last DCHP client list from the router and gives me the option of sending the 'magic packet' to the appropriate IP and MAC address to Wake On Lan (WoL) any machine"
AutoExit for Windows Home Server is an add-in for WHS that allows me to do stuff with the machines on my network: shutdown, reboot, hibernate, log off, lock etc.
To support all the functionality you need to install some stuff on to each machine, which I'm not keen to do. However, Some of the features work with just the add-in installed into WHS... including Wake-on-Lan.

Done. Nice.

Post By
Josh Twist
4:07 AM
24 Jun 2009
Fun with a Power and Energy Monitor
Continuing the to-be-short-lived theme of
my Computing Adventures at Home I recently purchased a
Plug-in Power & Energy Monitor from
maplin.
Since then my wife has looked increasingly concerned at the frequency with which I seem to be turning devices on and off in the house to attach my new toy.
My main motivation for the purchase was to check the power consumption of the server I run at home. This is a machine that I bought about a year ago and thought it would become my new desktop and part time gaming machine. Foolish really, as I never have any time to do any gaming so it quickly retired to take up a role as a
big phat virtual server. It runs a number of Virtual Machines pretty much 24-7 including my Windows Home Server (what an awesome product), my source control and a development web-server.
I was worried that, given the intended purpose of the machine, it was probably chewing through electricity like Augustus Gloop gets through Wonka bars. I was also curious to test the now, commonly held theory that most chargers consume the same power no matter whether the charging device is connected or not.
Chargers
Here’s my new toy with my mobile phone charger plugged-in (sans phone).

The good news, as you can see, is that when the phone isn’t plugged in the charger draws so little power that it doesn’t register at all with the monitor. This compares well to the 4 Watts it draws when the phone is connected and charging.
I found this pattern held true for the vast majority of chargers around the house – including my primary Lenovo laptop charger which drew less than 1W when the laptop wasn’t connected which compares well to the 50W when charging the laptop's battery.
On that note though, the one rogue(ish) device I found was my secondary laptop charger which is a
Kensington Power Adapter (K38047EU) which drew 4W even when the laptop wasn’t connected.
This is a shame as I use the Kensington as my ‘docking station’ (a bunch of wires on my desktop at home, not an actual docking station) and thus this charger is plugged in all the time and doesn’t travel with me. I should probably swap their roles.
My Server
So what about the server I had at home? Well, I was reasonably pleased to find that it was only drawing ~125 Watts (only!). This is still quite high but I genuinely thought the measurement would come in well above 200W so was quite happy about this.
However, the machine is full of bits that it no longer needs. For example, it’s entirely headless now and I always remote into the box over the network so there’s truly no need for the powerful graphics card it has. Or the Blu-ray drive. Or the normal DVD +/-RW drive.
So I set about removing all this unnecessary chuff to see what difference it would make to the power consumption and I’m delighted to report that it dropped down to a much more reasonable ~105W. I’m pretty happy with that for now.

Post By
Josh Twist
5:11 AM
23 Jun 2009
Using Windows Search in your applications
I've been working on a WPF app that does lots of stuff with XPS (you don't say Josh!
Merging XPS Documents,
Cracking an XPS in WPF). One thing I wanted to do was have an integrated search that could whizz through my repository of documents and have the results right there in my application.
Naturally, I was keen to leverage an existing mechanism to do this. My first port of call was to llok at how the Find feature had been implemented in WPF's DocumentViewer control:

Regrettably, the implementation of this search is somewhat, err, encapsulated. You can only get at it using lots of nasty reflection and 'going unsupported'. I really didn't fancy that.
And so my attention was drawn to
Windows Search.
Built on the original
Windows Desktop Search that you added to Windows XP,
Windows Search is part of Vista (and Windows 7 builds on this even more) - fortunately, it has an API that we can all use.
The way in which we query the index should be familiar to most .NET Developers, we just use System.Data's OleDb Providers. Here's some sample code that executes a query and populates a Windows Forms datagrid with the results:
using (OleDbConnection conn = new OleDbConnection(
"Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(txtSearch.Text, conn);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
gridResults.Rows.Clear();
gridResults.Columns.Clear();
for (int i = 0; i < reader.FieldCount; i++)
{
gridResults.Columns.Add(reader.GetName(i), reader.GetName(i));
}
while (reader.Read())
{
List<object> row = new List<object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row.Add(reader[i]);
}
gridResults.Rows.Add(row.ToArray());
}
}
}
And here's a snap of the results:

The query (txtSearch.Text) I'm using to get these results? Well, for those of you that can't read the tiny image...
SELECT TOP 5 System.ItemPathDisplay, System.ItemUrl FROM SYSTEMINDEX WHERE System.ItemType = '.config'
Oh yeah baby - it's just
like SQL! In this case I want to select the display path and the full url for the top 5 files in the system index where the extension is .config.
Projection
There is a mindblowing number of columns available when querying Windows Search - most of them are only applicable to certain file types, for example: System.Photo.Aperture, System.Photo.ApertureDenominator, System.Photo.ApertureNumerator, System.Audio.SampleRate.
You can get the full, daunting, list on MSDN:
System Shell Properties,
All Shell Properties (use the tree on the left to navigate to the categories).
Still, you can put together some amazing queries depending on your application (photo app anyone?).
Predicates
You can do most of the things you'd expect with the WHERE clause: e.g.
-- items not modified since
WHERE System.DateModified <= '2007-07-07'
-- find all images big enough to be wallpaper (on a small screen :)
WHERE System.Image.VerticalSize >= 768 AND System.Image.HorizontalSize >= 1024
-- items with a due date (includes mails and tasks remember!)
WHERE System.DueDate IS NOT NULL
Very cool - but I needed to search documents and dive into the guts of the text. There are two key ways of doing this:
CONTAINS and
FREETEXT.
Initially, I opted for CONTAINS and started building queries like the example below, passing the value from a textbox the user plonks his search into:
SELECT System.ItemUrl FROM SYSTEMINDEX WHERE CONTAINS('{query}')
This was fine when the query was "powershell" or "windows" but any non-word character blew it up (including spaces). So "where are you?", "windows vista" and "windows!" were all invalid.
Blindly, I decided to chop these queries up using regular expressions and rebuild them so that they'd become...
WHERE CONTAINS('"where" AND "are" AND "you"')
WHERE CONTAINS('"windows" AND "vista"')
WHERE CONTAINS('"windows"')
...respectively. This worked but it felt wrong. The FREETEXT alternative is really what I was looking for and does exactly what I needed without the need to hack the query to pieces:
WHERE FREETEXT('where are you?')
WHERE FREETEXT('windows vista')
WHERE FREETEXT('windows!')
Much easier.
Scope
Truly awesome so far - but I wanted to limit my search to a specific directory with documents that pertain only to this application. No problem!
There are two approaches here:
DIRECTORY - when you want to limit the search to single directory.
SCOPE - when you want to limit your search to specific folder and its sub-folders.
WHERE FREETEXT('your query') AND DIRECTORY = 'c:\users\josh\justhere'
-- or
WHERE FREETEXT('your query') AND SCOPE = 'c:\users\josh\godeep'
UPDATE - read this post '
Windows Search and the file scheme' before copying this code!
And more
There's lots more available in Windows Search SQL - you can
ORDER BY and even weight individual columns differently with the
RANK BY statement.
Modifying the index
The final obstacle for your application of Windows Search might be getting the files you want
into the index. Sadly, there's no support for INSERT, UPDATE or DELETE in Windows Search SQL but there is a different API to allow you to play with the indexes.
As a managed developer, I opted to use the Microsoft.Search.Interop.dll that some helpful folks created as part of the
Microsoft Windows Search 3.x SDK.
It's pretty easy to use but the documentation is a little sparse.
Here's some code I used to add a folder path as a user scoped rule (there are default scope rules that include or exclude folders, and user scoped rules that override these where necessary).
CSearchManager manager = new CSearchManager();
// the SystemIndex catalog is the default catalog that windows uses
CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
CSearchCrawlScopeManager csm = catalogManager.GetCrawlScopeManager();
// Check to see if our path is already a crawl scope
if (!Convert.ToBoolean(csm.IncludedInCrawlScope(ScanPath)))
{
// if not, add it at the user level
csm.AddUserScopeRule(ScanPath, Convert.ToInt32(true), Convert.ToInt32(true), 0);
csm.SaveAll();
}
As you can see, most of the work takes place against the
ISearchCrawlScopeManager interface - and as it notes in the documentation
Using the Crawl Scope Manager, you'll need the right permissions to modify the index.
A word of caution
I did have some problems with managing query scopes. Specifically, because these files were generated by my application I wanted to keep them tucked away. They're not sensitive or corruptible in any real way, but I didn't want them getting in the users way. Good places for such files are Common Application Data folders (ProgramData) or User Application Data folders (AppData\Local and AppData\Roaming etc).
As you'll see in
What is Included in the Index - these folders are specifically excluded. I thought I'd give it a shot at overriding this with a User Scoped Rule for my particular sub-folder. And, although the index made all the right noises (including the UI in Windows 7, below) the contents of these folders simply never showed up in my results.

The next thing is to check was the NotContentIndexed attribute of the files - this means the metadata might be indexed, but not the content of your files:
b

It turns out this is a bugette due to the fact that the exclusion of the ProgramData folder contains a trailing asterisk (c:\ProgramData\*). The solution for me was to put the contents elsewhere, but I believe removing the naughty rule and re-applying it without the trailing asterisk would work equally well.

Post By
Josh Twist
12:55 PM
22 Jun 2009
A developer's roundabout way of fixing some issues with a wireless router
My wireless router doesn't get on well with my wife's Samsung NC10 netbook. I've tried updating the netbook's wireless driver, the router's firmware (no new version available) and changing the channel but still no success. It's odd, because the router works fine with my other wireless devices but the only way to solve the problem is to restart the router, not the netbook.
At present, this is a real pain as the router is hidden away in a cupboard in the back bedroom. So I came up with something of a roundabout solution, if it's fair to call it a solution at all.
The idea was to use one of my servers to host a public endpoint in IIS that would talk to the router over a wired link and ask it to reset. I suspected I'd be in for a fair bit of screenscraping to interact with the router's web-based UI but it turned out to be scarily simple.
I used
fiddler to trace the HTTP interaction a user's browser has when resetting the router so I could recreate this using the System.Net.WebClient in ASP.NET. The right choice for an ASP.NET 'page' that doesn't need any controls is a handler. And this is all I needed to get it working.
public class MyResetRouterHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
WebClient client = new WebClient();
client.OpenRead("http://191.168.1.1/processlogin.cgi?loginPassword=not-telling-you");
using (Stream s = client.OpenRead("http://191.168.1.1/rebootinfo.cgi"))
using (StreamReader sr = new StreamReader(s))
{
context.Response.Write(sr.ReadToEnd());
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
The idea being that my wife can then request the page https://my.public.server.url/ResetRouterApplication/MyResetRouterHandler.ashx from her
phone and the router will reset. She'll then be fine to surf on the netbook within about 30 seconds.
Of course, you need to be very cogniscent of security when doing this as you're effectively creating a route through you NAT and firewall to your routers UI - I even opted to go for SSL.
However, this does open up some coding-for-fun at home opportunities. My next 'job' is to create a UI that gets the last DCHP client list from the router and gives me the option of sending the 'magic packet' to the appropriate IP and MAC address to
Wake On Lan (WoL) any machine. This is particularly useful if I want to remote into a machine and it's off or sleeping.

Post By
Josh Twist
5:29 AM
20 Jun 2009
Merging XPS Documents
This had me stumped for a while now. You may remember me playing with XPS documents and displaying them using WPF from this post:
Cracking an XPS in WPF.
Since then I've been struggling some more with the XPS API; this time trying to merge two documents to create a single XPS. It turns out there are a number of ways to think about this as XPS documents can actually contain
multiple documents (or DocumentReferences as they appear in the API). I decided to merge all pages from both XPS files into a single FixedDocument (and thus single DocumentReference).
Here's the code I used to do this - first we need to extract all the pages from the existing documents. We go for the PageContent type:
public static List<PageContent> GetAllPages(FixedDocumentSequence documentSequence)
{
var docs = documentSequence.References.Select(r => r.GetDocument(true));
List<PageContent> pages = new List<PageContent>();
foreach (var doc in docs)
{
pages.AddRange(doc.Pages);
}
return pages;
}
You've probably noticed that this takes a FixedDocumentSequence. Getting one of those from an XPS is the easy bit:
XpsDocument doc = new XpsDocument(sourcePath, FileAccess.Read);
FixedDocumentSequence seq = doc.GetFixedDocumentSequence();
Now to take those pages and put them into a new FixedDocumentSequence:
public static FixedDocumentSequence CreateNewDocumentFromPages(IEnumerable<PageContent> pages)
{
FixedDocumentSequence newSequence = new FixedDocumentSequence();
DocumentReference newDocReference = new DocumentReference();
FixedDocument newDoc = new FixedDocument();
newDocReference.SetDocument(newDoc);
foreach (PageContent page in pages)
{
PageContent newPage = new PageContent();
newPage.Source = page.Source;
(newPage as IUriContext).BaseUri = ((IUriContext)page).BaseUri;
newPage.GetPageRoot(true);
newDoc.Pages.Add(newPage);
}
// The order in which you do this is REALLY important
newSequence.References.Add(newDocReference);
return newSequence;
}
This returns a new FixedDocumentSequence that can be written to disk as easily as this:
using (XpsDocument xpsDocument = new XpsDocument(targetPath, System.IO.FileAccess.ReadWrite))
{
XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
xpsDocumentWriter.Write(fixedDocumentSequence);
}
All sounds easy right? No - this has had me stumped for weeks on and off. A very helpful chap in Redmond put me on to this
XPS document merge sample on MSDN. However, it didn't make for the easiest of reading (a lot of the code was WPF drag n' drop stuff and whole bunch of new XPS 'model'). However, I managed to distill out the bits I needed but my code was plagued with issues. The resulting document was invalid and the performance of the
newDoc.Pages.Add(newPage) line grew exponentially worse with each addition. Weirdly, the resulting FixedDocumentSequence could be viewed using WPF's DocumentViewer (and the FixedDocumentSequence.DocumentPaginator.Source property) just fine.
All very odd and all because I was adding my DocumentReference to the FixedDocumentSequence too soon. You'll notice in the sample above this is almost the last thing to happen - and with this all my troubles went away.

Post By
Josh Twist
2:00 AM
16 Jun 2009
Help! Why can't I use DataTriggers with controls in WPF?
or "Why can't I use TargetName with Style's Triggers"?
This is a common problem. The first is the desire to use DataTriggers directly with an element. Something like this slightly contrived example:
<CheckBox Name="chk" Margin="5" Content="Check me" IsChecked="True"/>
<Border Margin="5" Background="Navy" CornerRadius="5" Padding="5">
<TextBlock Foreground="White">I should disappear when you uncheck the textbox</TextBlock>
<Border.Triggers>
<DataTrigger Binding="{Binding ElementName=chk, Path=IsChecked}" Value="False">
<Setter Property="Border.Visibility" Value="Hidden"/>
<Setter Property="Border.Visibility" Value="Hidden"/>
</DataTrigger>
</Border.Triggers>
</Border>
Here, we have a checkbox next to a border containing some text. We also have a DataTrigger registered to change the visibility of the border when the checkbox is unchecked.
The first problem with this is that it's totally invalid. Elements (like Border) can only contain EventTriggers (which actually, would be quite suitable for this example but bare with me).
Only Styles, DataTemplates and ControlTemplates support the awesome DataTrigger, so it's time for a bit of a cheat.
Using a style
<CheckBox Name="chk" Margin="5" Content="Check me" IsChecked="True"/>
<Border Margin="5" Background="Navy" CornerRadius="5" Padding="5">
<TextBlock Foreground="White">I should disappear when you uncheck the textbox</TextBlock>
<Border.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=chk, Path=IsChecked}" Value="False">
<Setter Property="Border.Visibility" Value="Hidden"/>
<Setter Property="Border.Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
It's perhaps a bit verbose but it compiles (and works!). Happy days.
However, what if we want to modify a property of the TextBlock in our trigger, not just the border? Problem #2 - I can only change the properties of the element to which the style can apply.
Using a DataTemplate
Time to escalate our cheating slightly, time for a DataTemplate. The great thing about DataTemplates is they allow DataTriggers and support the TargetName property on their Setters.
To implement this, we just use what I call the ContentPresenter/DataTemplate combo, with this lot in resources:
<DataTemplate x:Key="myDataTemplate">
<Border Name="border" Margin="5" Background="Navy" CornerRadius="5" Padding="5">
<TextBlock Name="text" Foreground="White">I should fade and go red when you uncheck the textbox</TextBlock>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding ElementName=chk2, Path=IsChecked}" Value="False">
<Setter TargetName="border" Property="Border.Opacity" Value=".5"/>
<Setter TargetName="text" Property="TextBlock.Foreground" Value="Red"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
and a ContentPresenter wherever you want to use the template:
<CheckBox Name="chk2" Margin="5" Content="Check me" IsChecked="True"/>
<ContentPresenter ContentTemplate="{StaticResource myDataTemplate}"/>
Another great thing is this template is now reusable elsewhere within the scope of the resources - just specify another ContentPresenter.
I use this approach all the time as it helps to create a more readable structure within my Xaml files - in addition to giving me support for DataTriggers and TargetName.

Post By
Josh Twist
11:43 PM
15 Jun 2009
GetHashCode and LINQ to objects
I was coding some LINQ to objects the other day and fell foul of a common mistake. Let me walk you through the example. Here's an object Foo - notice how it is IComparable
and also overrides the Equals method:
public class Foo : IComparable<Foo>
{
public int Value { get; set; }
public override bool Equals(object obj)
{
Foo other = obj as Foo;
if (other == null)
{
return false;
}
return other.Value.Equals(Value);
}
public int CompareTo(Foo other)
{
if (other == null)
{
return +1;
}
else
{
var comparison = Value.CompareTo(other.Value);
return comparison;
}
}
public override string ToString()
{
return string.Format("{0}", Value);
}
}
It has one property called Value which is of type Int32 and when you ToString() the object you simply get this integer value.Now, the LINQ query I want to write sorts Foos and groups them. Here's an example done for a list of integers: List bars = new List { 2, 1, 1, 2 };
List<int> bars = new List<int> { 2, 1, 1, 2 };
var groupedBars = from b in bars
orderby b ascending
group b by b into g
select g.First();
// This writes each value to the console
Dump(groupedBars);
And here's the output:
1
2
Perfect, exactly what we'd expect. Let's now do the same for a very similar list of Foos:
List<Foo> foos = new List<Foo>
{
new Foo { Value = 2 },
new Foo { Value = 1 },
new Foo { Value = 1 },
new Foo { Value = 2 }
};
var selection = from f in foos
orderby f ascending
group f by f into g
select g.First();
Dump(selection);
And here's the output:
1
1
2
2
Mmm. The sorting worked OK but the grouping not so much. My Equals operator clearly states that two Foos are equal if they have the same value - but they're not being grouped in this way (though they are being sorted correctly).It's all my fault for ignoring this warning in Visual Studio:"'Foo' overrides Object.Equals(object o) but does not override Object.GetHashCode()"It's easily fixed with this very simplistic implementation of GetHashCode being added to the object:
public override int GetHashCode()
{
return Value.GetHashCode();
}
Implementing GetHashCode()
I was worried about this implementation so headed over to MSDN to check the docs and see how I _should_ implement GetHashCode(). I found this page Object.GetHashCode Method which contained the three rules of GetHashCode():
- If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
- For the best performance, a hash function must generate a random distribution for all input.
- The hash function must return exactly the same value regardless of any changes that are made to the object.
Instantly I was stuck by a dichotomy here. 'If two objects represent the same value (i.e. are Equal()) the hash function must return the same value' and 'the hash function must return exactly the same value regardless of any changes that are made to the object.' - eh?How can you possible satisfy both of these requirements for mutable objects? In my case, Foo's Value can change and the Equals override must account for this - however, the Equals and GetHashCode need to be aligned but that would break the last rule.I'm not the first person (by a long way) to spot this. Ian Griffiths discusses the issues in more detail in this post The Rules for GetHashCode.My decision is to ignore the last rule (which is primarily to support HashTables) and go with a changing GetHashCode - this best allows me to use group by in my LINQ queries how I wish to. I have to admit though that I'm sort of surprised that group by *doesn't* use the Equals method for grouping - surely this has more in common with ANSI SQL (and thus, most query languages)?Anyway, with the addition of my GetHashCode, the output now looks like this:
1
2
Happy days.As my buddy Zulfiqar says, another good reason to enable 'Treat warning as error' in Visual Studio.

Post By
Josh Twist
2:29 AM
29 May 2009
If you can't beat XAML, improve it
On my travels I get to speak to lots of developers who use (or want to use) WPF but feel slightly frustrated for one reason or another. Typically, it isn't obvious why they're frustrated at first but the conversation nearly always leads to them expressing their frustration with the tools. Typically, their feelings are:
- Blend is too hard for developers
- Cider (VS' WPF designer) is no good for building LoB apps
I guess Blend isn't really for developers, it's for designers. I began my career in IT as a web designer and so I'm pretty familiar with designer tools like Photoshop and Illustrator. I'm also pretty comfortable in Blend but I have to come clean and say I flat out find it doesn't get much use when it comes to much of my WPF development.
I wish I could say I use Cider instead, but I don't. As long term readers will remember
I actually disable Cider and go for full screen XAML editing. There have been improvements made to Cider that will come in VS2010 but mostly they just bring the capabilities in line with Blend (improved Binding support, searching for properties etc).
So where does this leave us? For me, it leaves me in a very happy world of coding XAML angle brackets and using Blend for animations and re-templating controls.
Text isn't so bad
I heard Don Box talk about Oslo and modelling recently and something he said turned on a whole row of lights in my head: "Developers don't like visual tools, they like text". He was referring of course to early concepts for Oslo which only included visual design tools to create models and the poor reception they got. They eventually realised that developers liked to create their models in text - and I'm no different.
We have the same with UI - designers are just modelling tools to help us create the UI in a visual way. It just so happens, in this case, that the model is _very_ close to the end result, but the principle is just the same. If we look at ASP.NET - we have a very good design surface available and whenever I have a discussion about WPF and tooling I always ask this question:
"Do you use the designer for ASP.NET development or do you code against the source with angle brackets".
In the two or so years I've asked that question
nobody has replied 'designer'; they always reply 'angle brackets'.
So what was different about Windows Forms? Everybody used the designer in this case - but you had no choice. The 'serialization format' of the Windows Forms designer was C# which, as excellent as it is, offers a horrible experience for describing object graphs when compared to XAML or HTML (and ASPX).
In short then, I'm very happy developing in XAML.
Having said that, there are problems, two of which I think are key:
- Barrier to entry - having to code in XAML creates a large barrier preventing many from entering the WPF world - this simply wasn't the case for Windows Forms. For this reason, I think the existence of Cider and it's continued development is very important. I also think Cider needs a total rethink when it comes to layout but that's a topic for another day.
- XAML's ease of authoring (or lack thereof) - XAML wasn't created with hand-crafting in mind and it's obvious, the verbosity on occasions becomes numbing. Specifically, XAML was designed with the idea in mind that it *shouldn't* be written by hand. This simply isn't the reality we find ourselves in.
XAML authoring continued
Charles Petzold discussed this in an article for MSDN Magazine:
Let my people code:
"But in some people's minds, writing XAML is an aberration. XAML is not supposed to be hand-written. As one Microsoft blogger put it, "XAML is for Tools," and over the months prior to its release, some XAML features have been removed because they were strictly for the benefits of humans rather than tools.
If this is true, I think it's time we realised that this currently doesn't stand. More people are hand crafting XAML than are using tools so in my opinion we should have a parallel focus on making XAML more authorable. Imagine going from this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="433" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
</Grid>
to this
<Grid
ColumnDefinitions="*,*,Auto,433"
RowDefinitions="*,Auto" />
Or from this
<Border>
<Border.RenderTransform>
<ScaleTransform ScaleX="2" ScaleY="2" />
</Border.RenderTransform>
</Border>
to this (which would be easily achievable with a custom MarkupExtension)
<Border RenderTransform="{ScaleTransform 2}" />
Of course, it's arguable that XAML, the markup language itself, isn't to blame for this verbosity - it's the object model within WPF. However, there's a blurry line between the two in most people's minds. Also, I suspect some changes to XAML might be necessary to really make a radical difference to XAML authoring.

Post By
Josh Twist
6:21 AM
28 May 2009
ViewModels and CheckListBoxes
During a recent WPF presentation I did for the folk at the .NET Developer Network (
dotnetdevnet.com - neat domain) in Bristol, one of the attendees posed me a question about how you might implement a ViewModel to deal with a CheckListBox in WPF.
The first thing to note is kind of important: there is no CheckListBox in WPF. Uh oh. Well, not really. It's mostly just a case of composition thanks to WPF's lookless controls.
For a quick win, we can just 're-template' a ListBox to provide CheckBoxes in the individual ItemTemplate(s). We'll look at exactly how we do this a little later.
The obvious feature missing from this implementation is the checking/selection algorithm implemented in Windows Forms CheckListBox but that shouldn't be too hard to put together. I'll leave it as an exercise for the reader for now to keep this article concise.
Now we know how to create a simple CheckListBox in WPF, how do we create a suitable ViewModel for it to bind to. Key to this is the idea of composing multiple ViewModels to create the full ViewModel picture.
In this post we'll look at creating a simple solution to this. There are many possible ways to skin this particular cat and this is just one. YMMV etc.
I like and agree with
David Hill's perspective on ICollectionView in WPF:
"... CollectionViews were actually good examples of the ViewModel pattern applied to collection-based models. In this post I explain in more detail why I think of CollectionViews as ViewModels." (from his post
CollectionViewModel).
We'll take this idea and run with it by creating a special collection based view to deal with the 'checkability' required by our CheckListBox. Obviously, we want to bind our CheckListBox to some kind of IEnumerable, preferably an ObservableCollection to better support updates for bindings. And so my thread of thought began. Step 1: Inherit from an ObservableCollection and wrap the item type in a CheckableWrapper<T>:
public class CheckWrapper<T> : INotifyPropertyChanged
{
private readonly CheckableObservableCollection<T> _parent;
public CheckWrapper(CheckableObservableCollection<T> parent)
{
_parent = parent;
}
private T _value;
public T Value
{
get { return _value; }
set
{
_value = value;
OnPropertyChanged("Value");
}
}
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
CheckChanged();
OnPropertyChanged("IsChecked");
}
}
private void CheckChanged()
{
_parent.Refresh();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler pceh = PropertyChanged;
if (pceh != null)
{
pceh(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Which as you can see, is 'owned' by a new CheckableObservableCollection<T> type:
public class CheckableObservableCollection<T> : ObservableCollection<CheckWrapper<T>>
{
private ListCollectionView _selected;
public CheckableObservableCollection()
{
_selected = new ListCollectionView(this);
_selected.Filter = delegate(object checkObject) {
return ((CheckWrapper<T>)checkObject).IsChecked;
};
}
public void Add(T item)
{
this.Add(new CheckWrapper<T>(this) { Value = item });
}
public ICollectionView SelectedItems
{
get { return _selected; }
}
public void Refresh()
{
_selected.Refresh();
}
}
I've done the bare minimum to get this scenario to work here, you can imagine a bunch of other methods and properties that would be useful to these classes. (Note, the call to Refresh on the ListCollectionView everytime an item is checked is a bit wasteful WRT performance - but it would be easy to fix with a bit more time and quite a bit more code).
The scenario I want to implement in this case is pretty simple. Populate a CheckListBox using binding and have the check status represented in the ViewModel so that I can code against it to write back to the database.
Also, I'd like to be able to show the Checked Items in a seperate ItemsControl just using some databinding.
We now need to hydrate our ViewModel with some data. For now I'll hardcode this in the form of some strings but in a later post I'll look at how I might get this from a database and save any changes back to a database.
Here's the very simple parent ViewModel and you can see the data population taking place in the constructor:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
Items = new CheckableObservableCollection<string> { "hello", "goodbye", "this is cool", "here's another option" };
}
private CheckableObservableCollection<string> _items;
public CheckableObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged("Items");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler pceh = PropertyChanged;
if (pceh != null)
{
pceh(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Cool. So now all we need is some Xaml to bind to this stuff. First, here's our 'CheckListBox' made especially for binding to CheckableObservableCollection
in this case:
<!-- TODO: Implement Checking/Selection algo -->
<ListBox ItemsSource="{Binding Items}" Margin="4" SelectionMode="Extended">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="check" IsChecked="{Binding IsChecked, Mode=TwoWay}" Margin="3" VerticalAlignment="Center" />
<ContentPresenter Content="{Binding Value}" Margin="1"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And finally, we need to bind our 'Selected Items' part of the view to the CheckedItems (ICollectionView) on our CheckableObservableCollection.
<ItemsControl Margin="4" x:Name="items" ItemsSource="{Binding Path=Items.CheckedItems}" DisplayMemberPath="Value" />
And here's the result - the list on the right is kept up to date based on selections on the left. I must stress again that this is my first implementation based on my first train of thought for tackling this (with a mindset of writing as little code as possible, but making as much of what I do write - 'reusable and generic').

Source code
Usual disclaimers apply, your own mileage may vary, you may lose your house if you stop paying for it. Get the code here -> Download Source Code (10KB).

Post By
Josh Twist
12:58 PM
26 May 2009
© 2005 - 2009 Josh Twist & Thomas Bruusgaard - All Rights Reserved.