Archive for the ‘.Net’ category

Custom Visual States in Silverlight

March 9th, 2009

Visual States are the way Silverlight communicates basic state information about an object.  Is a button pressed?  Is a mouse over a button?  Is a button normal?  The available states for an object are indicated via decoration with the TemplateVisualStateAttribute (in System.Windows).  For example, the Button class in Silverlight looks like this:

[TemplateVisualState(Name="Unfocused", GroupName="FocusStates"),
TemplateVisualState(Name="MouseOver", GroupName="CommonStates"),
TemplateVisualState(Name="Normal", GroupName="CommonStates"),
TemplateVisualState(Name="Pressed", GroupName="CommonStates"),
TemplateVisualState(Name="Disabled", GroupName="CommonStates"),
TemplateVisualState(Name="Focused", GroupName="FocusStates")]
public class Button : ButtonBase
{
    // Methods
    public Button();
    internal override void ChangeVisualState(bool useTransitions);
    public override void OnApplyTemplate();
    protected override void OnClick();
    protected override AutomationPeer OnCreateAutomationPeer();
}

You might notice from this code that the various states also have group names.  If you look at the states it makes sense why we would want to group them.  States like Unfocused and Focused are related.  States like Mouse Over, Normal, Pressed, and Disabled are all related to how a button looks with various interactions.  Silverlight only allows one state from any group of an object to be active at once.  This also makes sense.  A button cannot be Focused and Unfocused, or Pressed and Normal, but a button can be both Pressed and Focused.  I like to think of each group like an enumeration, and the states of each group as the values that enumeration can hold.

When the button switches to a new state, it does so by calling VisualStateManager.GoToState(…).  Of course there needs to be some logic to fire this switch, and this is ultimately driven by built-in events like MouseEnter, MouseDown, etc.  To switch to Focused, the code might look like:

VisualStateManager.GoToState(this, "Focused", true);

To consume visual states one uses something called a VisualStateGroup class which contains a VisualState objects, one each corresponding to a visual state decorated on the class. This object is attached to the object’s template. Here is some sample XAML for the button class:

<ControlTemplate TargetType="Button"
                 xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
  <Grid >
    <vsm:VisualStateManager.VisualStateGroups>
      <vsm:VisualStateGroup x:Name="CommonStates">

        <vsm:VisualStateGroup.Transitions>

          <!--Take one half second to trasition to the MouseOver state.-->
          <vsm:VisualTransition To="MouseOver"
                              GeneratedDuration="0:0:0.5"/>
        </vsm:VisualStateGroup.Transitions>

        <vsm:VisualState x:Name="Normal" />

        <!--Change the SolidColorBrush, ButtonBrush, to red when the
            mouse is over the button.-->
        <vsm:VisualState x:Name="MouseOver">
          <Storyboard>
            <ColorAnimation Storyboard.TargetName="ButtonBrush"
                            Storyboard.TargetProperty="Color" To="Red" />
          </Storyboard>
        </vsm:VisualState>
      </vsm:VisualStateGroup>
    </vsm:VisualStateManager.VisualStateGroups>
    <Grid.Background>
      <SolidColorBrush x:Name="ButtonBrush" Color="Green"/>
    </Grid.Background>
  </Grid>

This markup generates a VisualStateGroup named to correspond to a group on the object. It contains visual states, each named to correspond to an existing state on the object.  The VisualStateGroup can also contain transition objects to control the transition to any given state.  The VisualState itself doesn’t do anything but start a Storyboard animation.  From that animation you target objects and properties as you would any other story board.  The pieces all just fall into place!

Many built-in object contain a number of visual states that you can utilize with control templates to change look and feel, but you can also create your own visual states on custom objects, and consume those states in your own custom code.  While this system is not as flexible as the event triggers built into WPF, it does allow for some interesting capabilities.

Events, Delegates and Conditionals, Oh My!

March 7th, 2009

The traditional pattern for writing events in C# has been a 3 step process:

  1. Define the event in your class.
  2. Define a utility function to check if the event isn’t null, then fire it.
  3. Write code that calls the utility function.

An example:

public event Action<object,EventArgs> MyEvent;

protected virtual void OnAction(object sender, EventArgs args)
{
  if(MyEvent != null)
  MyEvent(sender, args);
}

...

//somewhere late in code
OnAction(this, new EventArgs);

This pattern, or variants of it, can be found all over the .Net framework, in various component suites, and in many .Net applications.  I have used it for years.  But with the advent of .Net 3.5′s abbreviated “lambda” style for delegate construction, a new pattern has emerged.  It took a while for me to convince myself that it is better, but I now use it all of the time.  This is also a three step process:

  1. Define the event in your class.
  2. Write an anonymous delegate for the event in the class constructor.
  3. Write code that directly fires the event.

An example:

public event Action<object,EventArgs> MyEvent;

public MyClass()
{
  //an anonymous delegate that does nothing
  MyEvent += (sender, e) => {};
}

...

//somewhere late in code
OnAction(this, new EventArgs);

Of course this could also be done in .Net 2.0 using the old anonymous delegate syntax, and since it all runs on the same CLR, its prolly the exact same IL.

The vital difference in these two patterns is the checking for a null value of the event. In the first pattern, a conditional statement is checking to make sure that the event is not null i.e. something is subscribed to the event. The second pattern doesn’t have to check this because we subscribed to the event in the constructor.  The event will never be null. What are the pros of doing it the second way?

  1. No conditional code needs to be written.  This eliminates bugs.
  2. Repetitive code is eliminated.
  3. The code is easier to follow.  Events are fired directly instead of going through a utility function.
  4. The code is easier to maintain, since there is less code.
  5. This is a rather anal point, but this code is also more thread safe.  In the first pattern an event could theoretically have a subscriber when checked, and not have one by the time it is called.  Like I said, pretty anal but true.

Of course the con here is creating a delegate for an event that may never be fired.  Delegates take up some small amount of ram, yada yada yada.  The OO prgrammer in me didn’t like the smell of this solution.  The pragmatist in me won out.  It is easily worth the trade-off in the small amount of resources needed for the anonymous delegates in the 2nd pattern to eliminate all of the cons of the first pattern.

Determining If Rectangles Intersect?

March 5th, 2009

Its funny the things one finds out are missing in a new framework.  Silverlight 2 is missing (as far as I can tell) a rectangle intersection/collision/overlapping test function.  I started writing my own and immediatly had a very nasty chunk of code.  I knew I was doing something wrong.  I found this short article which immediatly made me think back to college CompSci with its simple solution.  I need to test if two rectangles are overlapping, but the logic is easier if I write to test if they aren’t overlapping and negate the answer.  I have written an extension method in C# for the Silverlight Rect class to impliment logic similar to this.  Nifty!

Silverlight 2 1/2

March 3rd, 2009

There are some missing parts to Silverlight that really bother me.

  1. TemplateBinding – The TemplateBinding concept is a XAML tag only.  There is no backing class in the CLR.  Additionally, the TemplateBinding functionality does not support complex paths.
  2. Control Binding – There is no control binding is Silverlight.  Databinding works great, but I sure would like to be able to bind to a dependency object.
  3. ControlTemplate – You cannot programatically construct a ControlTemplate.  The ControlTemplate is both a XAML tag and a class, but there are no properties or methods in the class to provide a way to construct it in code.  This is yet another case of the XAML parser and the Core CLR doing some black magic.
  4. Timeline – The Timeline class is the base class for all of the built-in animations in Silverlight like Storyboard, ColorAnimation, DoubleAnimation, et al.  With a base class like this one would think one could inherit and implement a custom animation class.  Nope.  It looks like the actual functionality for these animations is hidden somewhere in the Core CLR, and these classes are just definitions of the animation.  To do custom animations one must use a game-loop.

These are all “black box” items to me.  Each one of these items bothers me because it presents Silverlight not as an extensible framework but as a simple API (well, not so simple).  As a long time .Net developer this really bothers me.

A couple of other things that bother me about Silverlight:

  1. Graphical elements do not have a “position changed” event.  Sometimes I want to know if an element has moved so I can do something about it.
  2. No right-mouse button support.  There are hacks to get around this but they don’t necessarily work across browser.
  3. Built-in drag-and-drop.  I just finished writing a custom control to allow drag-and-drop.  It was a lot of work and is not fully featured.

Point #2 from above is an inconvenience, but point #1 makes me take some radical approaches like polling or writing custom objects that do attempt to tell you when they have been moved.

With all of this hasle, Silverlight is a quantum-leap beyond HTML + CSS + Javascript.  It downloads and installs quickly.  It is very responsive.  The graphical things it can do are very awesome.  I just hope Microsoft address some of these points in the next release of Silverlight.

Poor Silverlight Documentation

February 17th, 2009

Microsoft has done a rather poor job of properly documenting Silverlight 2.0. I have run across several outright errors in the official MSDN documentation, and finding acurate documentation at other sources is very difficult. Today I am trying to style the header elements of a Silverlight DataGrid. The documentation for this is scant and wrong. Luckily I have found the default styles used out-of-the-box by Silverlight. Using the default styles, I figured out exactly where I was going wrong, and where various documentation I had read was wrong. There is nothing like learning by example.

ContentPropertyAttribute

February 9th, 2009

While diving into the programming of custom controls in Silverlight I wanted to set one of my properties as the “default property” from XAML.  What I mean here is that I wanted to emulate the behavior of many out-of-the-box controls in Silverlight (and WPF for that matter) where a property need not be explicitly specified, in all cases a content property of some sort.  For example, the Button control has a Content property which can be set in these three ways (excluding binding):

  1. <Button Content=”Click Me”/>
  2. <Button><Button.Content>Click Me</Button.Content></Button>
  3. <Button>Click Me</Button>

The relationship between these different ways of setting Button.Content should be fairly obvious.  Through XAML one can usually set any property on the underlying object via an attribute or child element.  Additionally, one property can be marked as the “default property”.  But how is this done?  How can I write a control and mark one of the properties as the “default property”.

In XAML/Silverlight/WPF parlance, this is refered to as the Content Property, which is confusing since there is also a property on a number of controls called content, and to make it even more confusing the property named Content is also the Content Property.  Confused?  Lets take a swing at this using my custom control and see how to set the Content Property on a control with no property called Content.

I have a control that doesn’t have “content” per se, but accepts a list of rules which regulate how the control should act.  I want the XAML to accept this list as the “default property”.  I want to be able to write:

<RuleManager>
  <Rule ... />
  <Rule ... />
  <Rule ... />
</RuleManager>

instead of the more verbose:

<RuleManager>
  <RuleManager.Rules>
    <Rule ... />
    <Rule ... />
    <Rule ... />
  </RuleManager.Rules>
</RuleManager>

The way I do this is with the ContentProperty Attribute in System.Windows.Markup:

[ContentPropertyAttribute("Rules")]
public class RuleManager
{

public static readonly DependencyProperty RulesProperty =
DependencyProperty.Register(“Rules”,
typeof(RulesCollection),
typeof(RuleManager),
new PropertyMetadata(null));

public RulesCollection Rules
{
get { return (RulesCollection)GetValue(RulesProperty); }
private set { SetValue(RulesProperty, value); }
}

public RuleManager()
{
Rules = new RulesCollection();
}
}

The ContentPropertyAttribute class should probably be renamed something like DefaultXamlPropertyAttribute since it does not always specify Content, but does specify the default property.  Its constructor takes the name of the property to use as the default (or "content") property. It took some digging, but this is the correct way to do it and it is tested working.  From XAML I need not specify the Rules element (aka property); the XAML parse will assume that information included here is mean for the Rules property based on the attribute.

MSDN documentation of ContentPropertyAtrtibute in Core CLR (Silverlight)

Catch Clause or: Crap! There is something I don’t know about C#.

October 18th, 2008

I first started programming .Net in 2000.  I got my hands on the Beta 2 version of .Net 1.0.  In those days I was programming in VB6, so VB.Net seemed like the best choice.  But a couple of weeks after downloading the beta I was in a book store and saw a C# book.  I picked it up and started thumbing through it.  I remember I said something out loud like, “Wow, this is just like Java!” I had programmed in Java for a while as well, and had a background in C/C++. I preferred the syntax greatly to that of VB.  From there on out I tried to do all my .Net stuff in C#.

I recount this tale because I so rarely find something in C# I don’t know or understand. This is bragging. Its just the reality of getting to know a language/environment over several years. 

Of course there are new language features released every year or two that I have to work to learn.  But all in all, the language isn’t much of a mystery to me.  So yesterday when a coworker told me I was using a throw statement in a catch clause wrong, I was very surprised.  I was doing something like:

try
{
  ...
  SomethingThatMyThrowEx();
}
catch(Exception ex)
{
  ...
  throw ex;
}

So what is wrong with this? I didn’t see anything wrong at all. I wanted to catch the exception, take some action, and simply re-throw the exception. And this code will do that. The problem is, the exception will have a new stack trace from the point at which I re-throw it. Why? Because the throw statement takes and expression, not an object. The “ex” object in this case is being used as an expression of how the exception should look when thrown. This seems really strange, but it is in the C# language spec. Crap, how did I miss this all these years!

When C#/.Net executes the throw line it uses the exception object as an expression of how the expression should be thrown, and ads a stack trace from the current location in code. The previous stack trace is gone.

So how do we preserve the stack trace? We use only the throw keyword with no expression. This instructs .Net to simply continue the exception bubble-up process:


try
{
  ...
  SomethingThatMyThrowEx();
}
catch(Exception ex)
{
  ...
  throw; //no ex
}

Pretty simple, and pretty damn subtle. I won’t forget that one!

.Net Parallel FX Library

September 18th, 2008

Microsoft is currently developing a new set of additions to .Net called the Parallel FX Library.  The library is intended to provide a better/easier API for multi-threading in .Net.  Anyone familiar with .Net will tell you that it already provides a rich threading library.  It is fairly easy to create and use threads in .Net using a number of approaches.  When I first read about the Parallel FX Library months ago, I was completely unexcited.  Last week I finally decided to take a look at the technology, and now I am excited.

Microsoft new libraries for threading is a giant leap forward for parallel tasks.  It is not a replacement for traditional, long running threads.  Instead, it is intended to help the developer offload tasks to multiple threads for performance gains on mult-core systems.  You cannot walk into a computer store and buy a new computer that isn’t at least dual core, so it makes sense that Microsoft would be targetting these platforms.

So far I have only explored the two areas of the Parallel FX Library, the basic Tasks framework, and the psuedo-looping mechanisms.

The Task is the basic unit of multi-threadedness in PFX.  The task encapsulates a delegate that will run on a thread.  The class Task is contained within the new namespace System.Threading.Tasks.

int x = 0;

//creates task, schedules for execution
Task task = Task.Create(foo => { x += (int)foo; }, 2);

//wait until execution is complete
task.Wait();

Console.WriteLine(x); //2

This example is very simple but illustrates the core concept that is the Task class.  As soon as Task.Create() returned the anonymous delegate was scheduled, and probably executing on a background thread.  The call thread.Wait() simply made the main thread hold until the value returned.  For those with a threading background, the Wait() statement will be obvious.

So what did this buy us?  Well, not a whole heck of a lot.  But this is just a very simple example.  Microsoft has built a lot of cool functionality on top of Task that will allow you to spawn all kinds of threads without having to manage them, all based on Task.

Consider the following example, which would not make very good production code but hopefully makes good example code:

int x = 0;
List<Task> tasks = new List<Task>();

//creates task, schedules for execution
for (int i = 0; i < 100000; i++)
{
Task task = Task.Create(foo => { x += (int)foo; }, i);
tasks.Add(task);
}

foreach (Task task in tasks)
task.Wait();

Console.WriteLine(x);

This code should run faster than a straight loop doing the same thing because these computations will be distributed to multiple threads which hopefully will be executed on multiple processor cores.  This code works, but I am still having to keep track of the tasks.  It seems like this should be done for me, and after a little digging I found that Microsoft has a class called Parallel in System.Threading.  This class has a few, very convenient static functions, For, For<>, and ForEach<>.  As you might guess, these functions act like loops.

int x = 0;
Parallel.For(0, 100000, foo => { x += foo; });
Console.WriteLine(x);

As you might guess, Parallel.For() is utilizing the Task class under the covers to execute the included anonymous delegate (lambda) to accomplish the same result as I wrote above.  The function signature for For takes an Action<int>, so we don’t need to cast foo to int.  The call does not return until all of the execution is completed.

Pretty cool so far.  We are now able to do repetitive operations on multiple threads with minimal code and no thread management.  For<> simply adds a generic type declaration for Action<>, and ForEach<> allows enumeration across a set of objects for the work.

I plan on digging into PFX more over the next week or two.  Some thought that this library might be release with .Net 3.5 SP1.  I would imagine that there will be another .Net release like .Net 3.6 or .Net 4.0 that will include PFX plus other works in progress like ASP.Net MVC.

Tired of SQL like syntax for LINQ

August 26th, 2008

I am a little tired of using the SQL like syntax that is available for LINQ.  Don’t get me wrong, LINQ and the language / .Net features introduced to support it in .Net 3.5 are great.  I don’t find myself using the SQL to LINQ at all, but I constantly find myself using LINQ with collecitons and XML.  After almost a year with the enhancements (in beta version this in GA .Net 3.5), the appeal of the SQL-like syntax has worn off, and I have come to realize that I enjoy using the actual function calls to which this psuedo-SQL-language is mapped.

I think the the SQL-like LINQ syntax was just the sugar to attract attention to LINQ.  In practice I have found that it make my code less readable.  To a developer that is not intimately familiar with LINQ, a complex expression is completely unintuitive.  It is just enough unlike SQL to confuse.  When it comes to complex select statements, joins, and other operations that are outside the standard SELECT…FROM…WHERE syntax (or FROM…WHERE…SELECT in LINQ), simply calling the framework functions directly makes more sense to me.  It creates code that is easier for C# developers to read.  It isn’t pretending to be SQL, and so it becomes much easier to follow what is really happening to anyone that understands enumeration, iteration and delegates.  With function chaining, it is also easy to write very clean chunks of code by use of indentation.  And when I have to explain the code to another developer that is unfamiliar with LINQ I can simply say, “.Select() is run for each record, .OrderBy() is run on the collection to sort the records, etc”.  With the SQL syntax I first must explain the mappings.

I have found myself rewriting old SQL syntax to C#/LINQ when I need to add new functionality.  As much as I use LINQ, I still have to look-up how to do certain operations when using the SQL-like syntax, but find it easy to write the same functional code with pure C#/LINQ extension calls.

I admire what the Microsoft .Net team did with LINQ, but I think I will be skipping the SQL syntax from now on.

Mix 08

January 16th, 2008

Mix is Microsoft’s conference on various web-centric technologies such as ASP.Net, AJAX and Silverlight. It is taking place March 5 – 7 in Las Vegas. MS just extended the deadline for the discounted registration until the end of January. I just signed up this weekend for the conference and am really looking forward to the event. I am particularly excited to see Silverlight 2.0. Microsoft will either be releasing GA code, or a late beta for Silverlight 2.0 at the conference, depending on who you believe. I encourage anyone that can get reservations to attend.