Scott Hanselman

11 Top Tips for a Successful Technical Presentation

May 17, '08 Comments [42] Posted in Speaking
Sponsored By

image Over five years ago I posted Tips for a Successful MSFT Presentation. Yesterday I watched the video of my Mix Presentation all the way through. It's always very painful to hear one's own voice but it's even worse to watch yourself. I never listen to my podcast and I avoid watching myself. It's like watching a person in parallel universe and it inspires self-loathing. However, if you are someone who values continuous improvement - and I am - you need to do the uncomfortable.

Here's my five-years-later Updated Tips for a Successful Technical Presentation.

1. Have a Reset Strategy (One-Click)

If you're going to give a talk, you'll probably have to give it more than once. If you have demonstrations of any kind, have a "one-click" way to reset them. This might be a batch file or Powershell script that drops a modified database and reattaches a fresh one, or copies template files over ones you modify during your demo.

Personally, I'm sold on Virtual Machines. I have seven VMs on a small, fast portable USB drive that will let me do roughly 12 different presentations at the drop of a hat. You never know when you'll be called upon to give a demo. With a Virtual Machine I can turn on "Undo Disks" after I've prepared the talk, and my reset strategy is to just turn off the VM and select "Delete Changes." A little up-front preparation means one less thing for you to panic about the day of the talk.

2. Know Your Affectations (Ssssssseriously)

I have a bit of a lisp, it seems. I also hold my shoulders a little higher than is natural which causes my neck to tighten up. I also pick a different word, without realizing it, and overuse it in every talk. This is similar to how Microsoft Employees overuse the word "so" (which is actually Northwestern Americans, not MSFTies) too much.

It's important to know YOUR affectations so you can change them. They may be weakening your talk. Don't try to remember them all, though. Just pick two or three and focus on replacing them with something less detracting. Don't overanalyze or beat yourself up, though. I've spoken hundreds of times over the last 15 years and I'm always taking two-steps forward and one step back. The point is to try, not to succeed absolutely.

3. Know When To Move and When To Not Move (Red light!)

One of the most powerful tips I ever received was this: "When you move, they look at you. When you stop, they look at the screen." Use this to your advantage. Don't pace randomly, idley or unconsciously. Don't rock back and forth on your heels. Also, empty your pockets if you tend to fiddle with lose change or your keys.

4. For the Love of All That Is Holy, FONT SIZE, People (See that?)

It just tears me up. It physically makes me ill. To give a presentation and utter the words "um, you probably won't be able to see this" does everyone in the room a disservice.  Do NOT use the moment of the presentation as your time to do the font resizing.

Lucida Console, 14 to 18pt, Bold.  Consider this my gift to you.  This is the most readable, mono-spaced font out there.  Courier of any flavor or Arial (or any other proportionally spaced font) is NOT appropriate for code demonstrations, period, full stop.  Prepare your machine AHEAD OF TIME.  Nothing disrespects an audience like making them wait while you ask "Can you see this 8 point font? No? Oh, let me change it while you wait."  Setup every program you could possibly use, including all Command Prompt shortcuts, before you begin your presentation.  That includes VS.NET, Notepad, XMLSpy, and any others, including any small utilities.

I've found that the most readable setup for Command Prompts is a Black Background and with the Foreground Text set to Kermit Green (ala "Green Screen."  Yes, I was suspicious and disbelieving also, but believe it or not, it really works.)  I set Command Prompts to Lucida Console, 14 to 18pt, Bold as well, with much success.

Also, set the font size to LARGEST in Internet Explorer and remember that there are accessibility features in IE that allow you to include your own Large Font CSS file for those web pages that force a small font via CSS.

Learn how to use ZoomIt and practice before-hand. It can be an incredibly powerful tool for calling out sections of the screen and making it so even the folks way in the back can see what's going on.

For simplicities' sake, I like to keep a separate user around call "BigFonty" (choose your own name).  He's an Administrator on the local machine and he exists ONLY for the purposes of demonstrations.  All the fonts are large for all programs, large icons, great colors, etc.  It's the easiest way to set all these settings once and always have them easily available.

5. Speak their Language (Know the Audience)

When I was in Malaysia for TechEd, I spent 3 full days exclusively with locals before the talk, I learned snippets of each of the languages, tried to understand their jokes and get an idea about what was important to people in Malaysia.  American analogies, much humor, and certain "U.S. specific" English colloquialisms just didn't make any sense to them.  When it came time to give the presentations, I better understood the Malaysian sense of timing, of tone and timbre, and I began each of my presentations by speaking in Bahasa Malaysia.  I changed aspects of my slides to remove inappropriate content and add specific details that would be important to them.

I've used this same technique in a half-dozen countries with success. While this is an extreme example, the parallels with any audience are clear.  If you're speaking to a room full of IT guys who work in the Automotive field, or the Banking industry, the fact that we are all programmers only gives you a small degree of shared experience.  Remember no matter the technical topic, try to get into the mind of the audience and ask yourself, why are they here and what can I tell them that will not be a waste of their time.  What would YOU want to hear (and HOW would you like to hear it) if you were sitting there?

6. Be Utterly Prepared (No excuses)

Short of an unexpected BSOD (and even then, be ready) you should be prepared for ANYTHING.  You should know EVERY inch of your demos and EXACTLY what can go wrong.  Nothing kills your credibility more than an error that you DON'T understand.  Errors and screw-ups happen ALL the time in Presentations.  They can even INCREASE your credibility if you recover gracefully and EXPLAIN what happened.  "Ah, this is a common mistake that I've made, and here's what you should watch for."  Be prepared with phrases that will turn the unfortunate incident around and provide them useful information.

7. CONTENT, CONTENT, CONTENT (Have some)

Every move, phrase, mistake, anecdote and slide should actually contain content.  It should be meaningful.  Your mistakes should teach them, your demos should teach them; even your shortcut keys, utilities and menu layout should teach them.  A presentation isn't an opportunity to read your slides.  I'll say that again. Don't READ your slides. I can read faster than you can talk.

Remember that most people can read silently to themselves 5 to 10 times faster that you can read to them out loud.  Your job as a presenter is to read in between the lines, and provide them structure.  Your slides should be treated as your outline – they are structure, scaffolding, nothing more.  If you jam your slides full of details and dozens of bullets, you might as well take your content and write an article.  It's difficult to listen to someone talk and read their slides at the same time – remember that when you design your content. YOU are the content, and your slides are your Table of Contents.

8. System Setup (Be unique, but don't be nuts)

When you a presenting, remember that you are looked upon as an authority.  Basically, you are innocent until proven guilty.  It's great to have a personality and to be unique, but don't let your personal choice of editors or crazy color scheme obscure the good information you're presenting.  I appreciate that you may like to use VI or emacs to view text files, but let's just say that sometimes Notepad has a calming effect on the audience. 

I give Microsoft talks, usually, so I tend towards Visual Studio, but 99% of my talks use a limited number of tools. Basically Visual Studio, Notepad, the Command Prompt and a Browser.

Remember that while you may prefer things a certain way while your face is a foot away from the screen, it's very likely the wrong setup when 500 people are more than 100 feet away.

I really like to get Toolbars and things out of the way. I use F11 (Fullscreen) in the Browser a lot, as well as Visual Studio's Shift-Alt-Enter shortcut to FullScreen. Turn off unneeded flair and toolbars. Also, turn on line-numbering so you can refer to lines if you're presenting code.

9. Speaking (Um…)

"Volume and Diction," my High School Drama teacher said to me.  Speak clearly, authoritatively, project your voice to the back of the room.  The best speakers don't even need microphones.  If you have a speaking affectation (I had a lisp growing up) or you tend to say, um, etc, or find yourself overusing a specific phrase ("a priori", "fantastic", "powerful", etc) take it upon yourself to NOTICE this mannerism and avoid it.

Practice multi-tasking.  It seems silly to say, but although we can all multitask to a certain degree, when we hit a real snag in a presentation, many of us tend to freeze.  Silence is deadly.  Remember, since all eyes are on you, complete silence and apparent introspection says "I don't know know what I'm doing."  When you need to get to a particular file, don't make the audience wait for you while you putter through explorer.  Have shortcuts ready (and explain when you use them).  Move fast and efficiently, but annotate your actions.  You should continue to "color-commentate" your actions like a sports announcer.  Don't allow "dead-air," unless it's silence for effect.

10. Advancing Slides (No lasers!)

I always used to hate slide-advancers, you know, those little remotes with forward and backward buttons. Then I tried one and I'm hooked. I use the Microsoft Presenter Mouse 8000 and totally recommend it. It isn't just a great Bluetooth mouse, but flip it over and it's a great Powerpoint slide advancer. 

Take a look at Al Gore's excellent presentation in "An Inconvenient Truth." It's seamless and flows. Now imagine him running over to his laptop to hit the spacebar each time he wanted to advance a slide. My presentations have gotten better as I've started incorporating this technique.

11. Care (deeply)

I really avoid presenting on topics that I don't care about. I avoid it like the Plague and I encourage you to do so as well. There's nothing more important that truly caring about your topic. If you care, it'll show. If you eschew all the other tips, at the very least care.


What are YOUR tips, Dear Reader? What tips, mantras or preparations have you used to make your presentations that much better?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Mix 08 Sessions available in new dual-stream versions using Silverlight

May 16, '08 Comments [21] Posted in ASP.NET | ASP.NET MVC | Mix | Screencasts | Silverlight | Speaking
Sponsored By

I posted the month before last that the Mix08 Sessions, mine included, were up and available at http://sessions.visitmix.com. I posted links to the MP4, WMVs and other downloaded versions at the time as well. The Silverlight versions were the same versions, so there wasn't really a compelling reason to use Silverlight.

What I didn't know, however, is that they (the powers that be) not only recorded the slides and demos, but also had cameras going at the same time. They did some post processing (on hundreds of sessions) and those new "dual stream" sessions are up and available online in Silverlight. One stream is a camera on me, and one is the slides and demos.

I'm fairly physical, so I really prefer my talks if you can see me. If you haven't seen the MVC talk before, you might enjoy watching this new version. You can see a screenshot below. If you click the screenshot you'll go directly to the site.

image

UPDATE: It looks like the servers are having trouble keeping up, but they're working on it. For now, don't select a chapter or you might be in for a wait. If the streams start, for now you'll just have to watch it straight through until they've fixed it. It's working well for me if you just let it play.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

VS2008 and .Net 3.5 SP1 Beta - Should You Fear This Release?

May 12, '08 Comments [23] Posted in ASP.NET | ASP.NET Dynamic Data | ASP.NET MVC | Learning .NET | Musings | Screencasts
Sponsored By

The Beta of .NET 3.5 and VS2008 SP1 is out. I'm sure everyone is blogging the heck out of it, so I'll try to add my own specific kind of value. There's fixes, many improvements (some subtle, some dramatic), and some new technology.

Should You Fear This (Beta) Release?

Maybe a little bit. Don't be afraid of the new assemblies or the bug fixes, I have found them to be very good and have no stability problems, but this Service Pack Installer might cause you some trouble in this beta, especially if you already have beta stuff installed over the top of VS2008RTM (the original version). It'll be correct when it releases later this summer.

Now, if you're going to decide to install a Beta of a Service Pack, do read the ReadMe and ScottGu's post. Go ahead, I'll wait here. OK, if you're already running some beta stuff, like the Silverlight Tools for Visual Studio, you'll want to uninstall that FIRST, otherwise you'll get an error and be upset. This will also be figured out when the SP actually releases, but be warned.

In this release, I have found the Progress Bar is wonky on XP and 2k3. It might say failed, and then succeed. Watch for the final message, not the bar. This will be fixed. Be aware also that it can be a long-ass install so get a coffee and pillow.

On the developer side, this is much more than just a "tightening of the screws" release, as it also kind of breaks a few rules and introduces some new stuff I've been personally waiting for.

What's New?

video-292ASP.NET Dynamic Data, ADO.NET Data Services ("Astoria"), ADO.NET Entity Framework (LINQ to Entities) are all additive. ScottGu has an extensive post detailing all the interesting bits.

Here's my explanation on ASP.NET Dynamic Data and why you might care. I've been doing talks around on ADO.NET Data Services, sharing my thoughts on how its RESTfulness relates to ASMX/SCF Web Services and WS-*.*, and I'm going to dig deeper into it this year because I think it's pretty sweet, especially if Ayende and I (mostly him) get it running over NHibernate. The ADO.NET Entity Framework can be plugged in underneath both ASP.NET Dynamic Data and ADO.NET Data Services, so taken as a whole, the data story is starting to be a lot clearer and more useful and I'm continuing to work/push for all this stuff over POCO (Plain ol' CLR Objects) whenever possible and/or appropriate.

For this release I've personally recorded seven (whew!) How-To Videos on ASP.NET Dynamic Data and the Dynamic Data Samples can be downloaded here. They videos and samples are short, sweet and to the point. I'm also hoping to do more integration-style videos showing all this stuff working together in something of a larger context.

There's also a bunch of fixes like VS2008 starts faster and the IDE is snappier in spots, the WPF Designers are beefed up, and a bunch of editor/designer bugs have been squashed.

Don't Mess With My GAC, Dude!

UPDATE: Patrick Smacchia, who certainly knows his product better than I, has posted a follow up with more detailed information about what's changed in .NET 3.5 SP1.

On the .NET 3.5 side of things, since this is an SP (Service Pack), yes, some stuff goes in your GAC and gets changed. However, the changes are completely additive. That means if an API's method signature has changed, that's a bug that we need to fix. It will be a fully compatible service pack release. It shouldn't break any of your existing code.

There's roughly 50 new or modified types throughout or about 80 to 100 if you count Dynamic Data. On the WPF side, there's a bunch of new stuff in System.Windows.Effects that will make WPF people happy. There's a new WebBrowserControl in System.Windows.Controls that's like "whew! about time!" as well as new DataBinding support in System.Windows.Data.

When folks tell me that things have changed, I personally don't always take their word for it, and would rather dig in and find out for myself what's changed in what assemblies.

As far as I know there are four major tools for doing Assembly Differences (some have been added since I blogged about Assembly Differences last year):

  • Libcheck - Over three years old, obscure, command-line, confusing, but still useful. I used this when diffing .NET 2.0 and 3.5 a while back.
  • Framework Design Studio - A recent tool by Krzysztof Cwalina, a personal hero of mine, along with his helpers Hongping Lim and David Fowler, it has both a GUI and a command-line option.
  • BitDiffer - This new tool from Greg Ennis is very polished and includes both a GUI and Command Line version. If it supported drag-and-drop it'd be even better. Unfortunately it crashed while I was trying to diff these assemblies.
  • NDepend - Last, but not least, a favorite tool of mine that I've blogged about and podcast about has been dramatically updated to do Assembly Diffs as well in a very cool way. The tool is very polished and lets you compare projects, dlls, supports drag and drop and is generally polished and wonderful, so I ended up using this tool.

So, Libcheck is frustrating, FDS is close, but only creates a text-based report on what's changed, BitDiffer crashed, and while NDepend does have some weird painting issues, but I was able to create this diagram with NDepend:

WhatIsNewInVS2008SP1

Here's a close up (you can get the whole picture by clicking on it). In this example I was hovering over a method that was blue, and got a tooltip indicating that a method has changed in that type.

image

I created the graphic by getting the DLLs from the GAC on a .NET 3.5 machine and the DLLs from a .NET 3.5 SP1 machine. Then I put them in two different folders on a machine that *did not have .NET 3.5 on it* to avoid any wackiness. Then I ran this Code Query Language (CQL) query:

SELECT METHODS WHERE CodeWasChanged

The results of that query were displayed in a number of ways, the most interesting one being the Metrics View. I set the metric to show the # of methods. In this example, 1 method = 104 pixels. Blue methods are CHANGED methods. Then I took 2 screenshots while scrolling horizontally and stitched them together in Paint.NET.

You'll see when you look at the diagram that there's some fixes here and there, but from a visual 20,000 foot view, perspective, nothing major that looks like more than bug fixes or smells of a systemic issue. Focusing on the Bug Fixes, it's onesy-twosy, bug fixes within a method here and there. The complete list of fixes is here and here.

BTW: I'm a huge NDepend fan, but I'm not associated with company at all, other than being a fanboy.

My Conclusion

Now that you've been both educated and warned, if you're not willing to wait a bit, you can download the VS2008 SP1 BETA here. Remember, this is a BETA of a Service Pack, so I'm personally continuing to install only on Virtual Machines that have VS2008 RTM.

If you have anything Beta that's layered on top of VS2008, like the Silverlight Tools, or something like that, back those off first, before installing this SP, and again, read the readme, as most known to-be-fixed issues are called out there already.

As ScottGu says:

"It will be a fully compatible service pack release.  We plan to ship the final release of both .NET 3.5 SP1 and VS 2008 SP1 this summer as free updates. "

So I'm feeling good about the final release later this year. But, for this beta, I don't want to take any chances with installer issues so it just seems prudent that I keep my primary machine on the initial version of VS2008/.NET3.5 until this SP1 is released. Have fun!

Related Links

Technorati Tags: ,,

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

The Weekly Source Code 26 - LINQ to Regular Expressions and Processing in Javascript

May 10, '08 Comments [11] Posted in ASP.NET | Javascript | LINQ | Silverlight | Source Code
Sponsored By

I've been getting more and more interested in how folks extend their applications using plugins and things. In my new ongoing quest to read source code to be a better developer, Dear Reader, I present to you twenty-sixth (half a year!) in a infinite number of posts of "The Weekly Source Code."

Sometimes when I read code, I kick myself (mentally) and say "Man, I should have thought of that!" Then I realize I'm not nearly as good a programmer as I think I am, and then I just let the source just wash over my brain.

Here's some source by smart people I've been reading this week that I should have thought of. ;) Coincidentally they are both examples of languages ported or re-imagined in another language.

"Processing" in JavaScript

When I say "Processing" I mean the open-source Java-based visualization language from http://processing.org/. Jeff calls it "more akin to sketching than coding" while I say it's sketching with code! Jeff yearns: "for the day when web pages are regularly illustrated with the kind of beautiful, dynamic visualizations that Ben Fry creates."

molten2

Well, John Resig, arguably already considered one of the best JavaScript coders on the planet after he gave us the tour de force that is JQuery, has ported Processing to Javascript and gives us Processing.js.

You can interact with it in two ways. First, as an elegant and tight Javascript API:

var p = Processing(CanvasElement);
p.size(100, 100);
p.background(0);
p.fill(255);
p.ellipse(50, 50, 50, 50);

Or, you can tunnel the actual Processing language like this:

Processing(CanvasElement, "size(100, 100); background(0);" + "fill(255); ellipse(50, 50, 50, 50);");

clockThis release is specifically targeted to Firefox3, Opera 9.5 and the Webkit Nightlies (Safari) - all unreleased, beta browsers. I'm going to try it under the DLR with Javascript in Silverlight. Heh heh.

Here are his demos. Remember, these don't work in IE7.

There's a load of demos, but here's a powerful one. A working clock in 17 lines of code.

void setup() {
size(200, 200);
stroke(255);
smooth();
}
void draw() {
background(0);
fill(80);
noStroke();
// Angles for sin() and cos() start at 3 o'clock;
// subtract HALF_PI to make them start at the top
ellipse(100, 100, 160, 160);
float s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
float m = map(minute(), 0, 60, 0, TWO_PI) - HALF_PI;
float h = map(hour() % 12, 0, 12, 0, TWO_PI) - HALF_PI;
stroke(255);
strokeWeight(1);
line(100, 100, cos(s) * 72 + 100, sin(s) * 72 + 100);
strokeWeight(2);
line(100, 100, cos(m) * 60 + 100, sin(m) * 60 + 100);
strokeWeight(4);
line(100, 100, cos(h) * 50 + 100, sin(h) * 50 + 100);
}

His code leans heavily on the Canvas which is why IE7 doesn't work. Much of the processing.js file is mapping from one API (the processing API) to Javascript constructs, usually canvas ones. For example, making a point(x,y) is:

  p.point = function point( x, y )
{
var oldFill = curContext.fillStyle;
curContext.fillStyle = curContext.strokeStyle;
curContext.fillRect( Math.round( x ), Math.round( y ), 1, 1 );
curContext.fillStyle = oldFill;
}

Note the rectangle that is 1 by 1. That's funny, but that's the life an API mapper. Remind me someday to tell you, Dear Reader, how I got filled pie charts working on an Original Palm Pilot that not only didn't support Put/GetPixel but didn't have floating point math. That was a hoot.

Anyway, one really good example of this guy's clean cleverness is the triangle function. Remember, this is a processing function and he's not only got to implement it, but also make the building blocks for doing it cleanly.

To start:

  p.triangle = function triangle( x1, y1, x2, y2, x3, y3 )
{
p.beginShape();
p.vertex( x1, y1 );
p.vertex( x2, y2 );
p.vertex( x3, y3 );
p.endShape();
}

Obvious, right? Well, not really, considering that the 2D Canvas doesn't have any of those three higher-level methods. Begin and EndShape are fairly clean. However, he had to implement a nice Fill, Stroke and ClosePath to do this cleanly.

  p.beginShape = function beginShape( type )
{
curShape = type;
curShapeCount = 0;
}

p.endShape = function endShape( close )
{
if ( curShapeCount != 0 )
{
curContext.lineTo( firstX, firstY );

if ( doFill )
curContext.fill();

if ( doStroke )
curContext.stroke();

curContext.closePath();
curShapeCount = 0;
pathOpen = false;
}

if ( pathOpen )
{
curContext.closePath();
}
}

It's about four layers deep, each primitive building on the next until he gets a nice clean triangle implementation, but then he can use it for quad() and it the same method handles bezierVertex as well. It would do you well to FireBug your way through his code. It's a wonderful fun way to re-learn Javascript from a gentleman who knows what he's doing.

LINQ to RegEx and Fluent Regular Expressions

I was trying to re-re-re-learn Regular Expressions again this week for a small task. It's funny how Regular Expressions are the first thing to leave my brain even though there are a bunch of Regular Expression Tools out there. Josh Flanagan came up with a Fluent Interface for Regular Expressions like:

Regex socialSecurityNumberCheck = new Regex(@"^\d{3}-?\d{2}-?\d{4}$");

would look like this:

Regex socialSecurityNumberCheck = new Regex(Pattern.With.AtBeginning 
.Digit.Repeat.Exactly(3)
.Literal("-").Repeat.Optional
.Digit.Repeat.Exactly(2)
.Literal("-").Repeat.Optional
.Digit.Repeat.Exactly(4)
.AtEnd);

It took me a second to like this. OK, it took me a while. Breathe for a minute, and read it out loud. It kind of makes sense, actually, although there is a reasonable argument against in the comments of Josh's post:

[It] strikes me that a user of this library needs to learn a fairly complex syntax which is almost as far from "plain english" as regex, when they could simply learn how to do regex.

Sure, but it's fun to try new things. If you look a his source, it's really just a really smart string concatenator. I think it would actually be a very interesting way to teach or learn regular expressions, especially if you're a casual RegEx'er like me.

Krzysztof Ko┼║mic created a similar API in 2007. His fluent interface over RegEx looks like this:

Pattern pattern = Pattern.Define().
As("Kot".Count(Times.AtLeast(2))).
FollowedBy(Any.Except('a','b','c')).
Start(At.BeginingOfStringOrLine);

Then Roy Osherove took Josh's API further and took Josh's Fluent Interface to RegEx from 2006 and applied a LINQ query syntax , creating in the process, LINQ to Regex.

Here's Roy's example:

public void FindEmailUsingPattern()
{
var query = from match in
RegexQuery.Against("sdlfjsfl43r3490r98*(*Email@somewhere.com_dakj3j")
where match.Word.Repeat.AtLeast(1)
.Literal("@")
.Word.Repeat.AtLeast(1)
.Literal(".")
.Choice.Either(
Pattern.With.Literal("com"),
Pattern.With.Literal("net"))
.IsTrue()
select match;
foreach (var match in query)
{
Assert.AreEqual("Email@somewhere.com",match.Value);
}
}

After the "from match in", the simple heart of it is Roy's static Against() call that returns a RegexQuery that is IEnumerable of Match, thereby supporting the foreach later on:

namespace Osherove.LinqToRegex 
{
public class RegexQuery : IEnumerable
{
private readonly string input;
private object lastPatternRetVal;
private RegexQuery(string input)
{
this.input = input;
}
public static RegexQuery Against(string input)
{
return new RegexQuery(input);
}

private string _regex;
public RegexQuery Where(Expression<func><pattern,bool> predicate)
{
_regex = new PatternVisitor().VisitExpression(predicate).ToString();
return this;
}

public RegexQuery Select<t>(Expression<func><pattern,t> selector)
{
return this;
}
#region IEnumerable Members

IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this).GetEnumerator();
}

public IEnumerator GetEnumerator()
{
MatchCollection matches = Regex.Matches(input, _regex);
foreach (Match found in matches)
{
yield return found;
}
}
}
}

You can find all the source for Roy's project up at his assembla.com project site and Josh's source is on his blog. It is worth noting, though that you can combine LINQ Queries with Regular Expressions without any tricks because Matches are returned in a MatchCollection an LINQ loves things that are IEnumerable.

You can use LINQ projections to pull objects out of a collection of matches like:

    List<yourType> = (from Match m in matches
select new YourType
{
Id = m.Groups[1].Value,
Something = m.Groups[2].Value
}).ToList();

So, we've got two sides of the coin here. First, the creation of the Regular Expression. That can be the standard way, or with a fluent interface. Either way, you end up with a string. Second, you've got the extraction of the information. Most often you'll care about the MatchCollection that comes back. You'll usually want to pull information out, so while you're foreach'ing your way over the collection, you can use LINQ to create an object projection that's chopped up and sorted and grouped all with one query, regardless of how you created the query in the first place.

Choice is good.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

TypeConverters: There's not enough TypeDescripter.GetConverter in the world

May 10, '08 Comments [12] Posted in Source Code
Sponsored By

While reading source today, I saw some code in the wild today that looked roughly like this (not the actual code):

type = typeof(T);
if (type == typeof(Boolean))
{
returnValue = (T)((object)Convert.ToBoolean(value));
}
else if (type == typeof(String))
{
returnValue = (T)((object)value);
}
else if (type == typeof(Int16))
{
returnValue = (T)((object)Convert.ToInt16(value));
}
else if (type == typeof(Int32))
{
returnValue = (T)((object)Convert.ToInt32(value));
}
//...and on and on for a dozen+ types

You get the idea. This isn't that uncommon, I've seen it more of than not. The person who is writing it usually knows it's bad 50% of the time, but it's always a trade-off between figuring out the right search query (a tough one, in this case!) and knowing what to look for in MSDN.

This brings up one of my favorite classes in the BCL, the TypeDescriptor class. A method like this:

public static T GetTfromString<T>(string mystring)
{
var foo = TypeDescriptor.GetConverter(typeof(T));
return (T)(foo.ConvertFromInvariantString(mystring));
}

...would allow all that switch/if/else to go away replaced by:

bool b = GetTfromString("true");

You'd probably want to expand the method with checks to see if T was in fact, System.Type, or System.String, but you get the idea.

image There are lots of standard converters like EnumConvertor, ColorConvertor, and more, all waiting for you in System.ComponentModel as seen in the image at right.

Not only that, but you can make your own TypeConverters and spread the love. They are used extensively when displaying types in Property Grids, in WinForms, or in XAML. You can also use them in PowerShell as a better way to present your objects as strings when "casting" in PowerShell.

Jesse Liberty has a fine example showing how to use Type Convertors in Silverlight to enable you to put complex types in XAML attributes.

From MSDN:

To implement a simple type converter that can translate a string to a [Type]

  1. Define a class that derives from TypeConverter.

  2. Override the CanConvertFrom method that specifies which type the converter can convert from. This method is overloaded.

  3. Override the ConvertFrom method that implements the conversion. This method is overloaded.

  4. Override the CanConvertTo method that specifies which type the converter can convert to. It is not necessary to override this method for conversion to a string type. This method is overloaded.

  5. Override the ConvertTo method that implements the conversion. This method is overloaded.

  6. Override the IsValid method that performs validation. This method is overloaded.

That's it, and when that Type was decorated with an attribute like:

[TypeConverter(typeof(MyNewTypeConverter))]

Then that new TypeConverter would be picked up and used by the line of code I showed before. Much better than a switch or pile of if/elses, I think.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.