Scott Hanselman

ELMAH and Exception Driven Development FTW

May 5, '09 Comments [53] Posted in ASP.NET | ASP.NET MVC
Sponsored By

Jeff blogged last month about Exception-Driven Development. I've been using ELMAH for years and you should too. Having great instrumentation in your app is such a joy. I added ELMAH to NerdDinner and have learned all sorts of things. It's amazing that someone would care to hack a site about Nerds eating dinner, but they try.

This wasn't a hack, but a great bug found in my Nerd Dinner Mobile code that I wouldn't have thought to look for. Here I'm getting a NullReference Exception...why?

image

Well, here's the code:

private bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
{
return (controllerContext.HttpContext.Request.UserAgent.IndexOf(userAgentToTest,
StringComparison.OrdinalIgnoreCase) > 0);
}

Of course, I'm breaking the "Law Suggestion of Demeter" with all that digging, but what's the real issue? I'm assuming that the request has a UserAgent string at all! Exactly as the YSOD that ELMAH "tivo'ed" for me above.

So I changed it to this. Yes, I know that this could all be on one line and really baroque, but I find a few more lines to be easier to read.

public bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
{
string UA = controllerContext.HttpContext.Request.UserAgent;
if (string.IsNullOrEmpty(UA) == true)
return false;
return (UA.IndexOf(userAgentToTest, StringComparison.OrdinalIgnoreCase) > 0);
}

I likely would have never thought of this bug had I not had logs and instrumentation. A smart user could have told me, or I could have used a Unit Test Generator like Pex, OR I could have just used my head and thought of it first. ;) Assert your assumptions. I didn't, and I assumed, wrongy, UserAgent would be non-null.

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

Hanselminutes Podcast 160 - JavaFX and the Web's Four Virtual Machines

May 5, '09 Comments [2] Posted in Javascript | Podcast
Sponsored By

joshua_marinacci My one-hundred-and-sixtieth podcast is up. In this episode Scott talks to Joshua Marinacci from Sun, a Staff Engineer working on JavaFX. JavaFX, along with Flash and Silverlight battle to be The VM for the Web. We chat about how JavaFX approaches things and muse on who will win the web.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is a sponsor for this show!

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET and Windows Forms. Enjoy the versatility of our new-generation Reporting Tool. Dive into our online community. Visit www.telerik.com.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

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

Don't Give Bile a Permalink - Finding Balance within The No Asshole Rule

April 29, '09 Comments [84] Posted in Musings
Sponsored By

I asked on Twitter today if it was "OK to be a dick as long as you were introspective about it?" I received a few responses, including one asking if I'd be more gender-neutral and pick a word like asshole instead. You can't please everyone. Forgive my language in this instance.

There's a lot of discussion on the Interweb right now about an individual in a technical community who used some imagery in a technical presentation at a technical conference that could be described as gender-insensitive. That's a Politically Correct way to say it. Another way to say it is that a guy used a porn metaphor and soft-core porn imagery in a technical presentation in front of a gender-mixed technical crowd.

Boiled down, the issue ultimately was not just about the images as it relates to gender, but rather that the images and the presentation metaphor was simply in poor taste. Certainly, taste in this context is subjective, but it's easier than you think to find the limits of good taste.

Dana Jones had this very erudite comment on a Rails mailing list:

Imagine a presentation about recruiting developers for your firm with the analogous presentation: "Big Game Hunting", replete with pictures of dead animals smilingly displayed by the hunters who killed them. Hunting is a perfectly legal sport and one which I personally have no objections to (just as I have no objections to porn), but do graphic images that will likely disturb at least *some* audience members really have a place?

What about a presentation about writing code on deadline: "Delivering Like a Birth Mom." Or how about graphic images of up-close breastfeeding in a talk titled "Nursing Your Projects Along."

These parallel theoretical presentations of Dana's brilliantly provide the boundaries of good taste vs. poor taste in this context. "I know it when I see it" is a truism. But with all subjective opinion, one man's norm is another's outlier.

That technical community is discussing the issue and working it out. One of the related posts by DHH, the creator of Ruby on Rails - but not the presenter in question - had an interesting post called "I'm an R-rated individual." It's basically a disclaimer/declaration that he's loud and proud and may offend. Some folks believe Rails.equal?(DHH) but that's of course, short-sighted.

This paragraph of David's post is excellent:

Blending like this isn't free. You're bound to upset, offend, or annoy people when you're not adding heavy layers of social sugarcoating. I choose to accept that trade because my personal upside from congruence is that I find more energy, more satisfaction, and more creativity when the bulls**t is stripped away.

A lot of people are talking about personal brand and "image management" right now, and it's easy to say, "oh, so-and-so is a jerk." and write them off. The reason that paragraph is so insightful is because DHH expresses two things. One, he consciously chooses his path. +1 Wisdom there. And Two, he realizes there are consequences...it "isn't free." +2 Introspection. Like a guy/gal or not, but give them credit for deciding to be someone. Feel bad if someone is a jerk and doesn't realize it. I thinking living consciously and unapologetically is to be commended.

DHH's path is not for everyone. It's not for me. I believe one should avoid being overtly offensive whenever possible and appropriate, public or private. I expend a some amount of effort being a consensus builder (perhaps because I'm an ENFJ and DHH is, I'm guessing, likely an ENTP) and I think one can be real without being rude. I encourage others to do the same.

However, it depends on what you feel strongly about and if what you feel strongly about outweighs what you believe others might feel. You need to be yourself, but you there ARE social norms, and others feelings, that should be considered.

@mstum on Twitter said: I'd rather have honest f-bombs than gentlemen hypocrites... Honest and direct people are so much easier to work with.

But can't one be an honest gentleman? Why is online (or offline) use of the F-word and general crassness somehow exemplary of "honesty?" If someone swears and slams their hand on a table in a business meeting I don't immediately think "Whew, finally an honest person!"

Being generally pleasant and helpful isn't sugarcoating, it's being pleasant and helpful.

@David_Ing said: Different worlds I guess. Reminds me of high school. Makes me feel old. Edgy douche is the new cool.

So where does it stop?

I had this conversation with Ade Miller on Twitter:

This may be a generation gap. I'm in my mid-30s and "social internet culture" for me doesn't automatically involve ending online arguments via reductio ad Hitlerum (Godwin's Law). Young people today (get off my lawn!) are largely more comfortable being unapologetically themselves online. I'm of a slightly older Internet generation that doesn't believe everyone is a unique snowflake and that if everyone behaves with a "this is me, like me or leave me alone" attitude then anarchy (ahem, or the internet) will emerge.

People believe strongly about some things and less strongly about others, and you'll never get everyone to agree. I certainly don't promote being a push-over. If something is an injustice, then, by all means speak up. There are some folks in the .NET community that people consider abrasive or have written off as jerks. But see it from their perspective! For them, there is a great injustice, or a number of them, and social norms be damned! I deeply respect this perspective.

For example, my wife is Black. If I post pictures of my wife on my blog, I risk alienating racists and folks against interracial marriage. However, that's a risk (hopefully small) that I'm willing to take, as I certainly feel strongly about it and I think I'm on the right side of history. I'm also a diabetic and I don't hide it. These are stands, small or large, that I'll take, as they are important to me.

You might knee-jerk and think that's a trite example. You might say "we're all too Politically Correct." This might be a true, but just because you want to avoid being Politically Correct doesn't mean you should email me and say, "Hey, how's your Black Wife? How's Diabetes sucking for you? Still blind?"

A question on code comments showed up on StackOverflow this week, and the most highly-voted answer included the F-word. An "Edit War" ensued, with members of the community switching a code sample back and forth between the actual F-word, and various other forms like F*ck, Frick, and Foolish.

I swear occasionally. I can appreciate the F-word as appropriate punctuation while simultaneously realizing its crassness. I don't typically swear in meetings. It's conceivable I would if I could find the right situation. Most everyone who speaks English realizes that the N-word is off limits. Americans also have other words that we Just Don't Use, although the British do. Using them in a meeting is certain death.

The point is that NOT using these words doesn't fundamentally make my life worse. DHH says:

"I find more energy, more satisfaction, and more creativity when the bulls**t is stripped away."

I respect that, and good for folks who agree. I respect everyone's right to say what they like.

If you're a nudist and you give your technical talks on C# naked, I likely won't be there to watch your talk. You may feel REALLY strongly about nudism, and I wish you well. You may believe in the legalization of drugs and prefer to give your technical presentations high, and I say, kudos, but I and others may not show.

There are some social norms, and you should know what they are and know how strongly you feel about them when you take your message to a larger audience. Know that there are consequences when what you value is broadcast in a larger context while promoting a technology. I've lost readers who have said I don't do enough deep technical content, or they find my "intensely personal" posts off-putting, but I'm conscious of my decisions and I feel strongly about the things I choose to discuss on my blog.

I respect DHH's perspective and others like him. Some are concerned that some edgy attitudes are preventing female programmers from embracing programming as a vocation. DHH says:

"You certainly have to be mindful when you're working near the edge of social conventions, but that doesn't for a second lead me to the conclusion that we should step away from all the edges. Finding exactly where the line goes — and then enjoying the performance from being right on it — requires a few steps over it here and there."

Again, another paragraph with layers. He knows where the edge is, enjoys dancing on the precipice jumping back. To dismiss him as merely loud and obnoxious is to do him (and people like him) a disservice.

I have set a level of what I consider reasonable professional conduct both online and offline. You should too. Know what THE edge is, know what YOUR edge is and know the effects of being near both. Decide what you feel strongly about and what you don't. Not everyone has the same norms, but everyone should know what the consequences are and measure them according to their own value system.

The advice that works for me is to avoid giving bile a permalink. Don't be a dick. If you are a dick, you don't get to complain when things go bad for you. There are consequences to all actions and they live on. They live on longer if you give them a permalink.

What do you 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

The Weekly Source Code 41 - Searching Code, Sharing Code, and Reading Code (and Comments)

April 28, '09 Comments [10] Posted in Source Code
Sponsored By

I really advocate folks reading as much source as they can because you become a better writer by reading as much as writing. That's the whole point of the Weekly Source Code - reading code to be a better developer.

Reading code in Open Source projects is a good way to learn, especially if the project has been around a while and been successful, or if you already respect the team of people working on it. Less reliably, you can find snippets of code by searching and sharing code.

Searching Code

There's basically three players in the "Code Search Engine" space. These are the ones I bump into all the time. There could be others.

  • Koders.com (where Phil Haack used to work)
  • Krugle - MSDN is using Krugle to power the MSDN Code Search Preview that searches MSDN Library, MSDN Code Gallery, and CodePlex.
    • (Note, the Krugle MSDN Code Search is going up and down, as it's in preview and they are actively developing it. If you get a login dialog, that's why. Wait a while.)
  • Google Code Search - If you have lots of code on your site you can make its existence explicit to Google by extending your Sitemap to include the CodeSearch extensions. You can also point them to your Subversion repo if it's publically available.
  • Codase - Been around forever, and still up and running, but nothing new on their homepage for 4 years? What's up? Weird. I don't count them as a player, but they were first, as far as I can see.

Searching the web is 99% free text search, as you know. Every once in a while, I'll use an advanced technique like searching with "filetype:ppt" or with a numeric range like "$1500..$3000" but seriously, that's like once in a 100 searches or less. I challenge you if you say you use it more. Free text searching almost always gets it right, unless you're searching for homonyms or something general.

Because free text is so good, while I like the idea of a code search engine and I do use them, I'm not sure if I need anything more than a "code-specific free text search." I personally believe that being really specific in your search query is a really good way to filter your way out of the ONE result you need.

Sometimes, however, when searching code you will occasionally want the advanced techniques.

Here's some examples:

If you're looking for a specific implementation of something, like an MD5 hash or a BTree, these search engines can be really useful. They can't tell you anything about quality though.

Sharing Code

On your blog...

I started using SyntaxHighlighter on my blog for all my code snippets and I'm bummed I didn't start earlier. The best aspect of it is that all my snippets are inside of <pre> tags. That means they're easily indexed and not littered with markup. The syntax highlighting is added on the client side by JavaScript. I use the PreCode plugin in Windows Live Writer and wrote up on I do it on my blog. It's fast becoming THE way to post code inline. I even convinced ScottGu (by doing it for him without asking) to use SyntaxHighlighter when I converted the Nerddinner PDF to HTML.

On the web or via IM...

You know by know that pasting code in an IM window is a recipe for pain, and misplaced emoticons. I use code-pasting services for this instead.

I really like using Josh Goebel's Pastie for sharing code, although he doesn't formally support C# or VB. I'm slowly moving to Gist.Github.com though.

The best social-code-sharing snippet sites are:

  • Pastie.org - Favorite of Rubyists and the "original." Couldn't be simpler.
  • Pastebin.com - Favorite of IRC users and supports C# and dozens of other languages. Also nice because it supports "expiration" of your code in a day or a month. Nice for email or IM.
  • Gist.GitHub.com - Winner for best name, as "Gist" (pronounced "Jist") meaning "Essense" is a great way to express what you're trying to, ahem, express. Just the gist. Supports virtually all languages as well as a "private" option. It also supports versioning, which is unique. This makes sense since Github is a "social source control system." Here's a screencast explaining how this concept can by taking to the next level.

I've had an interesting conversation or two about making sharing code easier with Jeff. We'll see where that goes.

Code Comments

Kind of unrelated, but still fun...I think that every developer should have a blog, or at least an outlet for writing. Those that don't, often use Code Comments to express themselves.

There was a great post at StackOverflow asking for the "best comment in source code you have ever encountered." This, of course, turned into a list of the worst comments ever found in source code, because that's how programmers work, right? Best == Worst. ;) A lot like the Daily WTF.

You can find some interesting stuff if you use the code search engines to search for stuff that shouldn't ordinarily be in code. This guy searched the Linux Source Code for swear words and graphed them over time.

Some other non-explicit examples...

  • Found on Koder's searching for Poop
    ; Poor-man's Object-Oriented Programming
    ;                   or
    ;                  POOP
    (module POOP
       (import Utility)
  • Found on Krugle searching for Mind-Numbing

    // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
    439 // OR the 2.0 calling convention (no ptions) - we really love backward compat, don't we?

  • Found on Google Search searching for Hate
     # God, I hate DTDs.  I really do.  Why this idiot standard still
     # plagues us is beyond me.
  • Found on Google Search searching for Horrible
     case 'H':
          horrible++;
          break;
  • Found on Koders searching for "God Himself"...not really a comment, but interesting.
     (c.query_gender().equals("male") ? "He" : (c.query_gender().equals("female") ? "She" : "It"))
              + " is " +
              ((c.query_level() == client.WIZ_GOD) ?
                    "the Almighty God himself\n\rBeware of his wrath if you don't follow his laws!" :
                    ((c.query_level() > client.MORTAL) ? "a powerful immortal" : "a puny mortal")))+ "\n\r"
  • Found on Google Search searching for "profoundly bad"
    if isinstance(real_child, SilentMock):
       raise TypeError("Replacing a mock with another mock is a profoundly bad idea.\n" +
        "Try re-using mock \"%s\" instead" % (name,))
  • Found on Google Search looking for "Pure Evil"
     my $db = delete $access->{db};
              # This is pure evil.
              $db->DESTROY;
  • Found on Google Search searching for Poop, but only in Ruby files.
    "Stimpy-drool",
    "poopy",
    "poop",
    "craptacular carpet droppings",

I'm sure if you search, you'll find lots of great stuff in comments, much more colorful than this. For example, the Greatest Code Comment Ever (Line 107) hit tip to Cam Soper:

uint32 sign=[fh readUInt32BE];
uint32 marker=[fh readUInt32BE];
uint32 chunklen=[fh readUInt32BE];
off_t nextchunk=[fh offsetInFile]+((chunklen+3)&~3);
// At this point, I'd like to take a moment to speak to you about the Adobe PSD format.
// PSD is not a good format. PSD is not even a bad format. Calling it such would be an
// insult to other bad formats, such as PCX or JPEG. No, PSD is an abysmal format. Having
// worked on this code for several weeks now, my hate for PSD has grown to a raging fire
// that burns with the fierce passion of a million suns.
// If there are two different ways of doing something, PSD will do both, in different
// places. It will then make up three more ways no sane human would think of, and do those
// too. PSD makes inconsistency an art form. Why, for instance, did it suddenly decide
// that *these* particular chunks should be aligned to four bytes, and that this alignement
// should *not* be included in the size? Other chunks in other places are either unaligned,
// or aligned with the alignment included in the size. Here, though, it is not included.
// Either one of these three behaviours would be fine. A sane format would pick one. PSD,
// of course, uses all three, and more.
// Trying to get data out of a PSD file is like trying to find something in the attic of
// your eccentric old uncle who died in a freak freshwater shark attack on his 58th
// birthday. That last detail may not be important for the purposes of the simile, but
// at this point I am spending a lot of time imagining amusing fates for the people
// responsible for this Rube Goldberg of a file format.
// Earlier, I tried to get a hold of the latest specs for the PSD file format. To do this,
// I had to apply to them for permission to apply to them to have them consider sending
// me this sacred tome. This would have involved faxing them a copy of some document or
// other, probably signed in blood. I can only imagine that they make this process so
// difficult because they are intensely ashamed of having created this abomination. I
// was naturally not gullible enough to go through with this procedure, but if I had done
// so, I would have printed out every single page of the spec, and set them all on fire.
// Were it within my power, I would gather every single copy of those specs, and launch
// them on a spaceship directly into the sun.
//
// PSD is not my favourite file format.

Enjoy your search and read more code!

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

Hanselminutes Podcast 159 - IronPython in Action with Michael Foord

April 25, '09 Comments [5] Posted in DLR | Podcast | Python
Sponsored By

ironpythoninaction My one-hundred-and-fifty-ninth podcast is up. Michael Foord makes his living as a Python programmer. More specifically has an IronPython programmer. He chats with me about his company's use of IronPython, the DLR and why they picked Python over C# or VB.

40% OFF COUPON: Michael's hooked me up with a 40% off coupon for a limited time for Hanselminutes listeners. Just buy the book with coupon code "ironpython40".

Links from the Show

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is a sponsor for this show!

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET and Windows Forms. Enjoy the versatility of our new-generation Reporting Tool. Dive into our online community. Visit www.telerik.com.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

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.