Just Let It Go

I was reading a blog post (Narcissism of Small Code Differences) today, and something rang true.

Basically the post (or what I got from it), is that the differences in ways people program are just that, differences. Just because a bit of code maybe isn’t written the way I would write it, doesn’t mean it’s wrong. As depicted in the post, there may be reasons why code is done in a certain way!

I mention this now, as I’ve just come across some code from a co-worker that in the past, I probably would have re-written, it’s a simple thing, and really more style based than efficiency etc.

The co-workers code reads like:


if(!xxx)
{
/*Do some stuff*/
return false;
}
else
return true;

Here I would itch to get rid of the ‘else’, either:


if(!xxx)
{
/*Do some stuff*/
return false;
}
return true;

as the ‘else’ is irrelevant in this case. Or even:


if(xxx)
return true;


/*Do some stuff*/
return false;

Neither would change the way the method works, but both are purely style changes that look more pleasing to me. But, hey! What if the original coder prefers it his way – it’s wrong for me to force my style on someone else.

So today I’ve decided to let go any style changes unless they significantly make the code easier to read / debug etc… Yay for narcissistic me!

Pulsy Button

After much umming and ahhing, and developing several versions of BrokeyButton I have the first cut of the PulsyButton.

What is PulsyButton? Well, it’s a button – that pulses. By pulsing I mean that it ‘pulses’ between the Background colour and a ‘PulseColour’ (that you set!).

Pulsy Button

Easy usage:
<PulsyButton Content="Hello" BackgroundColor="LightGray" PulseColor="Red" IsPulsing="True"/>

Obviously if IsPulsing is set to false then the button won’t pulse.
As it’s just based off the ‘Button’ base class, you can literally insert it wherever you have a Button, and all your styles etc will work fine.

I have plans to add more properties, and will over time:
* PulseTime — A TimeSpan for the pulse.
* PauseTime — A TimeSpan to pause the pulse for, i.e. pulse-paaaaauuuuusssseeeee-pulse etc

Also plans to fix some problems:
* Use StoryBoard and set the Background property directly
* Get rid of BackgroundColor property, so only Background is needed

Erm, can’t think of others at the moment.


Bit more detail -> What have I done?

Well, I had a lot of trouble getting a StoryBoard to work programmatically, I don’t know why, and I will perservere. But in the mean time, I’ve resorted to just a simple ColorAnimation.

How have I used a ColorAnimation with a Background brush?

Well, first I created a DependencyProperty:

public static readonly DependencyProperty BackgroundColorProperty
= DependencyProperty.Register( "BackgroundColor", typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( BackgroundColorChanged ) );

private static void BackgroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb.Background = new SolidColorBrush( (Color) e.NewValue );
}

This was my ahem workaround to the setting of the Background property directly, as the ColorAnimation will only animate Color properties (i.e. target the SolidColorBrush.Color property for the brush). By the by, it was the targeting of that property that caused me much hassle.

Anyhews, once we’re there, we should also have a PulseColor property (yes I know colour should have a ‘u’ in it, but I’ve gone all americanized :))

public static readonly DependencyProperty PulseColorProperty
= DependencyProperty.Register( "PulseColor", typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( PulseColorChanged ) );

public Color PulseColor { get { return (Color) GetValue( PulseColorProperty ); } set { SetValue( PulseColorProperty, value ); } }

private static void PulseColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb._pulseAnimation.To = (Color) e.NewValue;
}

Here I’ve included the PulseColor property, rest assured there is a BackgroundColor property as well. So, now we have the two colours to animate between, Background -> Pulse -> Background… We just need to create the animation.

private readonly ColorAnimation _pulseAnimation = new ColorAnimation();

There’s no need to recreate it, so it’s a readonly member. But when do I set this bad boy up? Not the constructor – nooooo, the colour properties won’t have been set up at that point, so I’ve gone for a ‘Loaded’ event consumer.

public PulsyButton()
{
Loaded += PulsyButton_Loaded;
}

private void PulsyButton_Loaded( object sender, RoutedEventArgs e )
{
_pulseAnimation.From = BackgroundColor;
_pulseAnimation.To = PulseColor;
_pulseAnimation.Duration = new Duration( TimeSpan.FromSeconds( 1 ) );
_pulseAnimation.AutoReverse = true;
_pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;


this.BeginAnimation( BackgroundColorProperty, _pulseAnimation );
}

The animation will now begin, and the pulsy fun is nearly there!
But wait… what about turning pulse on/off?

All that is done in the IsPulsingChanged property:

private static void IsPulsingChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
bool isPulsing = (bool) e.NewValue;
PulsyButton pb = (PulsyButton) d;
if( !isPulsing )
{
pb._pulseAnimation.RepeatBehavior = new RepeatBehavior( 0 );
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
else
{
pb._pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
}

Now, I’m not 100% sure this is the correct way to do this, in fact I’m certain it’s not. However, it does work, which at the moment is what matters.

So there you have it, a button that pulses.

——————=====================———————–

Can’t attach the code to the post, so gonna have to past it here, sorry!!

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

public class PulsyButton : Button
{
private readonly ColorAnimation _pulseAnimation = new ColorAnimation();

public readonly DependencyProperty IsPulsingProperty
= DependencyProperty.Register( “IsPulsing”, typeof( bool ), typeof( PulsyButton ),
new UIPropertyMetadata( IsPulsingChanged ) );

public bool IsPulsing
{
get { return (bool) GetValue( IsPulsingProperty ); }
set { SetValue( IsPulsingProperty, value ); }
}

private static void IsPulsingChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
bool isPulsing = (bool) e.NewValue;
PulsyButton pb = (PulsyButton) d;
if( !isPulsing )
{
pb._pulseAnimation.RepeatBehavior = new RepeatBehavior( 0 );
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
else
{
pb._pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
}

public static readonly DependencyProperty PulseColorProperty
= DependencyProperty.Register( “PulseColor”, typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( PulseColorChanged ) );

public Color PulseColor { get { return (Color) GetValue( PulseColorProperty ); } set { SetValue( PulseColorProperty, value ); } }

private static void PulseColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb._pulseAnimation.To = (Color) e.NewValue;
}

public Color BackgroundColor
{
get { return (Color) GetValue( BackgroundColorProperty ); }
set { SetValue( BackgroundColorProperty, value ); }
}

public static readonly DependencyProperty BackgroundColorProperty
= DependencyProperty.Register( “BackgroundColor”, typeof ( Color ), typeof ( PulsyButton ),
new UIPropertyMetadata( BackgroundColorChanged ) );

private static void BackgroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb.Background = new SolidColorBrush( (Color) e.NewValue );
}

public PulsyButton()
{
Loaded += PulsyButton_Loaded;
}

private void PulsyButton_Loaded( object sender, RoutedEventArgs e )
{
_pulseAnimation.From = BackgroundColor;
_pulseAnimation.To = PulseColor;
_pulseAnimation.Duration = new Duration( TimeSpan.FromSeconds( 1 ) );
_pulseAnimation.AutoReverse = true;
_pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;

this.BeginAnimation( BackgroundColorProperty, _pulseAnimation );
}
}

New Header!

Huzzah! I’ve utilised all my artistic skills and whomped a new header to the site!
I’m sure you’ll agree it’s pretty spiffy 🙂

Extensionising Wpf (or Chris’ fun with Extension methods and Wpf)

To be honest, it’s not really trouble using, or indeed writing extension methods, I don’t really have any troubles writing them, it’s more what I wanted to do with them that has bugged me.

As everyone who gets into writing WinForms / WPF apps knows, there will come a point where you will need to partition the work you’re doing to another thread. The usual reasons (so you can do other things, so the UI doesn’t lose it’s interactivity etc) apply.

Once you’ve entered this world you may even want to update the UI from within the thread – maybe it’s just a simple thing like enabling a button, changing the text on a label (etc). It’s quite a common thing to do and as such you can find shed loads of blogs, articles on the whys and wherefores of achieving those goals. I’ve been a WinForms developer for oooh, 4 years now, with the last year being a crossover of WPF / WinForms development. As a consequence I’ve done this quite a lot, and tend to find I have the same methods littering my code for achieving these goals:

private delegate void UpdateControlVisibilityDelegate(Control control, Visibility visibility);
private void UpdateControlVisibility(Control control, Visibility visibility)
{
if(!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateControlVisibilityDelegate(UpdateControlVisibility), control, visibility);
return;
}
control.Visibility = visibility;
}

Obviously, this is called pretty easily via the code:

UpdateControlVisibility(_myLabel, Visibility.Hidden);

Nicely, even if this is called from another thread, it avoids the cross-threading issues.

But what about making it better? Using the tools available and going all Extension method on it’s arse??

Extension methods are (I think) great, even if Resharper is currently screwing up the intellisense for them! Anyhews, the basic signature we’ll be looking at for the method would be something like:

public static void UpdateControlVisibility(this Control control, Visibility visibility)
{
/* Code */
}

Two things different from the previous, first, it’s static, second it’s got the ‘this’ keyword in front of the ‘Control’ argument. OK, so now lets just plug in the code…

private delegate void UpdateControlVisibilityDelegate(Control control, Visibility visibility);
public static void UpdateControlVisibility(this Control control, Visibility visibility)
{
if(!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateControlVisibilityDelegate(UpdateControlVisibility), control, visibility);
return;
}
control.Visibility = visibility;
}

Ah. The biggest problem is that the method uses the ‘Dispatcher’ property of the Window class. As the extension method has to be in a static class, we don’t have access to the Dispatcher property… so… should we pass it in?

public static void UpdateControlVisibility(this Control control, Visibility visibility, Dispatcher dispatcher) { /**/ }

We could. It would work (or at least in my tests seems to), but would be a bit messy, ideally we only want to pass in the Visibility argument (remember as it’s an extensibility method, the ‘control’ part isn’t ‘passed in’). So. What to do? Luckily, the ‘Dispatcher’ property is actually on the Control itself, so we can modify the method call to be something like:

public static void UpdateControlVisibility(this Control control, Visibility visibility)
{
if(!control.CheckAccess())
{
control.Dispatcher.Invoke(DispatcherPriority.Send, new UpdateControlVisibilityDelegate(UpdateControlVisibility), control, visibility);
return;
}
control.Visibility = visibility;
}

The only real thing of note is that we’re using the ‘CheckAccess()’ method of the control rather than the Dispatcher’s. No real reason, just shorter to type, and does the same thing (or so reflector tells me 🙂 ).

So, now we can just get our Control based, err, controls to have their Visibility changed safely:

_myLabel.UpdateControlVisibility(Visibility.Hidden);

Good thing is that we can just whack this code into a utility project and utilise it where we want.

So – is this all good? Have we solved the problems of the world? No, sadly not. There are some caveats which you should be aware of. I originally attempted this so I could ‘Show()’ a Window safely. This led to me writing the following:

private static void ShowSafelyDelegate(this Window window);
public static void ShowSafely(this Window window)
{
if(!window.CheckAccess())
{
window.Dispatcher.Invoke(DispatcherPriority.Send, new ShowSafelyDelegate(ShowSafely), window);
return;
}
window.Show();
}

I was using this like this (you’ll have to bare with the threading here, it’s important to the story..):

///Handles the click of the button, gets the data on a new thread.
private void _btn_Click( object sender, RoutedEventArgs e )
{
Button b = sender as Button;
if(b == null)
return;
Thread t = new Thread(GetData);
t.Start(b.Tag);
}


///Gets the data and shows it in a
///The information to retrieve the data with.
private void GetData(object obj)
{
RetrievalInfo ri = obj as RetrievalInfo;
if(ri == null)
return;
DataTable table = DbUtils.GetData(ri);
WndwResults wr = new WndwResults(ri, table);
wr.ShowSafely();
}

Now, as we can see, the ‘GetData’ method is run on a seperate thread and constructs a WndwResults Window, and displays it (using the ‘ShowSafely’ method. Looks fine, but when run, will throw a tiswas and give you an:

InvalidOperationException
"The calling thread must be STA, because many UI components require this."

OK, so lets set the Apartment state of the thread to be STA…

Thread t = new Thread(GetData);
t.SetApartmentState( ApartmentState.STA );
t.Start(b.Tag);

GO!

ARGH!!!

LoaderLock detected
"Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang."

???

What the hell does this mean??
Turns out that the Loader Lock is a system wide lock which Windows uses to load / unload dlls (http://www.lenholgate.com/archives/000369.html). As to what it’s doing here, well, I need to spend some more time investigating that. However, more importantly right now is what we can do about it?

Well, we can disable the Managed Debugging Assistant for the LoaderLock exception (via the ‘Debug -> Exceptions’ menu option), but when we do this, we see the Window we’re loading flash up and then dissapear – which isn’t exactly what we want… The other option is to change the code.

In my initial code, I created the WndwResults Window in the new thread. If I take this back a bit further, and construct the WndwResults in the main thread, (not ‘Show’ it, but just construct it) then we’re ok:

/* Simplified example */
{
WndwResults wr = new WndwResults();
Thread t = new Thread(ShowWindow);
t.Start(wr);
}


private void ShowWindow(object o)
{
Window w = o as Window;
w.ShowSafe();
}

The above code works fine, and that’s because we’re not constructing the Window in the new thread. Of course the issue here is that I can’t now pass the data into the constructor, which costs me a few things – use of ‘readonly’ for the members, and other such things. But we can live with that.

Soooo….

We add a ‘SetData’ method to the Window:

public void SetData(DataTable table, RetrievalInfo ri){ /*....*/ }

and, going back to our previous code:

///Gets the data and shows it in a
///The information to retrieve the data with.
private void GetData(object obj)
{
RetrievalInfo ri = obj as RetrievalInfo;
if(ri == null)
return;
DataTable table = DbUtils.GetData(ri);
_wndwResults.SetData(table, ri); //
_wndwResults.ShowSafely();
}

Run the code… and… FFS!!!

InvalidOperationException
"The calling thread cannot access this object because a different thread owns it."

Of course it does! Hmmm, not a lot can be done in this situation, because the SetData (in my case) sets a couple of DependencyProperties, which in turn update the UI.

What can be done though? Well – we can make the SetData method literally only set member variables, and then attach to the ‘Loaded’ event of the Window in it’s own constructor, so… if it originally did this:

public void SetData(string message)
{
_lbl.Content = message;
}

Now it needs to do this:

//First add the member:
private string _message;


//Second add to the constructor of the Window and event handler.
public Window1()
{
InitializeComponent();
Loaded += Window1_Loaded;
}


//Handle the event...
private void Window1_Loaded(object sender, RoutedEventArgs e)
{
_lbl.Content = _message;
}


//Finally, modify the SetData method to actually set the data.
public void SetData(string message)
{
_message = message;
}

Phew! Lots of stuff to do, and that’s just for setting a label!

What are the conclusions of this epic of blog posts?
Well, quite frankly, going down the extension method route, whilst informative in learning how the threading works (well, a bit) has given me some useful methods, but, there are a lot of caveats that a Window has to adhere to, to make it work properly.

I’m going to persevere with this though, I reckon I can at least get some decent set of utility extension methods (for example the setting visibility one) for WPF controls. I’ll keep you posted – you never know, it might even be more frequent than once a month!