Page view counter

May 2009 - Posts

And to think that I found it on Bing

Ever since I started writing books I check Google (and for the past number of years it has been Google) for my name every now and then; both for the ego gratification and to see if there is misinformation or unhappy readers or other stories I should respond to.

Bing

Not that long ago, like a good corporate boy I would Live Search (boy that was hard to make into a verb) for my name. Eh.

Today I tried Bing.  In the first page of searching images, I found an interview I gave last year at TechEd Barcelona, but was never able to track down.

TechEdBarcelona

Wow am I glad I’ve shaved off the dopey facial hair.

I was pretty impressed when I clicked on Biography. Somehow Bing culled through my 3MM entries and found 5,100 that were specifically biographical. Cool.  Here’s the first line of 6 of the first 10 articles found,

Bio
The other 4 had to do with me but were not really bios. Still, not bad.

I’ll be keeping an eye on Bing. Meanwhile, get ready to Bing yourself, don't be shy.

You can find out more on Bing.com

(Yes, this sounded a lot like hype, but I really liked it. And it is nice to see something new in searching)

What’s New In Silverlight 3

I had the pleasure of presenting What’s New In Silverlight 3 both at TechEd this year and then again to the Redmond .NET Developer’s Association,

Redmond

I think the best way to make this material available is to post my slides here along with the source code, and then to point to videos and blog entries that cover this material (either existing or as I create it in coming weeks).

Please note that this presentation was given using Silverlight 3 Beta.

  • If you are reading this and we are still in Beta, then you can get what you need by clicking on the image below, but please read the caveats carefully about using the Beta version.

GetStartedSL3

  • If you are reading this after we’ve released the RTW version of Silverlight, be sure either to obtain the updated version of the code or to proceed with caution as there may be small differences from the beta.

The slides are here as a zip file.

The Demos and Supporting Videos

3dFlip

For the first demo, 3d flip,  I recommend reviewing Using 3d Transforms Part 1 and Part 2.

For the second demo “The Slider and the TextBlock” you’ll want to look at the video Element to Element Binding.

The third demo is on Easing, and we have a good video on that here, as well as a mini-tutorial here 

Demos #4 and #5 are on Pixel Shading and bitmaps. Best we can do for you for now is this excellent video on Pixel effects.

The Bounce demo shows how messaging works and is so much fun you won’t need much to go with it.  After that you come to the demo for “based-on” styles.

Based-On Styles

I don’t have an entry for that for you yet, but one is coming very soon. For now, take a look at the following Xaml which is the heart of the demo:

   1: <Style x:Key="StandardButton"
   2:        TargetType="Button">
   3:   <Setter Property="Width"
   4:           Value="100" />
   5:   <Setter Property="Height"
   6:           Value="35" />
   7:   <Setter Property="HorizontalAlignment"
   8:           Value="Left" />
   9:   <Setter Property="VerticalAlignment"
  10:           Value="Bottom" />
  11: </Style>

We start by defining the style for a standard button, setting a width, height and alignments.  This style can be assigned within the Xaml to any button as follows:

   1: <Button x:Name="Button1"
   2:         Content="I am a standard button"
   3:         Style="{StaticResource StandardButton}" />

Now we want to create a Big button. A big button style is just like a standard button, except that it is taller and wider. Its alignment is the same.

   1: <Style x:Key="BigButton"
   2:       BasedOn="{StaticResource StandardButton}"
   3:       TargetType="Button">
   4:    <Setter Property="Width"
   5:          Value="250" />
   6:    <Setter Property="Height"
   7:          Value="50" />
   8: </Style>

You can see that what is key in this definition is the new BasedOn property.  You assign this new style exactly as you would any other style…

   1: <Button x:Name="Button2"
   2:         Content="I'm a big button"
   3:         Style="{StaticResource BigButton}" />

You can base a style on a style that is based on another style. In our final example, we’ll create a BigFont button that builds on the BigButton but sets a larger font.

   1: <Style x:Key="BigFontButton"
   2:     TargetType="Button"
   3:     BasedOn="{StaticResource BigButton}">
   4:    <Setter Property="FontSize"
   5:        Value="24" />
   6: </Style>

In this case, BigFontButton is “inheriting” its width and height from BigButton and its alignment from StandardButton.  When we assign this to Button3…

   1: <Button x:Name="Button3"
   2:         Content="Style: Big Font"
   3:         Style="{StaticResource BigFontButton}" />

The results are just what we hope for:

BasedOnStyles

DataValidation

The DataValidation demo is, if I’m honest, my favorite. I particularly like that this works by combining two existing parts of the Silverlight framework:

  • The ability to have the data object test a value and throw an exception if the value is invalid, which is turned into an error by the binding object and returned to the UI
  • The Visual State Manager which makes responding to that error either trivial or fall within a well established pattern.

Another thing I like about this feature is that you can and will use this long before you have a deep understanding of how it works.  That can be frustrating when you want to modify the behavior, but all the pieces of the puzzle are available, and here’s a road map to getting there.

First, Visual State and Templates

I would approach this by temporarily setting aside the issue of error handling and start with visual states and templates.  We have a series of videos that walk  you through this, and I’d view them in this order:

If you are serious about obtaining a deep understanding of all this, I’d also read the following mini-tutorials

With all that done, error handling will be almost self-evident.  The data entry classes have a new Visual State Group: ValidationStates that consists of three possible states

  • Valid
  • InvalidUnfocused
  • InvalidFocused

The sequence of events is that when the user attempts to enter data into one of the data entry objects (e.g., a TextBox) that data is transmitted to the DataBinding engine which asks the data object to which the TextBox is bound if the data is valid.

In the demo, we create a Book as a data object, and the book has an ISBN field.  We bind a TextBox to the ISBN field and when the user enters the ISBN the DataBinding object asks the book instance if the ISBN is valid.  The Book tests for three conditions:

  1. The data must be 10 characters long or it throws an exception with the exception message “Must be 10 characters long”
  2. The data must consist only of the numerals 0-9 or the letter X or it throws an exception with the exception message “must consist only of the numerals 0-9 or the letter X”
  3. The last character must match the checksum of the first 9 digits (the algorithm is described in Wikipedia) or it throws an exception with the exception message “checksum not valid.”

If you have set your flags properly (to be described in a minitutorial on data validation) the exception is turned into a command on the UI to change the visual state from Valid to either InvalidUnfocused or InvalidFocused.  What happens then is entirely up to whomever created the behavior for those visual states.

Rather than leaving you to your own devices, the controls team has provided default Visual State behavior for the following controls:

  • TextBox
  • CheckBox
  • RadioButton
  • ListBox
  • ComboBox

and in the next (post-beta version) PasswordBox

That behavior is to turn the control red, and when you click back in, to display the message from the exception,

InvalidChecksum

 

You are of course free to change all of this by templating this control just as you would any other (which is why you invested all that time reading about templating!)

Navigation

The final demo doesn’t exist. I just open up Visual Studio and create a new project clicking on Silverlight Navigation Application as shown in this cropped image,

NewNavProject

Visual Studio creates the infrastructure for you, opening with four Xaml files: MainPage.xaml and in the Views folder, AboutPage.xaml, ErrorWindow.xaml and HomePage.xaml.  Running the application (without touching it in any way) gives you a multi-page application ready to be customized to your needs.

NavigationWindow

More details to come on Navigation and especially on Validation. 

On The Bleeding Edge: Where All The Fun Is.


















Tim Heuer did a brilliant job in
his recent blog post sorting
through and summing up some of the confusion that has
arisen out of the current unusual circumstances of Silverlight,
Blend and Visual Studio all having two versions available at the same time: a release version and a pre-release version.

Rather than replicating his work, let me point you to his
post and also provide a slightly different perspective of life on the bleeding edge… 

 


Silverlight, Blend, Visual Studio, Oh My.

SilverlightLogo Silverlight 2 is a released development product available here 

Silverlight 3 is a beta product (with no commercial go live license) that is scheduled to go live this summer. It is available here.

Expression Blend 2 is the current commercial version of Expression Blend, available with full support (and on a trial basis if you like) here.  This supports Silverlight 2.

Blend 3 is in Preview mode and targets Silverlight 3, it is available on a trial basis here. To target Silverlight 2 you will want Blend 2 SP1.

VS2010 Visual Studio 2008 SP1 is the current and fully supported edition and it comes in many flavors: Standard, Professional, and Team System

Visual Studio 2010 Beta is ready for testing.

Windows Windows Vista is our current released operating system for individual computers, available here

Windows 7 Release Candidate is here and available for you to test

The Bottom Line

There are numerous mix and match variations, but why make yourself crazy? 

  • To target Silverlight 2, install Silverlight 2, Blend 2 and either VS 2008


  • To Target Silverlight 3:
    • Install Silverlight 3, Blend 3 and VS 2008 (Sp1) or
    • Install Silverlight 3, Blend 3 and VS 2010

NB: If you choose Visual Studio 2010 you will not be able to use the RIA Services at this time.

You can choose other combinations (e.g., Silverlight 2, Blend 2 and VS 2010, but unless you have good reason to, I don’t see the point. If you want the exhaustive list, however, see Tim’s post.

Please note that any time you are installing a Beta product you are on the bleeding edge and you must be prepared for less reliability than with a released product. Further, it is my personal belief that if you install a pre-release product you must also be prepared to repave your machine when you install the next version. It may not be needed, but being ready for it is a prudent precaution.

Pioneers take Risks But Achieve Great Things

Using pre-release software can certainly create headaches: when you run into a problem you must ask yourself: Is it Blend?  Visual Studio? Win7? Silverlight or me?   Aiiii!   But it is also the very best way to keep ahead of the learning curve, and each of these products, though pre-release is surprisingly stabile and each is well supported on their respective Microsoft sites:

My Working Environment on the Bleeding Edge

As a personal choice, I am currently keeping these working environments: 

Silverlight 2, Blend 2, Visual Studio 2008, Vista.

Silverlight 3, Blend 3, Visual Studio 2008, Windows 7.

Silverlight 3, Blend 3, Visual Studio 2010, Windows 7.

I do most of my work on the last of these, and so far it has been a gas.

Virtual Machines

As Tim correctly points out, one very powerful option when working with pre-release software is to use virtual machines – easily reset and recreated, but typically you pay a bit of a performance penalty.

I’m committed to Two Tool Development

I confess. After years of developing with separate debuggers, editors and compilers it was a wondrous thing to have an Integrated development environment in which all three and more were combined. I love Visual Studio.  And for the past year or so I imagined that Blend, while wonderful, was a temporary solution until Dev10 (shorthand for Visual Studio 2010) was ready.

Bzzzz. No! But thanks for playing!

After reviewing Dev10 (which is wonderful) and talking with the team, I’m now convinced that while many developers will do all their development in Visual Studio, serious (and certainly advanced) Silverlight programmers will in fact opt to work with two tools indefinitely.  It isn’t just that Blend is better suite for some types of work and VS for others; it is that there are real limitations (did I say that?); places where they do not overlap, and won’t any time soon.

For example, and taking this from the perspective of a developer; I’m thrilled that I can now create rows and columns in my grid in VS and that I can drag and drop controls on the design surface. That greatly simplifies the design process and while Blend may have some advantage there, only time will tell whether it is worth switching back and forth to accomplish these goals.

On the other hand, if I want to add animation I have two realistic choices: hand code it in Xaml in Visual Studio (always fun, might be dangerous, maybe tomorrow) or open Blend (where it just keeps getting easier).

Similarly, if I want to template a control (which, interestingly, I want to do more and more, especially as I work more with Data Validation), then once more Blend is not only the tool of choice, it is my only viable alternative: Visual Studio just isn’t designed to make that easy.

Coding In Blend

“Well,” I hear you say, “why go to VS at all? You can code right in Blend, with Intellisense and etc.”  Yah, you can. But as my buddy Dave Platt says (I’m cleaning this up) you can have an appendectomy through your mouth; it just takes longer and hurts more.  The ability to do bits of coding in Blend is a great convenience, but it wasn’t designed to be a programmer’s environment and there is no comparison between the level of support if offers and the level of support offered in Visual Studio. Not even close.  (OK, I owe you a list of specifics, but for now let’s take it as given).

That’s Not A Bug It’s A Feature

It is tempting to be somewhat defensive about this; almost as if this were a step backwards. But on reflection, I think it is actually a great leap forwards.  Rather than trying to make VS into an almost adequate designer, the folks who own Visual Studio decided to create a great developer tool. When you need to go beyond that, to take on relatively advanced design problems (such as managing view state and the associated story boards) it makes sense to use a tool that does that for a living.

And since the two tools work on the same project at the same time, with no need to “import” or “export” cycling between them is (nearly) painless.

Caveat: You Can’t Get There From Here (Yet)

While I strongly encourage you to create a machine with VS2010 (on Win7 if you can!) and with Blend 3, please note that as of this writing you can not open a Silverlight 3 project written for .NET 4 with the Blend 3 currently available (remember, we released Blend 3 back in March, years ago in web time).  To overcome this horrific limitation <smile>, you need only create a .NET 3.5 application. To do so, create a new solution, click on C# (or VB or Silverlight) and then drop down the framework and select ..Net Framework 3.5 as shown here,

Framework35

You’re back in business, though you will not for now be able to take advantage of the new .NET 4.0 framework features.

I will be returning to this theme of two-tools quite a bit, but wanted to open the door for discussion right away as I explore the myriad features in Silverlight 3.

Posted by jesseliberty | 3 comment(s)
Filed under: ,

Just Built My First SL3 / Dev 10 App

As you no doubt know we released Beta 1 of Visual Studio 2010 today   (the usual caution applies: I would advise only installing this on a machine you are prepared to repave!).  [Update - the Landing Page for all things related to VS 2010 Beta1 is here. ]

I installed it and Silverlight 3 on my laptop running Windows 7 (yowza!) and then fired it up and created an incredibly simple app as follows:

NewVS10Project

In the new project dialog shown cropped here, I chose to build to the latest version of the .NET Framework (marked Red-circle 1), then chose C# as the language I’d build in (2); narrowed the types of projects by choosing Silverlight (3) and finally chose a Silverlight application (4). 

At the bottom (not shown) I picked the directory and named the project Element Binding.

NewVS10ProjectDialog

 

 

As in previous versions, I’m prompted to choose either a web-based or a simple test application (I chose the latter) but I then had to choose to build to Silverlight 3 rather than 2).

VS10WhichVersion

Visual Studio opens on a new Silverlight 3 application and here is where everything changes.  No longer does the design surface say preview; now it says “Design” and means every syllable.  I created columns and rows much as I would in Blend (by clicking in the margins of the grid:

VS10CreatingColumns

I then dragged a slider into the first column and a text block into the second. WooHoo!

VS10DragControls

I then set the values for the slider to be 0 to 100 and the small increment to be 1 and the large increment to be 100. Finally, I set the properties for the TextBlock, the most important of which being its Text; which I set by clicking on the symbol next to Text (shown circled below) to choose Apply DataBinding

VS10ApplyDataBinding

The Source Dialog opens, and choosing ElementName brings up a list of the elements to which you can bind. Clicking on Slider1 (the slider control) caused the instruction “Use the Path pane to choose propoerties for the Source“ to appear as shown circled in the figure below,

VS10BindingToAnElement

Clicking on the Path pane opened a list of all of Slider’s properties. The property I wanted to bind to was Value, and I clicked on that. I had the option of choosing additional properties or options, but that was all I needed and in fact when I closed the dialog the value of the slider was immediately reflected in the text block in the designer. A quick test run of the application demonstrated that the TextBlock was now bound to the value of the slider, with no need for an event or an intervening data object! 

Sweet.

The application runs as intended,

VS10BoundElement

and here is the complete source, all of which is Xaml:

   1: <UserControl x:Class="ElementBinding.Page"
   2:    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:    mc:Ignorable="d"
   7:    d:DesignHeight="100"
   8:    d:DesignWidth="200">
   9:    <Grid x:Name="LayoutRoot"
  10:          Background="White"
  11:          Height="62">
  12:       <Grid.RowDefinitions>
  13:          <RowDefinition Height="3*" />
  14:          <RowDefinition Height="1*" />
  15:       </Grid.RowDefinitions>
  16:       <Grid.ColumnDefinitions>
  17:          <ColumnDefinition Width="200*" />
  18:          <ColumnDefinition Width="200*" />
  19:       </Grid.ColumnDefinitions>
  20:       <Slider Height="22"
  21:               Margin="0,20,0,0"
  22:               Name="slider1"
  23:               VerticalAlignment="Top"
  24:               Maximum="100"
  25:               SmallChange="1"
  26:               Value="50"
  27:               LargeChange="10" />
  28:       <TextBlock Grid.Column="1"
  29:                  Height="21"
  30:                  HorizontalAlignment="Left"
  31:                  Margin="5,0,0,0"
  32:                  Name="textBlock1"
  33:                  Text="{Binding ElementName=slider1, Path=Value}"
  34:                  VerticalAlignment="Center"
  35:                  Width="95"
  36:                  FontFamily="Verdana"
  37:                  FontSize="18" />
  38:    </Grid>
  39: </UserControl>

 

The key new Silverlight 3 feature is found on line 53 where we bind directly to the Slider.

This is just too much fun.

ecq100

Example-Code Quality, GuaranteedThis code was compiled with Silverlight 3 (Beta) using Visual Studio 10 (Beta) on Windows 7 (RC).  For more on this guarantee, please see this page.

Time Flys Like An Arrow; Fruit Flies Like A Banana

We recently released my video on the new Animation Transition Control and in looking it over I noticed that I promised to follow up on the definition of a Date/Time “Tick”

Gregorian

A quick look at Wikipedia reveals any number of problems with attempting to count the number of nanoseconds from the date 1/1/01. Without diving too deep into this bit of trivia, I will note that the Gregorian calendar used in civil affairs (in which today is May 8, 2009 AD or CE) attempted to fix errors in the Julian calendar but missed the mark, and created problems of its own.  These were “corrected” a number of times, introducing new problems making it nearly impossible to historically find your way backwards with any exactitude through the middle ages (10 days were dropped from the calendar all in one go in some countries by Papal Bull, but not in other countries, and some parts of Europe did not adopt some aspects of the Gregorian calendar for another two hundred years, with the Swedish introducing February 30 (30!) in 1712). Greece didn’t make the switch until 1918, fully three centuries after Pope Gregory’s proclamation.

Complicating things further is the introduction of leap seconds for the past 40 years, to account for the accumulation of irregularities in the Earth’s rotation.

Rata Die

A little further research, however, puts this all to rest, as it turns out that the Rata Die (RD) system assigns numbers to calendar days independent of calendars, and is almost certainly what Microsoft uses for Ticks as RD counts forward from 1 at midnight on January 1, year 1  in the Proleptic Gregorain calendar (that is, the Gregorian calendar you produce by starting today and carrying the Gregorian calendar backwards in time past the years of its introduction). 

Wasn’t that fun?

Posted by jesseliberty | with no comments
Filed under: ,

This is a note that I’m Cindy To Buy Chocolate

Newton Remember the Newton?  Such a great idea… almost. Long before the iPhone, Apple released the Newton, promising that you could write in long hand and the Newton would turn your scrawl into printed words. Unfortunately,  not always the words you wrote. 

There was a wonderful posting on UseNet called “If Lincoln had a Newton” – a search turned up what I hope is a faithful copy which includes this excerpt:  “Newer are unseated in a greased civil wear, toasting wealthier that notion or andy otter nodding so conceptive and so detoxicated can loading ensure….”

Gary Trudeau ran a series of now famous strips about Doonesbury’s frustrated but tenacious loyalty to the almost-perfect technology.

NewtonDoonesbury
Doonesbury Aug. 27 1993

 

Yesterday: handwriting. Today: Voice

Today’s Newton is voice transcription services that do for dictation what the Newton did for handwriting. I’ve subscribed to Jott because it answers a real need: the ability to send myself a reminder (with an alarm at a specific time) when I think of something (or my wife tells me something) I need to remember, but I’m driving. My choice without Jott was between 

  • waiting until I could safely pull over and enter it into my iPhone by which time I would certainly have forgotten what I wanted to write down, not to mention where I was driving to or…
  • crashing and being killed in which case there is would be no point in remembering

With Jott I can just press 1 button, Jott answers and says “Jott what?”  I say “Reminder”, it beeps, I dictate, and that’s it. I’m done. No fuss, and at the designated time, it rings my phone and reminds me. Very cool.

Unfortunately, Jott offers a great deal more. I can add entries to my todo list or to my calendar. Worst of all,  I can send email.  And this is where things get ugly.  I sent my wife a test message. I dictated “Hi. This is a note that I’m sending to you by Jott it.”  Here’s the verification message:

image

You can almost see how it got from one to the other. It’s actually not that bad.  I’ve seen worse. On the same day actually.

Google bought my telephone service, Grand Central, which was and is a wonderful offering that rings all my phones when I get a call and lets me answer wherever I am.  Originally, if it took a message it used to send me an email with the phone number of the person who called. Now it transcribes their message and sends an SMS. Cool. Kinda. Yesterday I IM’d my friend Alex asking him if he had any graphics left over from our nascent company “Silverlight Consulting” AIM forwarded my message to his phone. He called back and left this message on Grand Central (now called Google Voice):  “Hey. You’re looking for Silverlight Consulting stuff, I probably have that. I’ll call you tonight. Alright. Ciao.” 

I received this:

googleVoice

Just Give Me A Hint

The technology is exciting, and I’m a cutting edge kind of guy… I’m willing to take a garbled message and reverse engineer what they must have said, but I do need a hint.

The trick of course is to pick and choose your usage, not to expect too much and to enjoy the humor in the situation. But caveat emptor; don’t leave a life and death message through telephone transcription just yet.

Validation. Hey! You’re Done!

 

Towards the end of my “What’s New In Silverlight 3” presentation for Tech Ed,  I discuss the (much anticipated) enhanced Data Validation in SL3.  Now, anyone who has been around the block a few times knows that there are a lot of different ways to handle data validation, and that each framework offers a different approach (not that long ago the approach was summed up as “hey, you’re a programmer, you want data validation, write some.”)

error1

error3

Plus Ca Change, plus c’est la meme chose

In October I wrote a blog entry about Data Validation in Silverlight 2.  It is interesting to look back at it now and realize that what has changed is not the use of the binding engine, setting the mode to two way, or even setting NotifyValidationError=true andValidationExceptions=true. All that was true back in October.

What has changed is that back in October, we wrote the code to manage everything about the validation – not only the business logic (which is to be expected and desired) but the entire UI for managing the error notification:


olderrorcode

From Hand Coded To Toolable Visual State


ValidationStates

The key innovation in Silverlight 3 is to tie error handling into the Visual State Management of the control. We are used to the fact that all the standard controls have two state groups: the CommonStates and the FocusStates. To these we now add three ValidationStates,

What is more, a number of input controls (TextBox, CheckBox, RadioButton, ListBox, ComboBox and soon PasswordBox) already have default storyboards for transitioning into these states (as you’ll see in just a moment

This means that right out of the box these controls know how to respond to invalid data, where the validity is determined by the object to which they are bound. Sweet.

Writing The Code

Let’s start simple, using the out-of-the-box capabilities, and then in a subsequent post I’ll look at how a little templating can give you much finer control over the interaction with the user.

To make this work you need the following:

  • A form with a way for the user to provide input (we’ll use a text box)
  • A data object to bind the input control  to
  • A user to enter incorrect data

Here is a picture of the form, displaying the error message that is caused by entering an invalid ISBN (one that has the right number of digits but where the checksum does not compute correctly):

checksumInvalid

We’ll support two other errors as well (not the right number of digits, and invalid values)

InvalidLength

invalidValues

Start With The Data

What I like most about this model is you start with the data, not the UI. You begin by designing your data object, and what validity checks you want.  I’ll post the code right after Tech-Ed, but I start with a Book class that implements INotifyPropertyChanged in the normal way. Then I added to the property for the ISBN my validation checking, throwing an exception if it is invalid in any way. The text I put in the exception is the text that shows up in the error message.  Here’s the ISBN10 property:

public string ISBN10
{
get
{
return isbn10;
}
set
{
if ( value.Length != 10 )
{
throw new ArgumentException( "Must be exactly 10 integers long" );
}

char[] isbnAsArray = value.ToCharArray();

foreach ( char c in isbnAsArray )
{
if ( ( !Char.IsNumber( c ) ) && c.ToString().ToUpper() != "X" )
{
throw new ArgumentException( "Must be numbers or letter X" );
}
}

int runningTotal = 0;
for ( int i = 0; i < 9; i++ )
{
int val = ( Convert.ToInt32( isbnAsArrayIdea.ToString() ) * ( 10 - i ) );
runningTotal += val;
}
int mod = runningTotal % 11;
int checkSum = 11 - mod;

int isbnCheckSum = -1;
if ( isbnAsArray[9].ToString().ToUpper() == "X" )
isbnCheckSum = 10;
else
isbnCheckSum = Convert.ToInt32( isbnAsArray[9].ToString() );

if ( isbnCheckSum != checkSum )
{
throw new ArgumentException( "Checksum is invalid!" );
}

isbn10 = value;
NotifyPropertyChanged( "ISBN10" );

}
}

[ Checksum computation from Wikipedia. ]

From Data To DataBinding

Once you’ve created your data object, you can build the UI around it, and bind the display objects to the properties of the data object. I decided to create the page in Blend, making it absurdly easy to lay out the rows and columns and to define the style for the prompt and for the data entry text box.

BlendValidation

I could have assigned the visual state, etc. inside Blend, but since I wasn’t changing anything, but rather just using what is already provided I saved this and clicked on Edit In Visual Studio. I then added the binding for the Title and Author by hand,

<TextBox x:Name="Title"
Grid.Column="1"
Grid.Row="1"
Text="{Binding Title}"
Style='{StaticResource Input}' />
<TextBox x:Name="Author"
Grid.Column="1"
Grid.Row="2"
Text="{Binding Author}"
Style='{StaticResource Input}' />

And followed that by adding the binding for the ISBN which required just a couple extra properties, but, you’ll notice, the same properties discussed in the October article and shown above,

<TextBox x:Name="ISBN10"
Grid.Column="1"
Grid.Row="3"
Style='{StaticResource Input}'>
<TextBox.Text>
<Binding Mode="TwoWay"
Path="ISBN10"
NotifyOnValidationError="True"
ValidatesOnExceptions="True" />
</TextBox.Text>
</TextBox>

That’s it! the rest just works.  No, really.

One Little Extra

Alright, if you want to get fancy; the text box doesn’t update and check the validity of its contents until you tab out (how else can it know when you’re done?). Cribbing from Karen Corby’s presentation at Mix I added a button to attach the UpdateSource() method of BindingExpression onto, and while I was at it, being amazingly lazy, I added a button that puts in the real ISBN for Death In Venice (one does get tired of typing the same thing while debugging!)

Here’s the Xaml,

<Button x:Name="FillButton"
Content="Fill Textbox With valid ISBN 10"
Width="200"
Height="25"
FontSize="14"
Grid.Column="0"
Grid.Row="4"
Margin="5"
HorizontalAlignment="Right" />

<Button x:Name="ValidateButton"
Content="Validate Now!"
Background="Green"
Width="120"
Height="25"
FontSize="14"
Grid.Column="1"
Grid.Row="4"
Margin="5"
HorizontalAlignment="Left" />

and here’s the code-behind for the buttons,

void ValidateButton_Click( object sender, RoutedEventArgs e )
{
// BindingExpression requires using System.Windows.Data
BindingExpression bindingExpression =
ISBN10.GetBindingExpression( TextBox.TextProperty );
bindingExpression.UpdateSource();
}

void FillButton_Click( object sender, RoutedEventArgs e )
{
ISBN10.Text = "0141181737";
}
womc900

This code was compiled with Silverlight 3 – Which is a beta product!  For more on this guarantee, please see this page.