WPF Pixel Shaders are HERE!

Checkout Greg Schechters’s blog! Finally we get hardware accelerated Bitmap effects, and it looks like they’re significantly easier to implement than those nasty slow ugly software based effects! <ugh> even thinking about throwing pixel around in a CLR based language makes me want to wash with carbolic soap.

Anyway enough moaning, I’ll dust off nVidia FX Composer and re-work my little pixel shaders into HLSL. It’s been a while since i’ve been this close to the metal πŸ˜‰

If you’re feeling adventurous, you can download the .Net 3.5 SP1 beta from HERE!

Also, ScotGu‘s Blog outlining what’s new is well worth a read.

I’ll try to get round to the pixel shader version of my FX asap. Nothing like being on the Bleeding edge πŸ˜‰

Enjoy!

Posted in General | 6 Comments

WPF DataBinding and DBNulls

After spending a few hours with ADO.NET, typed dataset, and some WPF bindings I was feeling like I’d been 5 rounds with Mike Tyson.

Well, it wasn’t that bad, but it just felt that bad.

The trouble is the behaviour of ADO’s typed datasets when dealing with value types that can be NULL on the database. The implementation of this in ADO leaves much to be desired when interfacing with the real world.

Take the code I was working on today.  I created a value converter binding that converts null values to Visibility.Collapsed. As an example think of an address label that has 4 lines of address – if lines 2 & 3 are missing I want to collapse them so line 4 appears immediately under line 1.

The example above work ok, because strings are reference types and you can set how ADO.NET’s typed dataset behaves when the  column hold a null value.

The default behavior is to throw an exception when you attempt to read the value. Not ideal.

NullValue

If you try to change the behaviour for Value Types such as the Int32 above you’ll get the standard error message that the property value is invalid for that type :

NullError

So, if you have a WPF binding that is bound directly to the contents of a ADO.Net data row, the binding will fail with an exception – not really what i’d like. Reference types are ok, we can simply change the default behaviour of NullValue for the column to (Null) and all will be well.

Since there’s no way to change the behaviour of ADO.Net’s properties, we must resort to using an object to wrap the data row (or if you’re feeling adventurous, you could always add to the partial strongly typed datarow – but you’d need to use a different name to represent your type)

Using a standard C# Class to wrap the data row, we’re basically mimicking the Active Record pattern (wrapping a Database Column with a custom business object). Well, almost, we still have to resort to using the rest of ADO to add our class to a dataset for writing out to the Database (unless we go for something like Castle Active record πŸ˜‰ )

With a little code like the following we can wrap our column :

public class TestClass
{
    private ExampleDS.CustomersRow dataRow;

    public int? CustomerNumber {
        get {
            if (dataRow.IsCustomerLastOrderNumberNull())
                return null;
            else
                return dataRow.CustomerLastOrderNumber;
        }
        set {
            if (value.HasValue)
                dataRow.CustomerLastOrderNumber = value.Value;
            else
                dataRow.SetCustomerLastOrderNumberNull();
            }
    }
}

So, by using nullable types, we can convert the nasty DBNull into a real null making the interface to our data consistent across both value types and reference types.

Now when you bind to the data in your own class (after implementing INotifyPropertyChanged I hope!), you wont see any exceptions being thrown when the binding engine attempts to retrieve a real value type from a database column containing a DBNull!

If application is small and you’re binding to dataset data directly (even though the ADO classes do support property notification changes – See Beatriz Costa’s blog for more about that)  then it may not be worth the extra effort in making the data’s returned values consistent, but on a large application, its almost certainly worth making custom business object , or using one of the many ORM tools like iBatis,nHibernate or Castle’s Active Record, depending on your circumstances!

 

 

 

 

Posted in General | Leave a comment

C# Extension Methods

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

Posted in General | Leave a comment

WPF Bitmap Effects Revisited

Technorati Tags: ,,

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.

hlseffect

 

Continue reading

Posted in General | 11 Comments

Greyscale Bitmap Effect for WPF

Technorati Tags: ,,

 


[ 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 πŸ˜‰ ) i came across many requests for methods of ‘greying’ out or desaturating images etc. There were a few suggestions about converting to a different bitmap format, but that SMELLS and there was a few other things i came across , including an incorrect implementation that grey scaled the image by averaging the 3 pixels.That will give a grey image, (after all , all three components are set to the same value) its not a true grey scale conversion. A real grey scale conversion requires that the conversion factors for each component is weighted according to how we percieve that colour. For example, we perceive many more shades of green than either red or blue, so the green component of an image should make up proportionally more of the final grey scale than the red and blue components.Anyway, after a little digging, I came across an example project in the SDK that was pretty close to what I required , so I set about butchering it. 3 hours later, the GreyscaleBitmapEffect is the result.This is a true bitmap effect, just like the DropShadow or the Blur or the Outer glow, and can be applied to any element, not just your bitmaps.This means you can now have a trigger on IsEnabled=false that makes your element go grey!Anyway, on to the usage. First download the DLL and the managed library at the end of this article.Next, you’ll need to regsvr32 the Com component, from the command line.copy the DLL into your project folder, go to the command line and type Continue reading

Posted in General | 6 Comments

An evening with Derren Brown, and the Agile Manifesto

What a show. The man is simply amazing, magic or psychology, it doesn’t really matter, the end result is both stunning and completely mystifying.

db

Some of the show was obvious trickery like the levitating spirit table), but in my opinion that didn’t detract at all, in fact, I think that it adds to the overall entertainment value.

At work the next day, many discussions were had about the techniques DB may have used to achieve some of the effects. Take the Β£10 serial number trick, a punter is chosen at random by DB throwing a frisbee into the audience. This person is then asked if they can ring a friend, and if so DB wagers Β£10 that he can get the person on the phone to give him a series of numbers that he’s written on a large whiteboard. DB asks the person to repeat some seemingly random questions about mundane objects to their friend. Then on Derrens prompt, the person asks their friend for a series of numbers, which then don’t appear to match the ones Derren had written down on the whiteboard. When the trick doesn’t seem to have worked Derren owns up to the friend on the phone that he’s on the speaker phone on stage, and tells him the trick was a resounding success!

The rest of the audience is still under the impression that the trick failed miserably as the assistant is dismissed back to their seat. However, just as they’re approaching the edge of the stage DB fetches them back and asks them to take out the Β£10 they won in the bet. When they open up the Β£10 , the serial numbers on the Β£10 match the numbers the person on the phone gave! What a reveal!.

 

Continue reading

Posted in General, Personal | Leave a comment

DataTemplate Triggers with animations in WPF

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

download_server This icon represents when the request is downloading information and fades up first, then blinks when at maximum opacity. (Busy)

 

enable_serverThis icon is when the request is completed. It fades out after the Busy icon has been flashing.

 

desable_server

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

Continue reading

Posted in General | 5 Comments

Word Binary formats Vs WordprocessingML

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.

 

 

Posted in General | Leave a comment

Incremental searching using LINQ to XML

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!

 

Continue reading

Posted in General | Leave a comment

Cloverfield!

Wow, what a film. JJ Abrams – the boy done good. To do this film justice you need to see it on a screen as large as possible, but more importantly, the sound system needs to be capable of shaking you from your seat or you just won’t be getting your money’s worth!

cloverfield-teaser-poster

We watched at Cineworld in the Centertainment park near Meadowhall on screen no. 7, a 700 seater auditorium that is one of the largest in Europe – and wow, what an impact.

I wouldn’t say it’s horror, and I don’t think its really a monster flick, even though there’s plenty monsters. It’s the usual JJ Abrams stuff, where you never quite get to figure out what’s happening, but you just keep wanting to know more, and its packed to the brim with suspense. After an initial lead in with a party setting, the action starts, and then there’s an intense torrent of tension and apprehension which just doesn’t let up until the film is over.

If you’ve watched JJ Abrams TED talk about his Mystery Box – the film will totally make sense , and knowing how he works only adds to the experience I think.

One minor annoyance seems to be the blatant product placing for Nokia – I counted 7 blatant appearances the first of which was a Pink Nokia almost full screen in the party, which once you’re aware of them you end up spinning cycles looking for them instead of watching the film.

All in all a pretty good way to spend a couple of hours!

Posted in General, Personal | Leave a comment