Free WPF Training!

April 2nd, 2009

My retirement from WPF officially ended at 11:59 PM on April 1, 2009.  It’s good to be back!  As it turns out, I’m just not that good at golf and I don’t know what else a retired doctor does.  I better start working on my swing, I guess!

I am excited to see that Karl and Jaime have announced the dates and cities for their upcoming "WPF for LOB" training tour.  The training is FREE!  but you must register. 

Location

Dates

 Los Angeles, CA

 4/24 – 4/25

 London, UK

 5/15 – 5/16

 New York, NY

 5/29 – 5/30

 Phoenix, AZ

 6/5 – 6/6

 Chicago, IL

 6/12 – 6/13

[4/20/09 Updated the dates above to reflect the latest info from Jaime’s blog.]

Check out Jaime’s announcement for the full details and registration links.

Hanging up the Stethoscope

April 1st, 2009

There’s no easy way to break this news, so I’ll just say it… I’m moving on!

After 6+ great years working with this awesome platform, I’ve decided to pursue a new interest.  This new pursuit will leave me with little time to devote to WPF.  I know this news comes as a shock to many of you, but hopefully once you see my new interest, you will understand. 

Please know that I still have great fondness for the WPF platform.  My decision should not reflect negatively in any way on WPF!

Okay, if you must know what is pulling me away from WPF, here’s a sneak peak at my next big thing!

All my best!
Dr. WPF

Jaime's Mix09 Recap Series

March 30th, 2009

Jaime Rodriguez has just released a fantastic 3-part series summarizing the big things to directly or indirectly come out of Mix09.  I highly recommend it for anyone working within WPF and/or Silverlight:

It’s great to get a little insider insight into the thinking behind Microsoft’s ongoing client strategy.

Silverlight: How I Really Feel About the Iridescent Thong

March 21st, 2009

First, I have to give huge props to Microsoft for throwing an excellent party in Vegas this past week!  The week was definitely packed with excitement and backed by great content.  Be sure to check out the recorded sessions if you were not able to attend Mix09.

This post represents my response to this year’s big unverbalized question…

What about WPF?

Yes, this year’s conference felt like it was all about Silverlight 3.  I think Microsoft would readily acknowledge that this was by design (no pun intended).  And this was actually fine with me, since the Silverlight platform has made such great strides over the past couple of years.  It certainly deserves the attention it is now getting.

I have a reputation for making fun of Silverlight from time to time.  Truth be told, I bare no ill will toward Silverlight at all.  I’ve even delivered Silverlight training on several occasions.  I think of her as a kid sister to WPF (which plays the role of big sister, in case you were curious about either platform’s gender).  Privately I’m pulling for Silverlight to make good, but that doesn’t stop me from publicly taking shots at her whenever the opportunity arises.  It’s all in good fun… really!  ðŸ™‚

I’m not exactly sure what role I’d give myself in all of this.  Some might say that WPF and I are BFFs, but I’d argue against the latter F.  To me, "forever" is a word that has no place in technology.  When it comes to WPF, my devotion only goes as far as the platform presently supports.  I am her student; I am her practitioner; I am even her disciple; but make no mistake… if something better comes along, I will turn her out like a two-bit whor… rible analogy!  Let me change directions…

Based on what I see on the horizon right now, I think WPF and I still have a bright future together.  Silverlight gets more impressive with each release, but it has quite a ways to go before it reaches parity with WPF.  I just spent the better part of a conference watching web developers "ooh" and "ah" over features that I’ve been using in WPF for years now.  (Imagine how they’d feel if they had something as basic as a trigger!  See… there I go again…  I just can’t help myself. ;))

Additionally, I’m a platform guy.  So much of what I do now requires a full trust environment with access to platform APIs.  Until Silverlight breaks out of the sandbox and allows me to harness platform-specific features (which is not likely in the near-term, since it is so focused on cross-platform reach and a small footprint), I think WPF and I will stay pretty tight.

Why bring all this up now? 

I’ve received a number of… shall we say… "concerned" inquiries lately about the shrewdness of adopting WPF for new or future projects while Microsoft has such an obvious slant toward Silverlight. 

My honest recommendation to anyone deciding between WPF and Silverlight is unchanged over the last couple of years.  The platform has to be chosen based solely on the project requirements.  If Silverlight meets the requirements of your project and you need cross-platform reach, then you should definitely target Silverlight.  End of story.

On the other hand, if you’re developing a full trust, Windows application, you will likely be far more successful with the more mature (and in my humble opinion, more elegant) big sister, WPF.

Impending Doom

Some emails have expressed an explicit fear that WPF is about to be abandoned by Microsoft and then disappear completely.  Let me put my response to such concerns in terms that only a geek can truly appreciate… 

Don’t Panic!

To allay your fears, let me point you toward two very big buoys floating in the waters around Redmond: Expression Blend and Visual Studio 2010.  The user interfaces these products are actively being built in WPF.  Blend always has been a WPF application.  For information on the upcoming Visual Studio 2010 UI, check out Jason Zander’s blog.  Feel free to anchor yourselves to these buoys.  If these projects change direction, make sure you follow!  (Can you imagine a Visual Studio user interface written in Silverlight?  Even I think that would be awesome!)

I would also point out that many new features highlighted at Mix09 actually represent nice WPF advances too.  I know Silverlight received most of the glory, but new Blend 3 features like Sketch Flow, Behaviors, and the new Adobe importers are actually just as pertinent to WPF as they are to Silverlight.  And of course, there was the sneak peak at WPF 4.

The Big "If"

So what happens down the road "if" Silverlight does reach parity with WPF and it finally breaks out of the sandbox? 

Should that ever happen, my response to potentially losing WPF would basically be a shrug and a big, "So what?"  If Silverlight v.Next++ gives me everything I need for Windows client development and supports the same collaborative workflow as WPF, then why would I (or anyone) mourn the loss of WPF?  At that point, I’d be more concerned if WPF *was* still around.

Again, let me be clear…  I think this latter scenario is a big "If" and should things go in that direction, I don’t think we’re talking near-term.  Microsoft can move very fast when the correct motivations are in place, but even at full speed, I think this would be a multi-year scenario.

Again, my take is that nothing lasts forever in technology.  Both WPF and Silverlight will eventually be replaced by something bigger and better… or maybe smaller and better… who knows?  For now, I’m a WPF junkie and a Silverlight user.

Now the Important Stuff…

Here are the Sudoku puzzles I conquered on my return flight from Vegas: One, Two, and Three. (See JAGS 10K Instructions for mouse play.) 

Yep, three of them!  Usually, I only make it through a single puzzle, but I was unexpectedly bumped to first class on this flight where I basqued in the glory of geek icons such as Scorbs, The Gu, the WPF Wonder Man, and even Nate Dunlap!  Their collective auras must have increased my puzzle IQ.

Tips and Tricks: Making Value Converters More Accessible in Markup

March 17th, 2009

I recently had the pleasure of presenting some rather advanced WPF concepts (along with some cool tips and tricks) to a group of smart folks.  Unfortunately, I ran up against time constraints and was forced to drop the data binding portion of my talk.  I’m a little bummed about not being able to show one cool trick that I use a lot, so here it is…

Call me lazy (really, I’m okay with it), but I’ve never been wild about having to declare my value converters as resources before using them.  It’s just one extra step:

<Window.Resources>
  <src:MyConverter x:Key="MyConverter" />
</Window.Resources>

And then later the converter must be specified using a StaticResource reference, which incurs some overhead (albeit small overhead, in the grand scheme of things) for the resource resolution:

<TextBlock Text="{Binding SomePath, Converter={StaticResource MyConverter}}" />

I often choose to skip the middleman.  Instead of using the StaticResource markup extension to look up a converter, I simply derive my value converter, itself, from MarkupExtension.  Then I return an instance of it in the ProvideValue() override.

I have to assume there are plenty of others using this approach too.  (It’s clever, afterall, but that’s about the extent of the hyperbole I’d grant it.)  If you’re not one of them, I simply wanted to put it out there as a potential trick for your arsenal.

Below is a super simple example of a dummy converter (typically used to debug bindings) that does this:

public class DummyConverter : MarkupExtension, IValueConverter
{
    private static DummyConverter _converter = null;
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (_converter == null)
        {
            _converter = new DummyConverter();
        }
        return _converter;
    }
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        return value; // set breakpoint here to debug your binding
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        return value;
    }
    #endregion
}

The above class creates a singleton dummy converter that can be used across my app without any resource lookup.  The XAML usage is now simply this:

<TextBlock Text="{Binding SomePath, Converter={src:DummyConverter}}" />

This is much better, to my lazy way of thinking.

JAGS 10K, Platinum Edition

February 12th, 2009

There’s still time to vote in the Mix 10K Challenge

Voting closes on Monday, February 16, 2009.  If you haven’t yet voted, check it out.  You simply rate the entries on a scale of 1 to 5.  Feel free to start with my JAGS 10K entry (Just Another Game of Sudoku in 10K).  😀

A New Release of JAGS 10K is Now Available

On my recent return flight from San Antonio, I had the opportunity to tackle one of the toughest games of Sudoku yet.  Only 20 cells were given.  A typical "hard" puzzle gives you at least 25.

Naturally, I decided to attempt it within JAGS 10K (using the super secret method of loading a custom puzzle described in my previous post).  Afterall, every developer should eat his own dogfood!

This attempt revealed that the golden release of JAGS 10K is lacking in a very key feature.  Namely, there is no way to make visual cues within a cell.  Most Sudoku players rely on these marks when solving a puzzle on paper.  Without this ability on the computer, solving a tough puzzle is nearly impossible (unless you’re Dr. Spencer Reid from CBS’s Criminal Minds… yes, I’m a fan).

Clearly, I had some work to do!  As such, I took some time this past weekend to add the required new feature and I’m happy to say that the new release is now available for installation here.

Previous Features

All of the original features are still there.  You can play an auto-generated puzzle of a specific difficulty or you can load a puzzle from the web.

Mouse Play:  Some people commented on the lack of discoverability for mouse play.  Unfortunately, 10K does not afford you any room for including instructions within the app and the stock cursors just don’t do it for this particular user interaction.  So here’s the mouse play secret again… simply click on a cell and then drag down (or right) to increase the number and up (or left) to decrease it.  (Designers:  If it helps, I’ve been told by a few people that this is similar to how Blend’s property editor works for numerical properties.)

New Features

In JAGS 10K, Version 2.0, you can now hold down the Ctrl key to reveal visual cues that can then be toggled on or off, as seen here:

When you release the Ctrl key, you will see only the markers that are toggled on:

 

Now you can truly solve any level of puzzle! 

To make it even better, I added a more accessible way to specify a custom puzzle.  Now you can simply pass the gameboard as a URL parameter.  This allows you to easily share a puzzle with your friends.  In fact, if you’d like to take a crack at it, here is that tough puzzle from my return flight:

http://drwpf.com/Apps/JAGS/JAGS10K.application?000200000002930000005000670000000058070000020560000000014000900000076100000003000

Enjoy! It took me nearly an hour to solve!  Maybe you can beat me.

I also fixed a bug or two in the app and I added a minimize button (per Mladen’s suggestion in the comments for my official entry), so you can quickly hide the game if your boss walks in to your office! 😉

Code Size

So I’m sure you’re asking, "What did these enhancements do to the size of the code?"  As you might expect, it increased it quite a bit.  The size of the code actually went up by about 20 percent!

My first inclination was to simply release the updated version as "JAGS 12K".  But alas, if you can’t play by the rules, you shouldn’t play at all!  So I’ve spent the last several nights getting extremely creative in the code.  I’m happy to say that the code for this v.2 release is now once again 10K (exactly 10,240 bytes, to be precise).

Source Code

If you saw my original post, you know that it took a lot of work to get down to 10K in the first place.  Explaining my latest tricks would take too long, so I’ve decided to instead just post the code for anyone who is really that interested.  You can download the project hereCaution: Don’t expect it to be very legible!

JAGS 10K has been posted

February 5th, 2009

My aforementioned Mix10K entry has now been posted.  Please check it out, give it a rating, and let me know what you think.

I have just uploaded several new games, including some from The New York Times, The LA Times, and The Hindu (in honor of my original introduction to Sudoku).  I even included the puzzles from my recent flight to San Antonio (just because I could :D).

If you’re not into the syndicated games, you can also play auto-generated games at the difficulty level you select.

Enjoy your game!

Secret Bonus Feature for Hardcore Sudoku Players

I allow you to specify a gameboard on the command line.  This requires you to locate the executable file, jags.exe, in the click once application cache (C:\Users\[ProfileName]\AppData\Local\Apps\2.0\[obscure path]\jags.exe).  Simply pass an 81-character string of digits on the command line. Each 9-digit substring represents a row of the puzzle. Zeros (0s) represent empty cells.

If you actually use this feature, you may indeed have a problem.  Consider joining Sudokuholics Anonymous.  Maybe I’ll see you there!

Size Matters

January 31st, 2009

Ha! I did get a blog entry posted in January. (And I’m not dead, in case you were wondering… just swamped with work. Only a few weeks until my current project is complete and then I should have time to post some new stuff!)

Anyway, I thought I’d write a little blurb about my recent entry into the Mix 10K Smart Coding Challenge. I did not plan to participate in this contest because of other demands on my time. Then Wednesday night someone mentioned that there were only two days left. I took a quick peek at some of the existing entries and I suddenly got the urge to give it a shot. Not that I thought I could do better… (I know my limitations when it comes to design! ;)) Rather, it was the caliber of other participants that drew me in. Plus, the idea of squishing coolness into a mere 10K of code just seemed like fun. I just needed an idea!

That’s when I saw one of my favorite Christmas stocking stuffers sitting on the corner of my desk… Sit & Solve Sudoku. The shape of this little book says it all!

I love a good puzzle! I first discovered Sudoku a couple of years ago when spending a few weeks in India. Now it’s one of my favorite leisure activities when trapped on a plane.

Yes, I’m aware there are lots of online Sudoku games out there. But I’ll wager that very few, if any, are written using less than 10K of code! So there was my challenge. And I’m happy to say that I met that challenge.

You should be able to check out my entry, JAGS 10K, in the contest gallery shortly. I submitted it yesterday but it has yet to appear on the site.

I’ll add a link here when the app goes live. In the meantime, below is a sneak peak:

I probably won’t win any awards for this little game, but I’m pretty proud of it nonetheless! I had a blast packing it full of features and whittling it down to size.

Introduction to JAGS 10K

First, the name JAGS 10K stands for “Just Another Game of Sudoku (in 10K)”. It is quite possibly the smallest, fully functional version of Sudoku ever created! (hyperbole intended! :D)

Instructions

If you’ve never played Sudoku before, the rules are quite simple… Fill in the grid such that every row, column, and 3×3 box contains every digit from 1 to 9. That’s it!

Game Play

You can play JAGS 10K using the keyboard, the mouse, or both. For keyboard play, simply select a cell using the tab or arrow keys and press the desired number. Press 0 (zero) or Delete to clear a cell. For mouse play, simply click an empty cell and drag the mouse downward to cycle through the available digits. Release the mouse when you find the digit you desire.

The application will generate custom games for you, or it can obtain recently published games from the web. Just launch the app, choose your difficulty level, and enjoy!

Cutting it Down to Size

I thought it would be fun to share a few of the tricks I used to bring this application within the 10K limit. You can think of the remainder of this post as my tips for the next 10K challenge. 🙂

First, I should point out that JAGS 10K is written in WPF (duh!). But most of the tricks described here would work equally well in WPF or that other XAML-based platform. (You know what I’m talking about, right? That web platform. What was it called again? I’m sure you know what I mean, anyway… that technology whose logo looks like a big blue iridescent thong! Oh never mind.)

I should also point out that calling this contest a “smart” coding challenge is a bit of a misnomer. I would call it a “clever” coding challenge, at best. (But then they couldn’t play off the “art” in smart, so that wouldn’t fly.) In any event, making an application run in 10K or less involves the intentional implementation of some very poor coding practices! Using these tricks for a production application is not advisable.

First Things First… Make it Work

I began by simply writing the application the way I would any new WPF project. I always start with the view model and an extremely simple view to prove out the view model. This provides a very basic proof of concept app, without the eye candy (styling and visual appeal).

I was able to create a very simple Sudoku game in just a few short hours. I used fully descriptive variable names during this phase (since it’s rather important that one understand and easily follow the code they are creating). I also used a brute force algorithm for generating new game boards. I won’t bore you with the details, but I will readily admit that it is inelegant and architected purely to keep the code simple.

Downsizing via the Obvious Stuff

Once I had the game working the way I wanted, it was time to cut it down to size. At this point, it was about 60K. Clearly, when trying to get under 10 kilobytes, every byte counts! (Literally.) There are some very obvious things you can do: remove all white space, rename all variables using 1 character names, drop all the “private” qualifiers, group similar variables and declare them using a comma-delimited list, etc. After doing these things, I was down to about 20K.

Now for some of the less obvious tricks…

Use integers instead of enum values

The WPF and BlueThong platforms contain a lot of enums with long, descriptive value names. Typing out these names uses up precious bytes. In my code, I instead specified enum members via their explicit integral values, which are easily discovered using reflector.

For example, instead of using:

  ResizeMode=ResizeMode.CanResizeWithGrip;

You might use:

  ResizeMode=(ResizeMode)3;

Voila! You’ve just saved 15 bytes!

CAUTION: This is one of those shortcuts that you would never want to do in real code! If Microsoft decides to reorder enum values in a future update, the application will surely break.

Use a series of if statements instead of a switch statement

The following example combines the enum trick with the elimination of a switch statement to further reduce size (at the slight expense of performance). When processing keyboard input, each KeyDown event provides the key that was pressed using the System.Windows.Input.Key enum. Rather than writing typical code that looks like this:

  switch (e.Key)
  {
      case Key.Back:
      case Key.Delete:
          f();
          break;

     case Key.NumPad0:
     case Key.D0:
           b();
           break;
  }

I instead wrote code like this:

  int v=(int)e.Key;
  if(v==2||v==32)f();
  if(v==34||v==74)b();

Even in its most compact form, the switch statement above requires 94 bytes, whereas the less optimal series of if statements using known integral values only requires 56 bytes. An instant savings of almost 40 bytes!

Reuse Global Variables

If you find yourself declaring a lot of similar variables in different methods, consider just declaring the variable once in the global scope of your class and reusing it in those various methods.

Remember that code may be more compact than markup

Instead of this:

  <ComboBox Name="c">
    <s:String>Easy</s:String>
    <s:String>Medium</s:String>
    <s:String>Hard</s:String>
  </ComboBox>

You can do this:

  <ComboBox Name="c"/>

With this in the code behind:

  c.ItemsSource=new string[]{"Easy","Medium","Hard"}

Another 40-byte savings!

Instantiate variables using the var keyword

Since this contest targets .NET 3.5 and the current releases of the .NET languages, there are some additional cool tricks at our disposal. For example, instead of doing this:

  ListBoxItem x=new ListBoxItem();

You can do the following to save some bytes:

  var x=new ListBoxItem();

Use abbreviated property declarations

If you don’t need to access their private backing fields, declare properties using abbreviated notation:

  public string T{get;set;}

Leverage an existing framework class for INotifyPropertyChanged support

Remember, its size that matters… not efficiency. When I was looking for those last 100 bytes, I realized that a lot of space was wasted implementing the INotifyPropertyChanged interface on my view model class.

My original class began like this:

  public class P : INotifyPropertyChanged
  {
      public event PropertyChangedEventHandler PropertyChanged;
      void N(string n)
      {
          if (PropertyChanged != null)
              PropertyChanged(this, new PropertyChangedEventArgs(n));
      }

Clearly this contains long class names that are out of my control. Even with the white space removed, the above support for INotifyPropertyChanged requires a full 193 bytes.

Knowing that the framework contains several classes that already implement INotifyPropertyChanged, I set out with reflector to find one that could be leveraged for my needs. I decided GroupStyle was a good candidate, so I changed my class to derive from it, as shown here:

  public class P:GroupStyle
  {
      void N(string n){OnPropertyChanged(new PropertyChangedEventArgs(n));}

Using this simple trick, I now had full support for property change notifications for about half the asking price (96 bytes instead of 193). Tricky, eh?

Leverage Resources

Watch for lengthy elements that appear multiple times in your markup and surface those as resources. For example, if you notice that you are applying the same drop shadow effect in multiple locations, declare it as a resource and simply use a StaticResource reference to reuse it. (Okay, this is just good general advice for structuring resources, but it is even more important when you are up against a 10K size limit. :))

Make a few hard choices about Form vs. Function

Visual coolness costs big bytes! Markup-declared animations are very verbose. Styles are really lengthy because of all their Setters. The same is true for the Triggers collection on an element or within a style or template.

By the time I had developed the game engine and view model, I had already exhausted the majority of my 10K allotment. I then had to choose very carefully how I would design the actual user interface. I didn’t have room for gratuitous animations or other flashiness. In the end, I decided that my 10K app was more about function than form. (This decision may cost me in the voting, but I’m okay with that.) I was still able to pull off a nice look and feel (using a grand total of 10,195 bytes, or 9.96K) and I’m really happy with the overall product! In fact, I think I’ll bid you adieu now and go play another game of Sudoku!

WPF Disciples Gather at PDC08

November 1st, 2008

I’ve just returned from an excellent week at Microsoft’s Professional Developers Conference (PDC) in Los Angeles.  It was a great chance to learn about some exciting things coming to WPF in the future (and some available now).  And of course, there were many non-WPF things announced, if you’re into that sorta thing. 😉

Check out the online PDC session recordings for the goods.

I really enjoyed meeting several of the WPF Disciples face-to-face, some for the first time, at PDC08.  We had some good conversations which I’m sure will continue online, so keep your eyes on the disciples google group if you’re interested in such things.

I don’t typically comment on statements pertaining to my identity, but I feel the need to set the record straight on a few things that have shown up recently in the blogosphere.  For instance, my people would never subject Walt to a 17 question WPF quiz.  (My team can certainly ascertain a person’s WPF qualifications using 3 questions or less!)

In regards to Laurent’s comment, I must apologize for the misplaced probe! I assure you that was not at my behest. I actually had to dismiss that member of my security detail for subsequent inappropriate behavior. (Let’s just say that he’s a big fan of certain recently announced multi-touch features.)

And Josh, that is not kool-aid I’m drinking… That is the diluted blood of WinForms developers who have mistakenly questioned WPF’s readiness for LOB.

Finally, I would never describe life events in relationship to asparagus, as Nathan would have you believe. I don’t think that asparagus should ever be mentioned in polite conversation. (I just don’t trust a food that does funny things to your pee.)

As for the other details in those reports… they were pretty much spot on.

I’m already looking forward to the next gathering of disciples! 😀

Try Crack!

October 21st, 2008

No… I’m not recommending crack cocaine!  I’m talking about Crack.NET, the new lightweight .NET debugging tool from Josh Smith.  It’s better than cocaine and has fewer side effects!  (That’s pure conjecture.) 

I just gave it a whirl, and this is a great tool, especially for a v.1 release.  It’s super easy to use and has a very intuitive UI.

I can’t wait to see what we get in future versions of Crack.NET!  I’m voting for some WPF goodness like the tree explorer from Mole.  And hopefully we can get the ability to interactively change property values.  And I’d love to see some intellisense in the IronPython script editor. (I guess I may have to ask Josh if I can join the codeplex project. :D)