Page view counter

June 2009 - Posts

So Much Is Happening The Silence Is Deafening!

June has been a madhouse month;  I’ve been working 80 hour weeks as has just about everyone who has anything to do with Silverlight, and yet there has been very little noise.  It is, as they say, the quiet before the storm.

iStock_dawnXSmall

As you know, we can’t yet talk about the biggest developments,  but I can say that many of us are working on making sure that when Silverlight 3 ships the site is ready with videos and related material that is completely up to date. That means of course that existing videos must be checked for breaking changes, and new videos must be created to highlight the exciting new features in Silverlight 3 that have not yet been announced.  We expect to have a great deal ready on the first day, and to keep it coming over the first weeks.

Much more about that as soon as the cone of silence is lifted.

New Silverlight – New Projects

To coincide with the release of Silverlight 3, I’m starting two new projects that I believe will greatly enhance my ability to meet the needs of a very broad range of developers. 

One of the concerns voiced in the past year, for example, was that the videos and tutorials were fine as far as they went, but each stood in splendid isolation, with little connection to the reality of creating software. 

Yet, we also know that one of the great benefits of the How Do I video series is that a developer can watch any without having to watch them all. 

I have found what I hope will be a terrific way to provide the best of both: the open and documented  development of projects complex enough to touch on  nearly every aspect of Silverlight, and to raise many deeply related issues such as

  • Two Tools: Visual Studio and Expression Blend
  • managing data
  • web services
  • design
  • dealing with changing specs
  • patterns
  • code management
  • designers, developers, dezelopers and more
  • emerging best practices
  • real-world tradeoffs when resources are constrained
  • and dozens of other issues.

I’ve named the overarching project AgOpenSource -- an on-going development project that will be completely tracked,documented and explored within a wiki-document housed inside my blog.

AgOpenSource

AgOpenSource will consist of creating applications from initial brainstorming , through design, development, testing, delivery and what we are calling recycling.   Now, not every application will be developed fully and not every application will be a candidate for the entire process, but if we do in fact build something that works and if it has value for our site, recycling indicates that we would then use that application as part of silverlight.net.

The documentation for AgOpenSource explains that it will start out as a “Glass House” project in which the information flow will be pretty much one way. I’ll continue to create videos, mini-tutorials and so forth and I’ll also be building all the bits and pieces myself.

It is my goal, and I expect to achieve it quite quickly, to move AgOpenSource to CodePlex and to make it an Open Source project, as described in the documentation.  I believe that will greatly enhance every aspect of AgOpenSource (hence the name) and I very much look forward to that transition.

VideoWiki Reborn

The first application that we’ll tackle within AgOpenSource is the VideoWiki project that was conceived back in April. This project was discussed in a number of posts, but nowhere do I see a full “vision statement” of what it is. Clearly there is much brainstorming and “sketching” to be done.

A VideoWiki is best understood as a HyperVideo with interchangeable links. Briefly, and you can find much more detail in the VideoWiki page of the AgOpenSource documentation, a HyperVideo has links associated with various times, scenes or  events in the video.  When you follow the link you may be taken to additional information or even to another video.

With a VideoWiki, the set of links and where they take you are uncoupled from the video, and you may choose from a variety of links for any given video.  For example, imagine that when you choose our video on creating Out Of Browser applications in Silverlight 3, you are offered to watch it in our VideoWiki player. If you agree to do so, you are then asked which links you’d like:

  • Links targeted at programmers new to Silverlight
  • Links targeted at experienced programmers
  • A link set created by <famous author>
  • A link set for those who like lots of extra information
  • A link set for those who like extremely technical commentary

Once you make your choice, you load your video and your link set, and as you watch, links slowly appear in a window next to the video. If you click on one, the video pauses, and a new video opens with additional information.

The Better Videos Project

Starting the week of July 20, the previously announced Better-Videos project will begin to ramp up.  The effect, I believe will be more effective videos produced more quickly, but this is an experiment in the truest sense; no one knows what the outcome will be.

Business success team

 

 

 

Because the internal day-to-day progress of this effort is not directly related to Silverlight programming,  I’ve sequestered the blog entries  about the Better-Video project in the Video Bloglet that you can access from the sidebar on any page

SideBarBetterVids

 

From Twitter to Tutorials

Neither of these projects will slow down the other avenues for information and interaction. In fact, I expect to add more. For now, here is what I see as the pyramid of information flow.

Short Bursts – Twitter

Mini-Articles & Flashes – Quick Bits

Substantive Articles – This Blog

Diary of the BetterVideo Project – Video Bloglet

The AgOpenSource Project – the AgOpenSource Wiki

Deep Dives Into Silverlight – Mini-Tutorials and Videos

Extended Analysis of Silverlight Programming – Full Tutorials

Social Networking? Facebook, LinkedIn, My Books & Photos

Timing

Timing is everything… and while we’ve not announced the release schedule for Silverlight 3, I can say that  I expect to be finished with my sequestered work before I come back from vacation (mid-July). At that point I will pour myself into AgOpenSource and my other projects, keeping ahead of the curve and responding to the three drastically different needs of our community:

  • Providing an On-Ramp for those who are new to Silverlight
  • Meeting the needs of Intermediate Silverlight Programmers
  • Providing raw meat for serious geeks ready to get off the carousel.
My single focus, however, remains the same: working Silverlight programmers. 

Right now, it is the silence before the storm, but by the end of July, the signal : noise ratio should approach 1.

Organizational Chaos Followup

About a month ago I wrote about getting organized.  Since it is Sunday and I’m saving my big announcement blog entry for tomorrow morning <smile>, I thought I’d take a moment for a not-so-quick follow up.   

Two Philosophies Lead To A Unified Approach

Some years back I found myself with the strong conviction that what worked (for me) was this: “Don’t organize on the way in, search on the way out.”

Every time I forget this premise, and fall back into the habit of creating dozens of small categories in which to stash things away, I end up with lots of mis-filed papers and socks all over the floor.

[By the way, I have no idea if that was an original insight, or one that I swiped from Ed Belove, probably when he described Lotus Agenda. (So many of the good ideas I’ve heard over the past couple decades were actually Ed’s.)

Since I last wrote, I discovered what is probably the only popular self-help book I fpimd worth the cover price (though I still think it could have been edited down to a white paper):  Getting Things Done by David Allen.  Of course I’m not the first to discover GTD (as it is known); the book is a massive best seller (which I admit is often a bad sign).

More related than might appear at first, the essential message of GTD , at least as filtered through my brain, is:  “The more you keep in your head the less you can think about what you need to do so get absolutely everything you have to do or remember out of your head. The only way you can do that is if you have a system you trust 100%.  You must trust that the system won’t lose anything, and you must trust that the information will be there (proactively in my case) when you need it.  That is to say, you have to trust that the information will be stored more reliably and retrieved more reliably in the system than it would be in your head.

This apparently is a hurdle for a lot of folks, but I have absolutely no problem believing that a well designed system, properly backed up can do that. I’m reasonably convinced that silicon is faster and more reliable than meat.

Once I dump all my tasks, trivia, notes, things to remember and things I have to do but not yet into a sufficiently reliable system, I’m freed up to do what meat does much better than silicon: set priorities and make judgments.

Assembling the Right System

The time for writing my own system has passed. There are enough pieces out there that it is just a question of finding them and plugging them together. That took a little doing (and this real intention of this note is to save you the work of recreating that experience!)

For a while,  every “solution” created more problems than it solved.  But with a bit of refinement and a willingness to spend more money on applets than one would think possible, I believe I have found solutions that meet the specifications: they allow me to keep virtually nothing in my head that isn’t relevant to something immediately actionable, yet with total confidence that what I need will be immediately retrievable when needed. Even better, the system will alert me when that time arrives, and since I’m notoriously unaware of time passing that is a very good thing indeed (I asked my wife if it was lunch time yet, at 11pm just last week). 

Stringent Requirements:

For me to turn over so much responsibility to any system, I must have an enormously high level of confidence, and thus the system must meet the following outrageous set of requirements.

Information: Be able to save any bit of information that I receive or stumble upon in email, on the web, in conversation, in IM, on the phone, while driving, in short: any where at any time,  and store it 100% reliably and be able to retrieve it no mater where I am, with at least 95% fidelity,  in less than 3 seconds.

Responsibilities: Capture every task
, personal and work, instantly and then let me forget them until it is possible to take an action, and then alert me immediately that an action is both possible and necessary.  Allow me to set priorities and to aggregate tasks into projects, and to add these tasks from anywhere at any time and to be alerted to and to retrieve them no matter where I am.

Email: Manage the 3,000 email messages I get every day so that I spend no more than 20-30 minutes a day reading my email,  but see everything important and never miss a critical email and so that I can retrieve any email I need within 3 seconds.

I could certainly have treated E-Mail as just more Information but it was much more efficient to treat it separately.

 

Information

I have to start by saying that I’ve built and bought at least a dozen systems that tried to meet the Information requirement. I believe it took the perfect storm of the Web, and massive advances in mobile phone technology to finally make this all work.  My solution here is centered around a single application: Evernote. The next image is Evernote running on Windows. I tend to throw just about every note into a single folder (cleverly named notes).  I make an exception for a few very obvious specialty notes such as business cards, passwords and my favorite: short term memory, the notebook in which I record my hotel room, where I left my car, etc.

EverNoteWindows

I can retrieve this information (or enter new notes) instantly on the Web,

EverNoteFireFox

or, even better, right on my phone:

ever

EverNote provides a clipping application that allows me to grab any highlighted text anywhere and just add it, or drag and drop into evernote, but my favorite feature is that I can take a picture and Evernote indexes the words in the picture, which I can then search for.  Hmmm…. I know we stopped at a good place to eat in Brewster on the cape; didn’t I take a shot of it for Yelp? Let me search…

brewster coffee

In less than a second it finds my picture and while the red arrow is mine the highlighting is provided by Evernote.  Very nice.

Spec:

image Be able to save any bit of information that I receive or stumble upon in email, on the web, in conversation, in IM, on the phone, while driving, in short: any where at any time,

image store it 100% reliably

image be able to retrieve it no mater where I am,  

image in less than 3 seconds.

[I’m going to table the issue of adding notes from the car for the moment, but see my discussion of Jott below)

Responsibilities

This is the hard one. I recently tweeted that working for Microsoft is like learning to juggle a dozen razor sharp plates a dozen razor sharp plates, while riding a unicycle on an escalator”

I’m told that many people feel that their memory leaks a bit, mine seems to leak a bit more than usual.

 

Young man kayaking down waterfall

Keeping track of my myriad projects, deadlines and responsibilities is critical to meeting the expectations of my bosses, peers, clients (that would be you) and myself. But I’m happy to say that David Allen says that trying is a losing strategy. Once again, the right answer is to turn it over to a system you trust. So I set off to find a 100% reliable system. 

I’ll spare you the details; the solution I found uses a back end web-based service with a phone-based front end, augmented by a call-in transcription service.

The backbone; the engine that makes it go and makes it available from everywhere at all times, is the unfortunately named Toodledo. The Toodledo interface is not simple, but it is powerful and it supports everything I need and then some. In fact, I switched from Remmeber the Milk (which I very much liked) to Toodledo because the latter was a much better fit with GTD and with the approach I as formulating.

 

Toodledo

Toodledo has three key features:

  1. It understands projects and sub-projects
  2. It works and plays well with the ToDo application that I use on my phone
  3. It is more than happy to sync with and to notify you of upcoming events by SMS, its own iPhone app, email, fireFox, twitter, Google, iCal, netVibes, pageFlakes, rss, jott, tSheets, outlook, VistaGadgets or Android. Pretty good

 

Toodledo is almost enough, but I need something much more immediate. To accomplish that, I added to vital pieces of software. First: ToDo:

ToDo

 

Appigo’s ToDo is a wonderful iPhone application for ToDo lists and project management, and is especially rewarding if you follow the GTD method as it understands projects, sub-projects, priorites, and most important Context (where you must be to act on a problem – no point seeing that you need to update the blog if you’re not near a computer.

I take it back, most important is that if you assign a due date and time ToDo will notify you. My one feature request would be to add a reminder date/time that is not the same as the Due date/time, but that is just a quibble.

 

The same set of tasks seen on the ToodleDo, looks like this on ToDo

 

 ToDo-Iphone

Almost There, but What About Ideas and Tasks that come to you on the highway?

The one missing piece in all of this is the requirement that I  be able to capture data and tasks any time, any where.  For a long time, it went like this: someone would ask me to do something (during a call) or I’d think of something important and then I’d face an interesting dilemma: which was the better choice:

  1. Wait until I could get off the highway to write it into my software by which time I was certain to have forgotten at least one important detail if not the entire reason I’d gotten off the highway in the first place

iStock_ Shrugging Man Medium

The second choice is to try to enter the information into my phone while driving 65 miles per hour among Massachusetts drivers

 

iStock_SadGirlverySmall

The answer is Jott. . Jott is a dictation service that lets you call in (or send a message from their phone app or their desktop app).They then transcribe your message and send it to whomever you like, including Evernote or Toodledo. Tweter, Outlook or any of your contacts.

 

jott

There are limitations to Jott’s voice recognition (see this article) but all in all it is just great. I can say “Jott ToDo” and add to my todo list while driving, such as “Jott Todo, pay speeding ticket”

GTD Bliss

Together, ToDo, Toodledo and Jott make a system that completely meets the GTD requirement: I can put every task, big or small, into the system with 100% assurance that I won’t lose it, miss it or have to think about it until it is time to think about it.

Spec:

image Capture every task, personal and work, instantly

image let me forget them until it is possible to take an action

image alert me immediately when  an action is both possible and necessary 

image Allow me to set priorities

image and to aggregate tasks into projects,

image and to add these tasks from anywhere at any time

image and to be alerted to and to retrieve them no matter where I am.

 

 

Email

I get about 3,000 emails a day and that is enough to treat Email separately.  Just a little analysis shows that my email breaks down (roughly) as follows:

  • About 2/3 comes from valuable lists but is not directed to me and is not immediately actionable
  • About 80% of what is left have me in the To or CC list but are not really to me specifically. I need to read them but most are FYI and while important to someone are not critical to me
  • We’re now down to 20% of 1/3 or a select 200 of the 3,000 daily messages. These 200 look important but only 1 in 10 really are. But those 20 message  must not be missed!
On any given day the proportions will change, unpredictably, but I strongly suspect that overall there is a normal distribution,  and further, what I’ve described is well within one standard deviation. What’s more, I’m wiling to bet, based solely on experience that this describes the contents of most corporate email inboxes.

 

The Best Laid Plans of Mice and Men

You may remember that my first approach was to have just 5 mailboxes:

  • Inbox
  • Act  (take action on this email)
  • Waiting  (pending someone else’s action)
  • Reference  (hold for future blos or videos)
  • Archive (can’t do anything with this now, hold on to it)

This lasted less than a fortnight. . There was just too much email to sustain it. 

I then created “rules” in Outlook to separate out the newsgroup emails and other chaff that I knew I could defer.  Worked fine until I found I had missed some pretty important emails. 

I’ll save you all the interim steps, and skip to the solution that is now working quite well.

Email Working…

Step 1, I created a small but vital second contacts list called VIP.  In it, I put the v-cards for anyone who I work for, work with or who is associated with a project I’m working on. Then I added anyone else whose mail I must not miss.  I will not be publishing this list :-)

Step 2: I created these mailboxes:

  • Inbox
  • VIP
  • VIP Urgent
  • Probably Not Urgent
  • Reference
  • Read
  • Discussions (under which are any number of mailboxes for each discussion area)

Every single message that arrives is copied to read and marked as read, and thus I can count on having a copy. 

Each of the following rules has an Except clause that reads: Except if my name is in the to or cc field or the sender is in the VIP list. 

There are then a series of rules, with that except clause that copies mail for discussions to the appropriate discussion and out of the inbox.

VIPRule

There is an additional rule that essentially says that if it is not for a discussion and doesn’t meet the exception criteria, put it in the “probably not urgent” folder.

Finally there are two vip rules, anything that is from someone on the VIP list that is marked urgent goes to the VIP urgent list and a template is used to send an SMS to my phone.  Anything that is from a VIP but is not urgent goes to the VIP folder. And then anything to me or cc to me but not vip stays in the inbox.

I can now read my messages in just the order I want, deleting as I go safe that a copy of everything is already in “Read”

1. ViP Urgent and VIP – never miss a message from a VIP again
2. Inbox  - read everything addressed to me
3. As time allows skim Probably not urgent and the discussions

Save anything I might want to come back to in reference and/or copy it to Evernote (discussed below) and/or make an entry in ToDo (discussed below).

All of this is supplemented by Copernic, an extraordinary search engine that is able to retrieve the messages I need in the specified amount of time, along with any matching files, contacts, images and so forth,

Copernic

Email: Manage the 3,000 email messages I get every day so that I spend no more than 20-30 minutes a day reading my email,  but see everything important and never miss a critical email and so that I can retrieve any email I need within 3 seconds

Spec:

image Manage the 3,000 email messages I get every day

image I spend no more than 20-30 minutes a day reading my email

image I see everything important

image I never miss a critical email 

image I can retrieve any email I need within 3 seconds,

 

An Evolving Story

I’m quite sure that this is not the final chapter, but there does come a point where organizing becomes a major distraction in and of itself, and as a friend once said, “How many frogs do you want to kiss to find an even-more-handsome prince?” 

I look forward to your comments and can only promise to be returning to matters of more immediate substance very soon.

Have I Missed The Bus?

About 5-10 times a week I get a letter that says something like this:

“Your book, Complete Idiots' Guide to a Career in Computer Programming  is wicked old. Do you still believe a programmer can be self-taught and is it possible for someone my age?”

Got one today and thought I’d answer here.

John,

The short answer is that the book is terribly out of date on its specifics (languages, technologies, etc.). There are a lot of new choices to make as to which technology to follow; I have completely hitched my wagon to Microsoft’s .NET since 1999, and as of 2007 I now work for Microsoft as “Silverlight Geek

With that information (and caveat) let me say unequivocally that the answer to both questions is yes, but it is far harder than most people expect, and the chart I often draw relates to how far people get in their first programming book. It looks like this:

Pctg of pages Read2

I totally made the numbers up, but based on talking with literally hundreds of readers and students. Folks start out with very strong intentions, but then the material gets difficult, their other job and family and real life intrudes and their resolution wavers.

So the first question is this: are you an autodidact? If not, save yourself a lot of grief, and start with a class, or better, a degree program at a good university.

That said, it certainly can be done; I did it (I had no choice, they kept kicking me out of school) and many of the best programmers I know did as well.  Of course, I started teaching myself when there was a lot less to learn.

And that is what I’d suggest you do; learn a lot less than there is to learn; narrow the field. Start by getting opinions from people who seem to love their jobs and who actually code for a living. Note that none of us will be right, but you may be able to eliminate some areas that are clearly wrong. Then pick a narrow field and learn that and nothing else for the first year.

Reasonable focus areas to consider:

  • Silverlight (Rich Internet)
  • WPF (desktop application)
  • ASP.NET / AJAX
  • Flash/ AIR (Rich Internet)
  • Java
  • Database
  • Open Source & Dynamic Languages
  • There are many others

I have had four career altering moments: 

  • Moving from general Unix programming to serious C coding on Unix
  • Switching to C++ / Windows
  • Switching to C# / .NET
  • Focusing on Silverlight

Warning: I now work for Microsoft as the “Silverlight Geek” and thus have a strong bias. But you know that.

A Crash Course

Let’s assume for the moment that you decide, correctly <smile> to learn .NET and focus on Silverlight and C#, learning the associated technologies along the way. Good choice.

iStock_MusicWireManMedium

Here is how I’d suggest you do it. Note that I’ll be recommending my books and others, but there are many alternatives. I’m also assuming money is not an object, but there are often free or nearly free alternatives.

  • Get a good development environment. A PC with at least 2, preferably 4 gig of RAM, a fast and big disk or two, and I strongly prefer two monitors, as big as you can afford.
  • Your development environment. Depending on your timing that will be Visual Studio 2008 or 2010.  Best is to buy the MSDN Subscription but they are expensive (ranging from $1K to 10K). You can of course just start with C# Express which is free.
  • Get a good introduction to the language and to .NET. I recommend Learning C# 3.0 (by me and Brian MacDonald).
  • Follow that with selected chapters from Programming .NET 3.5 by me and Alex Horovitz. (Just by the way, this is my most underappreciated books <smile>). For the first go ‘round, read chapters 1,2,8,10 and then save the book for later (you’ll be back)
  • OK, you’re ready for Silverlight. My guess is that by the time you’re ready we’ll have released Silverlight 3 and the new books on Silverlight 3 will be available as well.
  • I’d get at least two books on Silverlight (but I buy lots of books) and at least one on Expression Blend 3

Everything you need for Silverlight is at our web site. Start with my  Guide to Getting Started. (Note to self: update that page very soon!)

  • Go to our Forums often.
  • Sign up and read some of the better Silverlight blogs. You can find them by subscribing to Silverlight Cream.

Write Code, Publish Code

As soon as you feel you can write a Silverlight application that does something cool, make sure you put it where people will find it.  Then keep going. As soon as possible, get any work you can, paying or not. Contribute code to open source or anything else you can. Build confidence. Write articles on things you’ve just learned.

 

Best of luck!

 

jessesig

Where’s Jesse?

From now until sometime this summer, you may notice bursts of slow. Please mark this up to:

  • Summer vacation
  • Building embargoed videos so that we have lots of great stuff ready when Silverlight 3 is released
  • Updating older videos, tutorials, etc.,  so that they work great when Silverlight 3 is ready
  • Planning Silverlight 4 <smile>
  • Vacation (what??)
  • Cooking hard on the VideoWiki project’s new incarnation (more soon)

That said, MiniTutorials and Videos will still be a major effort, and will only ramp up even more once Silverlight 3 is live (which as you know is…. well, soon!)

But stay turned, what I lose in frequency I’ll make up for in incredibly astute and entertaining writing, breaking news, inside information, unauthorized leaks and internal gossip. Or not.

Meanwhile, I’ll be twittering and writing about my adventures and experiments in attempting to take Videos to the next level. Since it isn’t something everyone will be interested in, I’ll move it to a separate on-going story accessible as pages outside the main flow, from a link on the side bar, much like the Quick Bits.  The first entry is here.

Posted by jesseliberty | with no comments

Silverlight Validation in Detail

 

In a previous post I mentioned that Silverlight 3 has enhanced support for data entry validation. In this first of two mini-tutorials on the topic,  I will take you through the process of implementing validation in some detail.

DataValidation1

The key to understanding Silverlight validation is the division of logic from UI. In this case, the logic is delegated to the business object that the input control is bound to, and the UI is owned by the the input control (and the associated controls for displaying error conditions.) 

In the case shown above, the text box into which the user is invited to type an ISBN is the input control. Not shown is a business object (also, in these cases called a data object) that holds the rules about what makes for a valid ISBN.

UIAndLogicInValidation

On the left of this diagram is the UI. It is presented to the user as a text box, and implemented using Xaml. On the right is the business logic. A business object is created, in this case as a class in C# that represents, most often, an object in the user’s domain of concern – here a book.

The business object (the book) knows what a valid ISBN is, the UI does not.  The Business object determines if the value given to it by the UI is valid. If not, it throws an exception, specifying what is wrong. In this case, it might throw one of three exceptions:

  • "Must be exactly 10 integers long"
  • "Must be numbers or letter X"
  • "Checksum is invalid!"

 

The UI doesn’t know what the rules are, and the Business object doesn’t know how the UI will present the problem to the user (if at all!). And that is good.

Using Binding to Mediate the Validation of the UI By the Data Object

We are already asking the Binding Object to connect the User Control to the Business object, so it is the obvious choice to also pass along the value for validation and the objects response (if any).

Normally, when you bind a property to a TextBox you would provide the Mode and the Path, in this case, you add two more properties:

 

   1: Text="{Binding Mode=TwoWay, 
   2: NotifyOnValidationError=True,
   3: Path=ISBN10, 
   4: ValidatesOnExceptions=True}" 

The Business Object throws an exception if the data is not valid, and puts the reason in the Exception’s message. The Binding Object turns the exception into a message to the control, and sets the controls visual state from Valid to either InvalidUnfocused or InvalidFocused. What the control does when it changes visual state from Valid to one of the invalid states is entirely up to the designer of the control or whomever templates that control.

[We’ll look at templating error states in the second part of this mini-tutorial in a few weeks.]

For this to work, the control must bind using two way binding and it must support the new ValidationState group (you can see the validation states group very readily by beginning the templating process of any of the input controls that support validation out of the box as shown here:

ValidationStates2

 

As of this writing, the controls that will support validation out of the box at RTW are

  • TextBox
  • PasswordBox
  • CheckBox
  • RadioButton
  • ListBox
  • ComboBox

With the exception of PasswordBox, all of these already work in the Beta version.

Data Validation Step By Step

You now have all the pieces, let’s put them together step by step. 

The designer sets up a binding between an input control (text box) and a data object (the Book object) ensuring that

  • The binding is 2 way
  • The Control has Visual state to support Validation states
  • The BindingFramework knows to turn exceptions into validation state (flags)

The user is prompted to enter an ISBN into the text box. The value entered is not evaluated until one of two events; either the user leaves the text box (causing the text box to fire its TextChanged method, or the user clicks the handy Validate Now! button which invokes UpdateSource on the textBox’s TextProperty without having to actually leave the textBox.

In either case,  the data is given to the Binding Framework which passes it to the Data Object for validation,

ValidationStage1

If the data is not valid, the DataObject throws an exception to the BindingFramework. The Framework turns the exception into an instruction to the input control to set its validation state to Invalid. This will kick off a storyboard, in our case turning the border red, and when the user clicks in the control bringing up the error message from the exception which is passed to the control in its error message.

Datavalidation2

[This drawing based on an original image by Karen Corby]

Steps To Creating Data Validation

There are times when I find that I follow every word of a presentation but I still have no idea how to actually do it.  So here’s how.

1. Create a  new project

2. Createi a business object that is going to own data validation

3. Create two way data binding between one or more input controls from the supported list above to one or more properties on your data object

4. For each control you want to validate, create a setter on the bound property that tests for the conditions you want to validate, and throws an exception if the data is not valid. In the control, be sure to set the two flags (NotifyOnValidationError=True, ValidatesOnExceptions=True).

That’s it!  Honest.

Here is the complete MinPage.xaml for this example followed by the complete code behind…

   1: <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   2:              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   3:              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   4:              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   5:              x:Class="Validation_OutOfBox.MainPage"
   6:              Width="600"
   7:              Height="250"
   8:              mc:Ignorable="d">
   9:     <Grid x:Name="LayoutRoot"
  10:           Background="White">
  11:         <Grid.RowDefinitions>
  12:             <RowDefinition Height="1*" />
  13:             <RowDefinition Height="1*" />
  14:             <RowDefinition Height="1*" />
  15:             <RowDefinition Height="1*" />
  16:         </Grid.RowDefinitions>
  17:         <Grid.ColumnDefinitions>
  18:             <ColumnDefinition Width="1*" />
  19:             <ColumnDefinition Width="1*" />
  20:         </Grid.ColumnDefinitions>
  21:         <TextBlock Text="{Binding Path=Title}"
  22:                    HorizontalAlignment="Center"
  23:                    VerticalAlignment="Bottom"
  24:                    Grid.Row="0"
  25:                    Grid.Column="0"
  26:                    Grid.ColumnSpan="2"
  27:                    FontFamily="Georgia"
  28:                    FontSize="24" />
  29:         <TextBlock x:Name="Prompt10"
  30:                    Text="Please enter the 10 digit ISBN"
  31:                    TextWrapping="Wrap"
  32:                    HorizontalAlignment="Right"
  33:                    VerticalAlignment="Bottom"
  34:                    FontFamily="Georgia"
  35:                    FontSize="18"
  36:                    Grid.Column="0"
  37:                    Grid.Row="1"
  38:                    Margin="5" />
  39:         <TextBox x:Name="TenDigits"
  40:                  FontFamily="Georgia"
  41:                  FontSize="18"
  42:                  HorizontalAlignment="Left"
  43:                  VerticalAlignment="Bottom"
  44:                  Margin="5"
  45:                  Width="150"
  46:                  Height="40"
  47:                  Grid.Column="1"
  48:                  Grid.Row="1"
  49:                  TextWrapping="Wrap"
  50:                  Text="{Binding Mode=TwoWay, 
  51:                  NotifyOnValidationError=True, 
  52:                  Path=ISBN10, 
  53:                  ValidatesOnExceptions=True}"   />
  54:         
  55:         <Button x:Name="FillIt"
  56:                 Content="Fill With valid ISBN 10"
  57:                 Width="120"
  58:                 Height="25"
  59:                 Grid.Column="1"
  60:                 Grid.Row="2"
  61:                 FontSize="12"
  62:                 HorizontalAlignment="Left"
  63:                 VerticalAlignment="Bottom"
  64:                 Margin="5"
  65:                 Background="#FF06F616" />
  66:         <Button x:Name="ValidateIt"
  67:                 Content="Validate Now!"
  68:                 Background="#FFFFFF00"
  69:                 Width="120"
  70:                 Height="25"
  71:                 Grid.Column="0"
  72:                 Grid.Row="2"
  73:                 FontSize="12"
  74:                 Margin="5"
  75:                 VerticalAlignment="Bottom"
  76:                 HorizontalAlignment="Right" />
  77:      </Grid>
  78: </UserControl>

Here’s the complete code behind,

   1: using System.Windows;
   2: using System.Windows.Controls;
   3: using System.Windows.Data;
   4:  
   5: namespace Validation_OutOfBox
   6: {
   7:   public partial class MainPage : UserControl
   8:   {
   9:     public MainPage()
  10:     {
  11:       InitializeComponent();
  12:       Book b = new Book();
  13:       b.Title = "Data Validation for Fun and Prophet";
  14:       LayoutRoot.DataContext = b;
  15:       FillIt.Click += new RoutedEventHandler( FillIt_Click );
  16:       ValidateIt.Click += new RoutedEventHandler( ValidateIt_Click );
  17:     }
  18:  
  19:     void ValidateIt_Click( object sender, RoutedEventArgs e )
  20:     {
  21:       BindingExpression bindingExpression = TenDigits.GetBindingExpression( TextBox.TextProperty );
  22:       bindingExpression.UpdateSource();
  23:     }
  24:  
  25:     void FillIt_Click( object sender, RoutedEventArgs e )
  26:     {
  27:       TenDigits.Text = "059652756X"; 
  28:     }
  29:   }
  30: }

 

Finally, here is the business class/ data object

 

   1: using System;
   2: using System.ComponentModel;
   3:  
   4: namespace Validation_OutOfBox
   5: {
   6:   public class Book : INotifyPropertyChanged
   7:   {
   8:     public event PropertyChangedEventHandler PropertyChanged;
   9:  
  10:     private string title;
  11:     public string Title
  12:     {
  13:       get
  14:       {
  15:         return title;
  16:       }
  17:       set
  18:       {
  19:         title = value;
  20:         NotifyPropertyChanged( "Title" );
  21:       }
  22:     }
  23:  
  24:     private string isbn10;
  25:     public string ISBN10
  26:     {
  27:       get
  28:       {
  29:         return isbn10;
  30:       }
  31:       set
  32:       {
  33:          
  34:         if ( value.Length != 10 )
  35:         {
  36:           throw new ArgumentException( "Must be exactly 10 integers long" );
  37:         }
  38:  
  39:         char[] isbnAsArray = value.ToCharArray();
  40:  
  41:         foreach ( char c in isbnAsArray )
  42:         {
  43:           if ( ( !Char.IsNumber( c ) ) && c.ToString().ToUpper() != "X" )
  44:           {
  45:             throw new ArgumentException( "Must be numbers or letter X" );
  46:           }
  47:         }
  48:  
  49:         int runningTotal = 0;
  50:         for ( int i = 0; i < 9; i++ )
  51:         {
  52:           int val =  ( Convert.ToInt32(isbnAsArrayIdea.ToString()) 
  53:                  * ( 10 - i ) );
  54:           runningTotal += val;
  55:         }
  56:         int mod = runningTotal % 11;
  57:         int checkSum = 11 - mod;
  58:         
  59:         int isbnCheckSum = -1;
  60:         if ( isbnAsArray[9].ToString().ToUpper() == "X" )
  61:           isbnCheckSum = 10;
  62:         else
  63:           isbnCheckSum = Convert.ToInt32(isbnAsArray[9].ToString());
  64:  
  65:         if ( isbnCheckSum != checkSum )
  66:         {
  67:           throw new ArgumentException( "Checksum is invalid!" );
  68:         }
  69:  
  70:         isbn10 = value;
  71:         NotifyPropertyChanged( "ISBN10" );
  72:       }
  73:     }
  74:  
  75:     private void NotifyPropertyChanged( String propertyName )
  76:     {
  77:       if ( PropertyChanged != null )
  78:       {
  79:         PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
  80:       }
  81:     }
  82:   }
  83: }

 

That’s it!

 

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