Scott Hanselman

Taking Proper Screenshots in Windows for Blogs or Tutorials

April 7, '11 Comments [54] Posted in Tools
Sponsored By

What? A blog post on how to take a screenshot? Seriously? Sure, this might seem a silly or superfluous blog post, but I can assure you that I see lousy screenshots on blogs, online tutorials and more (including some of my old posts) at least daily. Perhaps it's my "geek eye" but I (and I assume you, Dear Reader) just know when something is wrong with a screenshot. Just like you are the only one who notices when someone is running a 4:3 image on a 16:9 flat screen at a convention and it looks darned unprofessional, the same is true with screenshots.

"A bad screenshot is equivalent to a misspelled world. It makes both you and the word look unprofessional." - Me, just now.

Sometimes the best way to show you how to do something is to first talk about how not to do something.

Don't save Screenshots as JPEGs

JPEG is lossy. Lossy means "throws stuff away." Always save your screenshots as PNG, which is a lossless (throws nothing away) format.

A badly JPEGed image with hard to read text

Don't do uncomfortable, unnecessary or bad resizing

When resizing, only do it if you have to. Always use the highest quality resize algorithm your paint application supports. I use Paint.NET. It's one of the greatest pieces of software out there that should have shipped with Windows. Try to resize things "evenly," like 50% or 25%. If you resize to 73% or or 431 pixels by something, you are throwing data away and your screenshot will look bad.

A badly resized image with blockiness

Try to avoid small resizes, like taking an image and resizing it to 95%. If you are that close, try reframing or resizing the thing you're shooting, rather than doing such a small resize.

Don't customize your environment to the point it's unrecognizable

Think about Framing Your Screenshot as you would a photograph. I don't care about your toolbars. I don't care about your add-ins or your browser bookmarks. Turn EVERYTHING unnecessary off. That means toolbars, toolboxes, windows, add-ins, bookmark bars - anything that would make your screenshot look like your system and not mine. Keep everything stock and standard if you can.

Too many toolboxes open in Visual Studio so I can't see the code

Don't use tiny fonts and fancy colors.

As you can guess by now, these rules apply to screencasts as well. That means 16pt or better, folks. I use Consolas 16pt, minimum. 20 or 24 for Console Windows. Keep the default colors for your IDE. For Command Windows, use either White Text on a Blue Background or Green Text on a Black Background. Both have been proven to be the highest contrast and easiest to see (by me in totally scientific tests.)

Totally unreadable small text on a black background in Visual Studio

Don't show me what's underneath your transparent Aero Title Bar

Notice how you can almost see stuff underneath the transparent title bars of these last few screenshots? That's lame. There's two ways to fix it. One, open up notepad with its white background and put it behind the application you are shooting so the white is what you see behind the transparency.

Notepad open behind Visual Studio

Then, you can crop around it and get a title bar that doesn't look like crap:

A title bar that doesn't have crap behind its transparancy

Two, use a proper screenshot tool like Window Clippings. More on this later, but it's truly a great tool and worth it if you are taking more than a few screenshots a week. It'll save you time and make you look good. Window Clippings does two things right around transparency. First, it'll programmatically and automatically put a background behind your image while its taking the screenshot, and second, it'll make your transparent regions actually transparent when it makes a PNG.

See this square corner? That's not transparent and looks subtly lame. This was taken with the Window Selection option in the Snipping Tool that came with Windows.

A non-transparent corner with extra pixels 

See this one taken with Window Clippings? It's correctly transparent as a PNG and there's even an option to include a nice drop shadow.

A nice shadow with a transparent rounded corner

Don't use Basic or Classic Theme for Screenshots

Again, I don't know your personal preference, but it doesn't matter. Make your screenshots look like the typical computer, not your computer as you refuse to let Classic Theme go. ¡Viva NT4! Um, no.

A screenshot using the lame basic theme for Windows

Don't use Raster Fonts or Disable ClearType

We're going for aesthetics and standardization, here. Consider these two screenshots. The first has ClearType off. Notice the blocky capital A, for example.

Lousy bitmapped text

Next, the same shot with ClearType on.

Nice antialiased text

Don't Over-Annotate or use wacky Callout Effects

Another great screenshot program is SnagIt from TechSmith. I use their Camtasia product for all my screencasts. As great as SnagIt is, it has the powerful ability to create "callouts" easily. Too easily.

Don't use callouts. May God have mercy on your soul for using them.

Don't get me wrong, SnagIt is an awesome tool. But just don't point it at your face. Avoid callouts, and when you do, stay classy.

A classy and subtle callout

Use ALT text

Try to use ALT text for all your screenshots. There's a blind person (or a hundred) reading your blog. Do them a favor and put in some nice descriptive ALT text on your screenshots. I like to leave them personal messages that you never see. It takes only a second, but it lives in your post forever and helps the visually impaired participate.

Don't forget to squish your PNGs

PNG may be a lossless format but you can often still squeeze 5-30% of the size out of them with tools like PNGOut. This is a must-have tool in your path. I add PNGOut as a post-build step when I make tutorials and you can even hook up Window Clippings to run it for you after a screenshot. It is CPU intensive, but it's worth the effort when publishing your content. Go do it now, get all the PNGs from your blog, run PNGGauntlet on them (it'll take a while) and compare the directories. You'll save tens of megs if you're like me, and your readers will reap the benefits every time they visit your site.


So, rolling all this advice up, here's a good screenshot and a bad one.

Bad Example

Here's a common example that completely bad. This screenshot is:

  • Using the Basic Theme
    • It was likely taken on a Virtual Machine that didn't have Aero turned on.
  • Not Transparent
    • The window corners are curved, but there's a corner pixel.
  • Oddly cropped to fit
    • The right side is missing, but just a bit. Either chop a lot, or none. Don't chop a little.
  • Poorly resized
    • Note the trouble resizing the words "Installed Templates"
      Notice the aspect ratio is ever-so-slightly wrong.
  • JPEG'ed
    • Note the lossy artifacts under the selection in the listbox.
  • Poorly Staged
    • Note the highlight in the listbox is gray? That means the window didn't have focus when the screenshot was taken. It makes it hard to see the point of the screenshot.

Bad Screenshot

Good Example

Good Screenshot

Or, given our self-imposed width limitation of 600 pixels, perhaps:

Better Screenshot

I hope this guide helps you, Dear Reader, if you create screenshots as a part of your job.

Please, care about your screenshots as much as you care about your text.

"If a picture is worth a thousand words, a crappy screenshot is a thousand misspelled words." - Me, Just now. Again.

Enjoy!

Related Links

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 260 - .NET API design that optimizes for Programmer Joy with Jonathan Carter

April 7, '11 Comments [4] Posted in Learning .NET | Podcast
Sponsored By

Conery, Hanselman and HappinessScott sits down with Jonathan Carter to  brainstorm about optimizing APIs for programmer happiness, rather than programmer productivity.

Download: MP3 Full Show

Links:

NOTE: If you want to download our complete archives as a feed - that's all 260 shows, subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

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 our 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 and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX,MVC,Silverlight, Windows Forms and WPF. Enjoy developer tools like .NET Reporting,ORM,Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visitwww.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

Spring 2011 Fiction Reading List - Young Adult eBooks Will Save Science Fiction

April 5, '11 Comments [27] Posted in Musings
Sponsored By

image I haven't done a Reading List blog post in a few years now. I used to do them with some regularity but full off lately. Interestingly, I'm still reading about a book a week pretty consistently since I got the a Kindle . The Kindle is a direct one-way link between my wallet and Jeff Bezos' bank account. I've literally found myself reading the covers of books in airport bookstores then buying them on the Kindle. The battery life is insane (weeks) and since the last update, I can even use the 3G overseas.

Young Adult eBooks Will Save Science Fiction

I've been a big sci-fi reader my whole life, and recently I've felt I've been running out. I've read all the classics, re-read the classic classics, and enjoyed some of the recent releases. However, where I've really found innovation is in the "Young Adult Market." These books are mostly for the older teen set, and not just the ones that like vampires and werewolves. So much of Young Adult Fiction is Science Fiction, but while it's some of the most read fiction on the market today, it's not being formally recognized by the old guard, either critically or with awards.

Here's some of the books I've read in the last few months. Many are multi-part series. I recommend ALL these books. I've not included the ones that I've read that suck. That said, I pay attention to reviews and avoid the suck. I have had pretty good luck. I've read more great books and had more fun reading in the last year than I can remember in the last ten years.


Everlost (The Skinjacker Trilogy) Nick and Allie don’t survive the car accident, but their souls don’t exactly get where they’re supposed to go either. Instead, they’re caught halfway between life and death, in a sort of limbo known as Everlost: a shadow of the living world, filled with all the things and places that no longer exist. It’s a magical, yet dangerous place where bands of lost kids run wild and anyone who stands in the same place too long sinks to the center of the Earth. When they find Mary, the self-proclaimed queen of lost souls, Nick feels like he’s found a home, but Allie isn’t satisfied spending eternity between worlds. Against all warnings, Allie begins learning the “Criminal Art” of haunting, and ventures into dangerous territory, where a monster called the McGill threatens all the souls of Everlost. In this imaginative novel, Neal Shusterman explores questions of life, death, and what just might lie in between.
Everfound (The Skinjacker Trilogy) While Mary lies in a glass coffin aboard a ghost train heading west, her minions are awaiting her re-awakening by bringing lots of new souls into Everlost to serve her. Meanwhile Jackin’ Jill has met Jix, a fur-jacker—a skin jacker who can take over the bodies of animals, most notably jaguars. Jix serves a Mayan god who collects Everlost coins, and has his own agenda. In the concluding volume of The Skinjacker Trilogy, Neal Shusterman reveals new sides of the characters of Everlost, who are pitted against each other in a battle that may destroy all life on Earth.
The Maze Runner (Maze Runner Trilogy, Book 1) When Thomas wakes up in the lift, the only thing he can remember is his first name. His memory is blank. But he’s not alone. When the lift’s doors open, Thomas finds himself surrounded by kids who welcome him to the Glade—a large, open expanse surrounded by stone walls.Just like Thomas, the Gladers don’t know why or how they got to the Glade. All they know is that every morning the stone doors to the maze that surrounds them have opened. Every night they’ve closed tight. And every 30 days a new boy has been delivered in the lift. Thomas was expected. But the next day, a girl is sent up—the first girl to ever arrive in the Glade. And more surprising yet is the message she delivers. Thomas might be more important than he could ever guess. If only he could unlock the dark secrets buried within his mind.
The Scorch Trials (Maze Runner Trilogy, Book 2) Solving the Maze was supposed to be the end. No more puzzles. No more variables. And no more running. Thomas was sure that escape meant he and the Gladers would get their lives back. But no one really knew what sort of life they were going back to.In the Maze, life was easy. They had food, and shelter, and safety . . . until Teresa triggered the end. In the world outside the Maze, however, the end was triggered long ago.Burned by sun flares and baked by a new, brutal climate, the earth is a wasteland. Thomas can only wonder—does he hold the secret of freedom somewhere in his mind? Or will he forever be at the mercy of WICKED?
The Hunger Games In the ruins of a place once known as North America lies the nation of Panem, a shining Capitol surrounded by twelve outlaying districts. The Capitol is harsh and cruel and keeps the districts in line by forcing them all to send one girl and one boy between the ages of twelve and eighteen to participate in the annual Hunger Games, a fight to the death on live TV. Sixteen-year-old Katniss Everdeen, who lives alone with her mother and younger sister, regards it as a death sentence when she is forced to represent her district in the Games. But Katniss has also resolved to outwit the creators of the games. To do that she will have to be the last person standing at the end of the deadly ordeal, and that will take every ounce of strength and cunning she has.
Catching Fire (The Hunger Games, Book 2) Against all odds, Katniss Everdeen has won the annual Hunger Games with fellow district tribute Peeta Mellark. But it was a victory won in defiance of the Capitol and its harsh rules. Katniss and Peeta should be happy. After all, they have just won for themselves and their families a life of safety and plenty. But there are rumors of rebellion among the subjects, and Katniss and Peeta, to their horror, are the faces of that rebellion. The Capitol is angry -- and now it wants revenge. Full of plot twists, this riveting sequel to the New York Times bestseller is guaranteed to keep young readers on the edge of their seats!
Mockingjay (The Final Book of The Hunger Games) Against all odds, Katniss Everdeen has survived the Hunger Games twice. But now that she’s made it out of the bloody arena alive, she’s still not safe. The Capitol is angry. The Capitol wants revenge. Who do they think should pay for the unrest? Katniss. And what’s worse, President Snow has made it clear that no one else is safe either. Not Katniss’s family, not her friends, not the people of District 12. Powerful and haunting, this thrilling final installment of Suzanne Collins’s groundbreaking The Hunger Games trilogy promises to be one of the most talked about books of the year.
I Am Number Four Nine of us came here. We look like you. We talk like you. We live among you. But we are not you. We can do things you dream of doing. We have powers you dream of having. We are stronger and faster than anything you have ever seen. We are the superheroes you worship in movies and comic books—but we are real.Our plan was to grow, and train, and become strong, and become one, and fight them. But they found us and started hunting us first. Now all of us are running. Spending our lives in shadows, in places where no one would look, blending in. we have lived among you without you knowing. I am Number Four.

Other great books I've read or re-read lately that I highly recommend.

Fledgling The story of an apparently young, amnesiac girl whose alarmingly unhuman needs and abilities lead her to a startling conclusion: She is in fact a genetically modified, 53-year-old vampire. Forced to discover what she can about her stolen former life, she must at the same time learn who wanted-and still wants-to destroy her and those she cares for and how she can save herself. Recipient of a MacArthur Foundation "genius" grant, the Nebula Award, the Hugo Award, and numerous other literary awards, Octavia Butler has been acclaimed for her lean prose, strong protagonists, and social observations that range from the distant past to the far future.
Kindred Dana, a modern black woman, is celebrating her twenty-sixth birthday with her new husband when she is snatched abruptly from her home in California and transported to the antebellum South. Rufus, the white son of a plantation owner, is drowning, and Dana has been summoned to save him. Dana is drawn back repeatedly through time to the slave quarters, and each time the stay grows longer, more arduous, and more dangerous until it is uncertain whether or not Dana's life will end, long before it has a chance to begin.
Blind Lake Robert Charles Wilson, says The New York Times, "writes superior science fiction thrillers." His Darwinia won Canada's Aurora Award; his most recent novel, The Chronoliths, won the prestigious John W. Campbell Memorial Award. Now he tells a gripping tale of alien contact and human love in a mysterious but hopeful universe.At Blind Lake, a large federal research installation in northern Minnesota, scientists are using a technology they barely understand to watch everyday life in a city of lobster like aliens upon a distant planet. They can't contact the aliens in any way or understand their language. All they can do is watch.Then, without warning, a military cordon is imposed on the Blind Lake site.
Spin One night in October when he was ten years old, Tyler Dupree stood in his back yard and watched the stars go out. They all flared into brilliance at once, then disappeared, replaced by a flat, empty black barrier. He and his best friends, Jason and Diane Lawton, had seen what became known as the Big Blackout. It would shape their lives. The effect is worldwide. The sun is now a featureless disk--a heat source, rather than an astronomical object. The moon is gone, but tides remain. Not only have the world's artificial satellites fallen out of orbit, their recovered remains are pitted and aged, as though they'd been in space far longer than their known lifespans. As Tyler, Jason, and Diane grow up, a space probe reveals a bizarre truth: The barrier is artificial, generated by huge alien artifacts. Time is passing faster outside the barrier than inside--more than a hundred million years per year on Earth. At this rate, the death throes of the sun are only about forty years in our future. Jason, now a promising young scientist, devotes his life to working against this slow-moving apocalypse.
Agent to the Stars The space-faring Yherajk have come to Earth to meet us and to begin humanity’s first interstellar friendship. There’s just one problem: They’re hideously ugly and they smell like rotting fish.So getting humanity’s trust is a challenge. The Yherajk need someone who can help them close the deal.Enter Thomas Stein, who knows something about closing deals. He’s one of Hollywood’s hottest young agents. But although Stein may have just concluded the biggest deal of his career, it’s quite another thing to negotiate for an entire alien race. To earn his percentage this time, he’s going to need all the smarts, skills, and wits he can muster.
Camouflage Two aliens have wandered Earth for centuries. The Changeling has survived by adapting the forms of many different organisms. The Chameleon destroys anything or anyone that threatens it. Now, a sunken relic that holds the key to their origins calls to them to take them home--but the Chameleon has decided there's only room for one.
Marsbound A novel of the red planet from the Hugo and Nebula Award–winning author of The Accidental Time Machine and Old Twentieth.Young Carmen Dula and her family are about to embark on the adventure of a lifetime—they’re going to Mars. Once on the Red Planet, however, Carmen realizes things are not so different from Earth. There are chores to do, lessons to learn, and oppressive authority figures to rebel against. And when she ventures out into the bleak Mars landscape alone one night, a simple accident leads her to the edge of death until she is saved by an angel—an angel with too many arms and legs, a head that looks like a potato gone bad, and a message for the newly arrived human inhabitants of Mars: We were here first.
Starbound (A Marsbound Novel) A New from the Hugo, Nebula, and John W. Campbell Award-winning author of Marsbound. Carmen Dula and her husband have spent six years travelling to a distant solar system that is home to the enigmatic, powerful race known as "The Others," in the hopes of finding enough common purpose between their species to forge a delicate truce. By the time Carmen and her party return, fifty years have been consumed by relativity-and the Earthlings have not been idle, building a massive flotilla of warships to defend Earth against The Others. But The Others have more power than any could imagine-and they will brook no insolence from the upstart human race.
Replay Jeff Winston, forty-three, didn't know he was a replayer until he died and woke up twenty-five years younger in his college dorm room; he lived another life. And died again. And lived again and died again -- in a continuous twenty-five-year cycle -- each time starting from scratch at the age of eighteen to reclaim lost loves, remedy past mistakes, or make a fortune in the stock market. A novel of gripping adventure, romance, and fascinating speculation on the nature of time, Replay asks the question: "What if you could live your life over again?"
Room: A Novel  In many ways, Jack is a typical 5-year-old. He likes to read books, watch TV, and play games with his Ma. But Jack is different in a big way--he has lived his entire life in a single room, sharing the tiny space with only his mother and an unnerving nighttime visitor known as Old Nick. For Jack, Room is the only world he knows, but for Ma, it is a prison in which she has tried to craft a normal life for her son. When their insular world suddenly expands beyond the confines of their four walls, the consequences are piercing and extraordinary. A stunning and original novel of survival in captivity, readers who enter Room will leave staggered, as though, like Jack, they are seeing the world for the very first time.


Related Links

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 259 - Remote Eclipse/Java Development using TFS at Microsoft with Martin Woodward

April 5, '11 Comments [0] Posted in Podcast
Sponsored By

Team Explorer Everywhere Scott talks to Martin Woodward, a Microsoft Program Manager who lives and works in Northern Ireland on the Java-based Eclipse plugin for Team Foundation Server. Martin Woodward is the Program Manager for Visual Studio Team Explorer Everywhere and part of the Team Foundation Server group at Microsoft. He helps to ensure that Eclipse and cross-platform developers are an active part of the TFS eco-system.

Download: MP3 Full Show

Links:

NOTE: If you want to download our complete archives as a feed - that's all 259 shows, subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

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 our 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 and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX, MVC,Silverlight, Windows Forms and WPF. Enjoy developer tools like .NET Reporting,ORM,Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visitwww.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

NuGet Package of the Week #4 - Deserializing JSON with Json.NET

April 1, '11 Comments [20] Posted in Javascript | NuGet | NuGetPOW | Open Source
Sponsored By

Hey, have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.2, Setup Automatic Updates, Get NuGet Package Explorer. NuGet 1.2 is out, so make sure you're set to automatically update!

The Backstory: I was thinking since the NuGet .NET package management siteis starting to fill up that I should start looking for gems (no pun intended) in there. You know, really useful stuff that folks might otherwise not find. I'll look for mostly open source projects, ones I think are really useful. I'll look at how they built their NuGet packages, if there's anything interesting about the way the designed the out of the box experience (and anything they could do to make it better) as well as what the package itself does.

Json.NET is a popular high-performance JSON framework for .NET

If you're moving data around on the web, you'll eventually come upon JSON (JavaScript Object Notation) or as I like to call it, XML with curly braces. (Kidding) (No, I'm not kidding, you can easily convert between XML and JSON in most cases)

It's a lightweight data-interchange format. "It is easy for humans to read and write. It is easy for machines to parse and generate." It's also just JavaScript.

image

From JSON.ORG:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Basically stuff is either a name/value pair, or a list of stuff. That's it. It's great way to push data around, and since it's so flexible and works with JavaScript, it has become THE way to access many popular APIs for sites like Twitter and Facebook.

Json.NET is James Newton-King's excellent library for accessing and working with JSON on .NET. The 4.0 release is cool not only because it's in NuGet, but also because it's currently the best way to deal with JSON data structures on the Windows Phone. Json.NET is notable particularly for James' obsessive focus on performance (check the charts and graphs!) It's also been around FOREVER. I blogged about Json.NET in 2006, in fact.

Inside the Json.NET NuPkg

If you open up the Newtonsoft.Json.4.0.1.nupkg using the NuGet Package Explorer (that's a ClickOnce link, son) I can learn a lot about how James has packaged up his library.

NuGet Package Explorer - Newtonsoft.Json.4.0.1 (15)

First, notice now he's got a number of folders under his /lib folder. I talked about this a little with the last NuGet Package of the Week, but James has taken it to the max. Kudos to him!

With NuGet, you can have one package that includes versions of assemblies for many different Framework Versions. Check the NuGet documentation on Supporting Multiple .NET Framework Versions and Profiles.

James has create a single NuGet package for Json.NET that does the right thing for .NET 2.0, 3.5, 4, SL4, and the Windows Phone 7. Nice.

One thing I think James should add is a Newtonsoft.Json.Sample package per David Ebbo's post "Take NuGet to the next level with sample packages." I found myself wondering where to start with Json.NET as there was no sample code included. No worries, to the cloud web! James has amazing documentation on Json.NET on his site.

Using Json.NET

I've got this silly little site called SmallestDotNet.com that will look at your system using your Browser's UserAgent (and some JavaScript) to determine what version of .NET you have, and suggest the smallest possible download for you to up to date.

NOTE: This SmallestDotNet site was launched in 2008 but was broken on IE9 until my new friend Calinoiu Alexandru Nicolae from Romania (@CalinBalauru on Twitter) volunteered to fix it. Big thanks to Calin for his work on the SmallestDotNet site! Work is ongoing.)

The site also has a simple JSON payload that will give you the correct direct link to the right download for you. I never understood why it was so hard to get a direct download for .NET, so we put it in a basic JSON payload so you could access it programmatically.

The SmallestDotNet JSON payload looks like this. It's not very sophisticated, but it is what it is.

{
"latestVersion": null,
"allVersions": [

],
"downloadableVersions": [
{
"major": 4,
"minor": 0,
"profile": "client",
"servicePack": null,
"url": "http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=5765d7a8-7722-4888-a970-ac39b33fd8ab"
},
{
"major": 4,
"minor": 0,
"profile": "full",
"servicePack": null,
"url": "http://www.microsoft.com/downloads/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992&displaylang=en"
},
{
"major": 3,
"minor": 5,
"profile": "client",
"servicePack": 1,
"url": "http://www.microsoft.com/downloads/details.aspx?FamilyId=8CEA6CD1-15BC-4664-B27D-8CEBA808B28B&displaylang=en"
},
{
"major": 3,
"minor": 5,
"profile": "full",
"servicePack": 1,
"url": "http://go.microsoft.com/fwlink/?LinkId=124150"
},
{
"major": 3,
"minor": 0,
"profile": "full",
"servicePack": 1,
"url": "http://www.microsoft.com/downloads/details.aspx?FamilyId=10CC340B-F857-4A14-83F5-25634C3BF043&displaylang=en"
},
{
"major": 2,
"minor": 0,
"profile": "full",
"servicePack": 2,
"url": "http://www.microsoft.com/downloads/details.aspx?familyid=5B2C0358-915B-4EB5-9B1D-10E506DA9D0F&displaylang=en"
},
{
"major": 1,
"minor": 1,
"profile": "full",
"servicePack": 1,
"url": "http://www.microsoft.com/downloads/details.aspx?FamilyID=a8f5654f-088e-40b2-bbdb-a83353618b38&DisplayLang=en"
}
]
}

Maybe I can access it with Json.NET? I wonder if it'll be easy or hard. There's a number of ways I can do it. This one uses the JObject "DOM" in JSON.NET:

var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response = client.DownloadString(new Uri("http://www.hanselman.com/smallestdotnet/json.ashx"));
JObject o = JObject.Parse(response);'
//Now o is an object I can walk around...

Or, I can make C# classes that LOOK like the shape of my JSON payload and deserialize directly into them, which is cool:

class Program
{
static void Main(string[] args)
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody"); //my endpoint needs this...
var response = client.DownloadString(new Uri("http://www.hanselman.com/smallestdotnet/json.ashx"));

var j = JsonConvert.DeserializeObject<SmallestDotNetThing>(response);
}

public class SmallestDotNetThing
{
public DotNetVersion latestVersion { get; set; }
public List<DotNetVersion> allVersions { get; set; }
public List<DotNetVersion> downloadableVersions { get; set; }
}

public class DotNetVersion
{
public int major { get; set; }
public int minor { get; set; }
public string profile { get; set; }
public int? servicePack { get; set; }
public string url { get; set; }
}
}

Now, look at the j variable in this screenshot. How cool is that?

The JSON has deserialized into C# objects in a Watch Window

There's lots of choices on how you want to consume your JSON with .NET.

New Json.NET Features

The new Json.NET is compiled on .NET 4, and includes some really cool dynamic support. From James' blog, see how things used to work, and how the new C#4 dynamic keyword makes working with JSON more fun.

JObject oldAndBusted = new JObject();
oldAndBusted["Name"] = "Arnie Admin";
oldAndBusted["Enabled"] = true;
oldAndBusted["Roles"] = new JArray(new[] { "Admin", "User" });

string oldRole = (string) oldAndBusted["Roles"][0];
// Admin


dynamic newHotness = new JObject();
newHotness.Name = "Arnie Admin";
newHotness.Enabled = true;
newHotness.Roles = new JArray(new[] { "Admin", "User" });

string newRole = newHotness.Roles[0];
// Admin

This is really an amazing open source library and I encourage you to check it out if you're doing anything at all with JSON, and maybe throw JamesNK a few coins for his efforts. Thanks, James!

Another Json Library: JsonFx 2.0

If you're really interested in ways to consume JSON using C# dynamics, also check out JsonFx 2.0 on GitHub or JsonFx on NuGet! This library is extremely easy to use with dynamics.

Check out how this simple code:

dynamic foo = new JsonFx.Json.JsonReader().Read(response);

Gets you this result...note that is a C# dynamic typed object:

JSON deserialized into a DYNAMIC

Very nice. Enjoy!

Related Links

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.