Development
C# Extension Methods
by rob on Apr.16, 2008, under .Net, Development
Just a quick post.. thought I’d share a neat way of handling some legacy date nastyness from an oracle DB that I’m having to interface with.
DateTime’s on this monstrosity of the 90′s are stored as the typical Unix Epoch format, as in seconds since 1/1/1970. The usual method of handling these things is to have some conversion functions in a utility namespace somewhere that handles the (quite simple) translation to and from the C# DateTime format.
However, using new fangled features makes for some really neat code by ‘extending’ framework types to convert to and from the Unix times. Anyway, enough talk, show me the code
public static class ExtensionMethods { /// <summary> /// Long extension method to convert a Unix epoch /// time to a standard C# DateTime object. /// </summary> /// <returns>A DateTime object representing the unix /// time as seconds since 1/1/1970</returns> public static DateTime FromEpoch(this long unixTime) { return new DateTime(1970, 1, 1).AddSeconds(unixTime); } /// <summary> /// Date Time extension method to return a unix epoch /// time as a long /// </summary> /// <returns> A long representing the Date Time as the number /// of seconds since 1/1/1970</returns> public static long ToEpoch(this DateTime dt) { return (long)(dt - new DateTime(1970, 1, 1)).TotalSeconds; } }
So , now instead feeling all dirty inside, riddled with guilt at calling those filthy Utility.Methods() you can ease your conscience by using
DateTime dt1 = DateTime.Now;
long unix1 = dt1.ToEpoch();
DateTime dt2 = unix1.FromEpoch();
Ahh, extension method bliss, and once again all is well in the world.
My work here is done.
For today.
Download the sample
WPF Bitmap Effects Revisited
by rob on Mar.27, 2008, under .Net, Development
Ok, so the first pass was ok (apart from the messed up file uploads
thanks alot WLW! ) but there are still a few minor niggles. Firstly was the whole com registration deal. Whilst its not really a bit deal in development (you can register the effect as part of the build process) when it comes to deployment, well, it means your xcopy deployable project just got a whole load more complex!.
Whilst looking at the possibility of using isolated com & the reg-free support with manifests, I came across a couple of blog entries by John Melville detailing how to build a managed C++ single assembly for bitmap effects.
So, I brushed off my C++ cap, and jumped straight in. Using a single managed C++ assembly approach is a much more elegant solution, and gives us back the ability to distribute the bitmap effect assembly with our application rather than jumping through the usual com registration hoops.
Anyway, I have created 2 new bitmap effects, and I’ve also re-factored the GreyScale bitmap effect in the last post into a single assembly.
The 2 new Bitmap effects are a
- SaturationBitmapEffect
Has a single DependencyProperty called , surprisingly , "Saturation". The range for this value must be from 0.0, to 1.0 which represents an unsaturated image up to a fully saturated image.
Although you can use the HSLBitmapEffect, the SaturationBitmapEffect uses only 3 multiplies so is significantly faster than doing a full colorspace transform just to reduce the saturation. Just like the GreyScaleBitmapEffect, the SaturationBitmapEffect also uses correctly scaled colour components to represent a the greyscale image.
- HLSBitmapEffect
The HLS bitmap effect allows you to control all three components; Hue, Saturation and Lightness. Each RGB colour is transformed into its double hexacone equivalent in the HLS space, and then scaled or shifted by the DependencyProperty’s exposed on the Effect called… heh, you guessed it, Hue,Saturation and Lightness!
Here you see the Bitmap Effect being applied in Blend. If you click the little triangle next to the BitmapEffect Name, you should see the effects dependency properties.
Greyscale Bitmap Effect for WPF
by rob on Mar.21, 2008, under .Net, Development
Technorati Tags: WPF,Greyscale,BitmapEffect
[ please see the THIS post about single assembly effects ]
Whilst trawling the MSDN forums looking for a solution to a problem i was having (completely unrelated to bitmap effects – i’m easily distracted
DataTemplate Triggers with animations in WPF
by rob on Mar.02, 2008, under .Net, Development
I’ve just had the displeasure of burning quite a few hours on a stupid problem with starting animations from a control template using data binding and datatriggers in WPF. I’ve solved it eventually but only after wasting way too long on something I think should have been pretty straight forward.
Anyway, here’s the problem definition.
Write a control to display the state of a variable representing the status of a request to a server. Pretty simple? Well, you would have thought so. But as usual, the ‘lets make it cool’ part of my programmer head got in the way, an I found myself wanting to animate the control.
Ok, nothing amazing, just make it fade up nicely when it changes state, blink while it’s the request is in progress, and fade out when were done. Not to much to ask for!
So, I create a sample application and added the server graphics
This icon represents when the request is downloading information and fades up first, then blinks when at maximum opacity. (Busy)
This icon is when the request is completed. It fades out after the Busy icon has been flashing.
Lastly, this icon shows when the request failed for whatever reason. Im sure the users aren’t concerned with the inner exception property of the soapexception
Anyway, wanting to continue with the distinct separation of concerns for the UI & the internal datamodel I have in my application, I created the control’s template to
Word Binary formats Vs WordprocessingML
by rob on Feb.20, 2008, under Development, General
I noticed today that Joel Spolsky had written an entry about how complicated the Word binary formats are now that Microsoft has finally released the full binary file formats. He notes that the spec is a whopping 349 pages, and you have to digest another 9 if you’re interested in the internal storage layout too.
358 pages? You should try digesting the new XML formats!
First, we get to the WordprocessingML, the reference for which weighs in at 5219 pages! Yep, that’s a whole 34Mb of PDF. Add in the specs for the ‘extras’ that annex the TC45 spec, like DrawingML, CustomXML, Biblio, VML, and EquationML and then add in the OpenXML / OpenPackagingConvention documentation, and its approaching 9,000 pages of specs.
If you’re into self-abuse you can find the whole TC45 document and associated specs for the Office formats on the this page of the ECMA site
Alternatively if you’re interested in the OpenXML formats, and don’t fancy blowing the next 2 years of your life reading the specs, Wouter Van Vugt has an excellent blog on the subject and is the author of the rather more useful (and free!) OpenXML Explained ebook!
Enjoy.
Incremental searching using LINQ to XML
by rob on Feb.11, 2008, under .Net, Development
I have a requirement in the current project to provide a method of converting a title entered in an edit box, into a corresponding code number. The current customers implementation is page based (web style) where you enter words, and click search. after a couple of seconds the results are shown on a page based grid when there are too many results to display. The search also finds ANY of the terms, and doesn’t match on partial words. The time constraints for the telephone operators using this system are quite harsh, and any delay in finding the correct codes is quite a problem.
I think I can provide something much better than the default searching capabilities, which will improve our customers experience, and provide a better service for their clients.
I’ve decided that a real-time incremental search function will give the best results, so given my current project is using .NET 3.5 I decided this was as good a time as any to dive in and figure out how to use LINQ properly. I’ve played with the 101 samples but not really had a chance to apply anything I’ve learned in my own projects.
So, the requirement is to provide incremental matching of multiple partial terms across an XML file with 28,000 nodes, where we’re interested in the title and code elements. I also want to match on all terms entered in the search to narrow the quantity of matches, rather than increasing them.
So, for the first spike, I used an XPath query and a loop to extract the nodes with matching titles. I needed to get a feel for how fast the search would be given we have 28,000 nodes to parse!
600 lines really is a luxury!
by rob on Jan.31, 2008, under Development, General
I’ve seen a couple of posts , the first by Jeff Atwood about what can you build in 600 lines of code and a response from Charles Petzold commenting that 600 lines is a luxury.
Heh. 600 Lines. That really was a luxury. Back when I first started out in the games industry, for fun and a bit of friendly competition we used to write games that must be close to 256 BYTES as possible.
So, the other night I took a quick trip down memory lane and dug out my old source code, and by old I mean old. When I unzipped the code, I swear the monitor turned sepia. This stuff is from the days when 4Mhz PC’s cost more than most cars,CD’s were still a twinkle in Philips’s eye, and Norton Tools was indispensable. Ok, so it was only 1989, but it still feels old!
Anyway, sifting through the files I could only find two examples of my 256 Byte games (and one from a friend) but I’ll present them below for your amusement.
They’re written in 8086 assembly, yep, those are real 16 bit registers
And the tool of choice was TASM, back when Borland produced real tools, rather than the bloated Java crap they’re peddling today.
First up is Pacman. Running these relics in a window means the code to sync to the vertical refresh doesn’t work too well! I had to fire up a VM because they wont run at all on my Vista64 install. Anyway, the ghosts move randomly rather than tracking you, but there is collision detection against the walls. Come on, what do you expect for 256 bytes?
Microsoft LIVE! Maps, WPF and Winforms.
by rob on Jan.30, 2008, under .Net, Development
I was having a deep discussion with a friend the other day, about how WPF and Winforms controls can’t overlap on the same surface. It’s not really a big limitation, since WPF is so rich you’d never need a Winform Control on your surface, right?
What if you really , really wanted a nice Google map or a Live! map on your WPF form? well I guess you’re S.O.L. then.
Well, up until now!
Yep, that’s a Microsoft Live map right there on your WPF form. Ok, I know its not overlapping , so you’re thinking I could have faked it.., but I haven’t honest, its just in a <StackPanel> as an example.
Anyway, here’s how it works.
Charles Petzold, Its an honour!
by rob on Jan.30, 2008, under Development, General, Personal
In trying to keep up with all things WPF, I came across a post on Charles’s Blog outlining how lighting worked in WPF3D. He was having a minor problem with the effect and hadn’t yet worked through how to light surfaces correctly. His test square surface consisted of only two poly’s.
So, being the helpful kind of person I am, I sent him an email outlining how surface subdivision should be used to allow for realistic vertex lighting (which was the effect he was trying to demo) with either Gouraud or Phong shading. I also sent him a couple of book recommendations for 3d work, given he was in the middle of writing 3D Programming for Windows,
![]() |
3D Programming for Windows (Pro – Developer) by Charles Petzold |
which he evidently found useful enough to send me a free signed copy of his latest book! I’m truly in the presence of greatness! Here’s the signed first page.
Thanks Charles!
[EDIT]
Looks like I’m in the not the only one ‘in the club’! Both Jeff Attwood of Coding Horror Fame has recieved a copy, as has the awesome Adam Nathan. (I can thoroughly recommend Adams as one of the best WPF books around too)
![]() |
Windows Presentation Foundation Unleashed (WPF) (Unleashed) by Adam Nathan |
ReSharper 3.x MbUnit and VS 2008
by rob on Jan.25, 2008, under .Net, Development
Image via Wikipedia
As a long time lover of ReSharper, I finally got round to upgrading to the new 3.1 version, but I came across a minor problem after the install, ReSharper wasn’t appearing in the VS2008 IDE
.
So after a quick Google it appears you need a specific incantation when you install on a machine with both versions of Visual Studio installed :
msiexec /i ResharperSetup.3.1.Full.VS80.msi VSVERSION=9.0
hey presto, we’re in business. ReSharper appears on the inside VS2008′s menu bar once more!
The next issue I had wasn’t really a problem with resharper but its built in unit test runner didn’t support MbUnit natively. Enter Albert Weinert , who has created a very nice ReSharper plugin to allow you to run your MbUnit tests right in the IDE using ReSharper’s test runner! I don’t think I’m the only one salute you Albert with each press of f5
Albert’s Blog links to the latest version of his DLLs.



![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=764175ce-8251-4348-abda-2d865cb6a8a0)