You're reading Mabsterama, the weblog of Matt Hamilton. Enjoy your stay.
AWDNUG August 2010
After a month off in July, the Albury/Wodonga .NET User Group met again last night. Numbers, as usual, were down, but it was an enjoyable meeting.
Nathan demonstrated SpecFlow, a behaviour-driven development framework for .NET, in which you write your “specifications” as “features” and “scenarios” in a plain text, human-readable format, and match them to actual code in the form of “steps”. I was sceptical at first, but having seen Nathan’s demo and watched Rob Conery’s Tekpub video, I’m starting to think that this might be a valuable tool – especially if you’re designing an application from scratch.
Unfortunately I’ll be away for the next two meetings, since Sal and I will be travelling around Europe and the UK. It’s a dirty job, but someone’s gotta do it! I’m sure the guys have some interesting presentations and discussions lined up, so do considering coming along to the meetings. You never know: you might even learn something! ![]()
Halfwit Hits Version 1!
Last night I released version 1.0.0.0 of Halfwit, my streamlined Twitter client.
As of version 1, Halfwit requires the .NET 4 Client Profile, but if you don’t have it it will be downloaded and installed at the same time.
The only new feature in v1 is URL shortening, and at this point it’s still something of a work in progress. The idea is that you type (or paste) in the URLs you want to tweet about, and then you have the option to shorten them. Here’s a screenshot (click to embiggen):
The idea is that you can choose to shorten a single URL in your Tweet, or shorten them all. I’ve forgotten to include the keyboard tip next to the “Shorten All” menu item in this release. For reference, it’s Ctrl+Shift+U. Hit that just before you hit Enter and all the URLs in your tweet will be shortened for you.
Right now, URL shortening is limited to the http://is.gd service. I have plans to add others (and, obviously, a way for you to choose which one you prefer) in a future version.
To try out version 1 of Halfwit, you should first uninstall the current version. Because this one requires a new version of the .NET framework, I decided not to automatically update users of version 0.x. Once you’ve uninstalled, you can click here to take you to the Halfwit v1 install page. I will update the Halfwit home page later to point there too.
Hope you enjoy using Halfwit! Remember, all feedback is appreciated, be it on Twitter, UserVoice or Codeplex!
Give WPF’s DatePicker some Keyboard Love
I’ve just started using the DatePicker control from the WPF Toolkit for .NET 3.5 SP1. DatePicker is built into .NET 4, but for reasons I’ve already explained, we’re stuck on 3.5 for the time being.
Anyway, the DatePicker is a simple enough control. It has a TextBox where you can type in a date, and a button that pops open a calendar if you prefer to use the mouse.
For us keyboard junkies, though, it’s lacking a few little niceties. For example, I want to be able to use the up- and down-arrow keys to increment and decrement the date. I’d also like to be able to jump straight to today’s date using Ctrl+D – a habit I picked up from using Microsoft Money for many years.
So here’s some code that will introduce those keyboard shortcuts into all the DatePickers in your application. Basically I’m using the EventManager class to set up a “global event handler” for the PreviewKeyDown event on the DatePicker.
First, override the OnStartup method in your App class (in App.xaml.cs):
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); EventManager.RegisterClassHandler(typeof(DatePicker), DatePicker.PreviewKeyDownEvent, new KeyEventHandler(DatePicker_PreviewKeyDown));
Next, define your “DatePicker_PreviewKeyDown” method in the same class:
private void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) { var dp = sender as DatePicker; if (dp == null) return; if (e.Key == Key.D && Keyboard.Modifiers == ModifierKeys.Control) { e.Handled = true; dp.SetValue(DatePicker.SelectedDateProperty, DateTime.Today); return; } if (!dp.SelectedDate.HasValue) return; var date = dp.SelectedDate.Value; if (e.Key == Key.Up) { e.Handled = true; dp.SetValue(DatePicker.SelectedDateProperty, date.AddDays(1)); } else if (e.Key == Key.Down) { e.Handled = true; dp.SetValue(DatePicker.SelectedDateProperty, date.AddDays(-1)); } }
Note that I’m using “dp.SetValue” in this code rather than just assigning a value directly to dp.SelectedDate. The reason I’m doing it this way is that the SelectedDate value might be data-bound. If it is, assigning a value to it directly will “cancel out” the binding.
The “global event handler” trick with EventManager is a very powerful and flexible way to add application-wide behaviour to any control. Give it a try!
Creating a WPF Style in Code
The other day I was designing a page in WPF, and wanted to show or hide a TextBlock depending on whether one date was after another.
Both dates were stored in properties on the DataContext of the page, so theoretically I could have gotten to either of them via a binding. I have an “AtLeastConverter” class which will return true if the supplied value is equal to or greater than the converter parameter, so I decided to use that.
So I wanted to do this:
<TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Value="True"> <DataTrigger.Binding> <Binding Path="Date"
Converter="{StaticResource AtLeast}"
ConverterParameter="{Binding Pig.WithholdDate}" /> </DataTrigger.Binding> <DataTrigger.Setters> <Setter Property="Visibility" Value="Hidden" /> </DataTrigger.Setters> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style>
The problem, of course, is that you can’t bind the ConverterParameter property – it has to be a fixed value. I could have created an IMultiValueConverter and passed both values in, but I figured if I was going to write code, I might as well take the YAGNI approach and write it just for this one page.
So here’s the equivalent code in the constructor of my page. It creates the same style in C#, and assigns the correct value to the ConverterParameter of the Binding without having to bind it (since I know it won’t change during the lifetime of the page):
WithholdWarning.Style = new Style { TargetType = typeof(TextBlock), Triggers = { new DataTrigger { Value = true, Binding = new Binding("Date") { Converter = new AtLeastConverter(), ConverterParameter = _removal.Pig.WithholdDate }, Setters = { new Setter { Property = TextBlock.VisibilityProperty, Value = Visibility.Hidden } } } } };This is making use of C# 3’s wonderful object and collection initializer syntax, which really tidies up what could otherwise be very messy code. In the end, the C# doesn’t look dissimilar to the XAML – it just has more curly braces and no angle brackets. It’s nice to know that there’s always an alternative.
AWDNUG June 2010
Last night at the June meeting of the Albury/Wondonga .NET User Group we covered OData.
I spent a few minutes going back over some ground we’d covered last month on Entity Framework, then walked through the steps covered by Scott Hanselman in this great blog post where he creates an OData service from an EF model. The only snag I hit (and it was a pretty major one) is that I didn’t have SQL Server Express installed on my laptop so I was just using SQL Server Compact Edition, which decided it would throw a NotSupportedException when I tried to use it in a web application.
Undeterred, I instead connected to the net and started browsing around the Netflix OData feed, demonstrating how to build queries by altering the URI. I then downloaded LinqPad and wrote some ad-hoc LINQ queries against Netflix data, and finally created a console application in Visual Studio to perform queries of our own.
Despite dwindling numbers, it was a fun evening. We even had a brief look at the Halfwit code. :)
See you next month!
DDD Melbourne 2010
On Saturday, Andrew and I attended the inaugural DDD Melbourne (that’s "Developer Developer Developer Melbourne") "community conference" at Docklands in Melbourne.
Big props to Alex Mackey and Malcolm Sheridan, as well as all the other organizers and sponsors, for what turned out to be a great event.
Here’s a quick rundown of the sessions we attended (after the introduction and the opening keynote from Roger Lawrence):
Getting Started With Silverlight and SharePoint 2010
Really we just tagged along to this one to get a glimpse of SharePoint 2010 in action. We don’t do any Silverlight and we’re only ‘end users’ of SharePoint, so the presentation was of little real value to us. It was interesting to see just how complex the creation and deployment of SharePoint “features” is, even in Visual Studio 2010. Nalaka ran a very slick presentation though, so all credit to him.
Design by Contract - Code Contracts in .Net 4
One of the most interesting sessions for me was Bill Tulloch’s demonstration of code contracts. Bill had managed to lose all his code snippets while doing some last-minute testing the night before, so this was very much an “on the fly” presentation. Still, he did an excellent job of demonstrating how code contracts work and the benefits of using them.
I’m not sure that I’m game to introduce them into any existing code. Seems like it’s something that would be much better suited to a “green field” project. Still, it’s powerful stuff and gives us an idea of what the future holds in terms of static analysis on code.
Developing your data access layer using ADO.NET Entity Framework 4.0
Prasanna‘s demonstration of EF4 was extremely valuable for me. I’m keen to look at the Entity Framework as a direction for our data access layer (despite being stuck in .NET 3.5 SP1 for the foreseeable future). I was especially happy to see the “code first” (also known as “code only”) approach to building a model. That looked like a really nice “fluent” approach to constructing mappings without having to deal with a design surface or XML files.
Secrets to Becoming a Better Developer
Sorry, Chris. I really wanted to get to this session (and in fact I saw a few tweets describing it as the “best session of the day”), but I was engaged in conversation with a bunch of folks from the Twittersphere outside, and we didn’t even realise that the next session had started until it was already half way through. So we missed this one, but I found our conversation outside very interesting, so it wasn’t a total loss.
Building large scale LOB applications with WCF RIA Services
By this stage, late in the day after a late night and an early morning, I was really starting to struggle. My eyelids were heavy, and I actually caught myself nodding off during Sergey’s presentation. I’ll be honest: This presentation was dry. There was very little code – mostly slides – and that meant that you had to pay close attention to what Sergey was saying to follow along. Perhaps if I’d not been falling asleep I would’ve enjoyed the session more, but on the other hand, if there had been more code I might not have been falling asleep.
Non-Relational Databases
Tarn’s presentation was probably the most entertaining of the day. He did the whole thing from Ubuntu, using (I think) Vim and Monodevelop along with the command line to demonstrate his code. It was a fun look at the world of “NoSQL” with some compelling arguments.
The Wrap Up
The final “session” was a chance for the guys to give away some prizes and thank the sponsors. Wouldn’t you know that my name was the first to be drawn for a few ticket to REMIX Australia? Unfortunately I had to turn it down ‘coz I can’t make it to Melbourne when it’s on, so instead I got a cool organizer/presenter’s polo shirt which I will wear with pride to our local user group next month. :)
The best thing about events like these is the opportunity to meet face-to-face with people I consider “friends” online. I got to meet (for the first time) Paul Jenkins, Brendan Forster, Aaron Powell, Michael Kordahi and Nick Josevski, as well as catch up with some old friends that I usually only see at Code Camp Oz.
If you missed DDD Melbourne, I can recommend checking out DDD Sydney, which is scheduled for late July at this early stage. I probably won’t be able to make it all the way up there, but if it comes off as smoothly as DDD Melbourne, it should be awesome.
Username Auto-complete in Halfwit
A couple of nights ago I finally started working on username auto-complete in Halfwit. What’s username auto-complete? That’s the feature whereby you type an “@” sign, and then as you type extra characters, Halfwit looks up your text in the list of recently-seen users and fills in the name for you. Here’s a screen cap:
So in this screenshot I’ve typed “@m” and Halfwit has filled in the first matching name – my own. I then typed “o” and it’s picked the next match – MossyBlog (you can pay me later for the free linkage, MossyBlog).
For the technically minded, here’s how it works.
First, I keep a static List<String> of the 1000 most recently seen usernames. I figured 1000 usernames “ought to be enough for anybody”, but I can make that number larger if the need arises.
Next, I’ve defined an attached property that I can apply to any TextBox. It hooks the KeyUp event of the TextBox and does some simple string manipulation to find a matching name.
The cool part is that this lookup can be based on either the text after an “@” sign, or just the whole text. We need that because there’s another TextBox in Halfwit where you can simply type a username without the “@” prefix. The auto-complete works there, too.
I won’t include the code here – you can grab the whole thing from CodePlex. Check out the “UsernameLookup.cs” file for the attached property class.
Saved Searches in Halfwit
Build 57 of my Twitter client Halfwit is now available, with a bunch of new features since I last blogged about it. The one I’ve added tonight is the ability to talk to Twitter to save common searches.
When you visit the Search page, Halfwit will ask Twitter for a list of saved searches and populate the items of the ComboBox with them. If you want to save a search you can simply press the “Save” button to save it back to Twitter. Here’s a screenshot!
As you can see, each saved search has a “Delete” button alongside it in case you want to get rid of it.
Give Halfwit a try today and let me know what you think!
Immutability in C# 5?
On the latest episode of .NET Rocks, Carl and Richard spoke to Anders about the new release of .NET and C# and what the future might hold. Predictably, Anders revealed that parallelism will be a focus on C# 5, with language enhancements to make use of things like Parallel Linq.
One of the things he spoke about was how difficult it is today to make a truly immutable reference type, with compile checking etc. This got me thinking about how immutability might work in a hypothetical future version of C#, without adding new keywords or language constructs. Immediately the “readonly” keyword sprang to mind.
The readonly keyword is applied to fields in a class. Fields declared as readonly can only be initialized inline or in the type’s constructor. Once they’re initialized, they are, as the name implies, read only.
public class Foo { public Foo() { Bar = 5; // Bar can now only be read } public readonly int Bar; }
Imagine if you could declare a class as readonly. All of the class’ fields would have to be declared as readonly too (a bit like the way static classes can only have static members), and its properties would have to have getters only – no setters. Any fields or properties would also have to be either a value type or a similarly read-only reference type, so there was no cheating by changing the property of a property. Let’s mock up a class to see what it might look like:
public readonly class Foo { public Foo(int bar, string buzz) { Bar = bar; _buzz = buzz; } // this would be fine public readonly int Bar; // no setter on our property, so that's fine too private readonly string _buzz; public string Buzz { get { return Buzz; } } // Fizz is a readonly class so this is also fine public readonly Fizz Fizz; }
This class would be guaranteed, at compile time, to be immutable. It would be safe to pass around between threads since nobody could change its state. It’d be fine to add methods to it which perform calculations based on the class’ fields and properties, since even they wouldn’t be able to modify the values (they’re all read only too).
I suppose the next step in this evolution would be a way to constrain methods or generic classes to only accept readonly types as their parameters, so that multithreaded code could be guaranteed not to change state. A simple “where T : readonly” generic constraint might suffice.
In theory it might be possible to take an existing “non-readonly” class and wrap it dynamically into a read only “proxy” (similar to a mock), but that would be complicated since any reference-type properties would need to be wrapped in a similar way, to prevent users changing their values. Not only that, but any collection property on the class would have to be converted to a ReadOnlyCollection or IEnumerable to prevent it from being modifies. It’d be a pretty hardcore piece of code.
I think a way to create a compile-time guaranteed immutable class in C# would be very helpful for people writing massively parallel code. This could be one way to do it … maybe the gurus like Anders have something entirely different in mind. Time will tell!
Windows Mobile development in Visual Studio 2010
So Visual Studio 2010 and .NET 4 have been released, and they’re awesome. I’ve been using VS2010 since beta 2, and it’s a big step up from 2008 when it comes to the code-editing and designing experience.
Which is sad, because I can’t use it.
You see, Microsoft have recently announced Windows Phone 7, which is an all new operating system for mobile devices. It looks fantastic, and I’m really excited about the announcement. To develop applications for WP7, you must use Silverlight. Again, a great idea and I’m all for it.
However, Microsoft seem to have decided that Silverlight on WP7 will be their only mobile development strategy going forward, and have opted to drop any support for Windows Mobile/.NET Compact Framework in Visual Studio 2010. Basically if you want to continue developing your Windows Mobile applications, you’re stuck in Visual Studio 2008.
Let’s be honest about Windows Phone 7 and the enterprise:
Windows Phone 7 is slated to be released some time at the end of this year. Apparently there’ll be a “classic” version that allows enterprises to deploy their own applications to the device rather than going through the public “marketplace”.
That means that we might see in Australia early next year. More realistically it’ll be late next year.
Even if we do, our company has a significant investment in Windows Mobile devices. We have as many WM2003 devices as we do WM6. There’s no way we can simply throw those away and upgrade all our devices to WP7.
If we go by our historical turn-around in devices, I’m looking at being stuck with Windows Mobile until at least 2012, probably more like 2014.
Since our major system here at work targets both the desktop and mobile platform, we have both kinds of projects in every solution. That means we can’t open any of our class-library solutions in Visual Studio 2010.
So right now we have two options:
1. We split the code into separate solutions (one for mobile and one for desktop), but the mobile solution would still just be “links” to the desktop source code. Then we could use VS2010 to modify the code, but we’d still have to use VS2008 to build the mobile projects. Since the two projects would be separate, there wouldn’t be any instant compiler feedback if a change you made in the desktop project broke the mobile project.
2. We stay in Visual Studio 2008 for all our solutions except maybe the WPF-based desktop application. That’s really depressing, since it means we can’t use any of the new .NET 4 features – VS2008 will only compile all the assemblies it depends on to .NET 3.5.
I kind of feel like I’m stuck under water with Microsoft’s boot on my head. I’ve seen hints here and there that a Windows Mobile development “toolkit” for VS2010 will be released out of band some time in the future, but nothing concrete.
