Scott Hanselman

Dealing with Images with Bad Metadata - Corrupted Color Profiles in WPF

July 30, '10 Comments [4] Posted in Bugs | Windows Client | WPF
Sponsored By

Creating a Twitter client is a really interesting exercise in application development because, amongst many reasons, it's taking input from effectively an infinite number of people and places. Never trust user input, right? Input to your application comes not only in the form of text, but also images. Writing a Twitter client is effectively writing a web browser that only browses one website. Getting a browser stable is hard.

Long Zheng, Raphael Rivera and the MetroTwit team (MetroTwit is a lovely new Twitter client) have hit an extremely interesting crashing bug. The input comes in the form of a corrupted JPG image from the web.

Here's the bad image. Looks like a picture some folks speaking on a panel. However, even though this image looks fine, this specific binary version of it has a corrupted Color Profile.

Sometimes folks don't realize that image formats contain lots of metadata that you can't see. Your JPGs may show what camera you used, what lens, what settings, possibly even the geo-coordinates of where you took the picture!

You can view all this extended information (EXIF) with a number of tools. A great free one is ExifTool by Phil Harvey at the command line, or a non-command line one like ExifPro. Windows Live Photo Gallery lets you view the data also.

Here's a snippet of some of the info in this pic:

Device Mfg Desc                 : IEC http://www.iec.ch
Device Model Desc               : IEC 61966-2.1 Default RGB colour space - sRGB
Viewing Cond Desc               : Reference Viewing Condition in IEC61966-2.1
Viewing Cond Illuminant         : 19.6445 20.3718 16.8089
Viewing Cond Surround           : 3.92889 4.07439 3.36179
Viewing Cond Illuminant Type    : D50
Make                            : Leica Camera AG
Camera Model Name               : M8 Digital Camera
Software                        : Aperture 3.0.2
Shutter Speed Value             : 1/256
Exposure Compensation           : 0
Max Aperture Value              : 1.0
Metering Mode                   : Center-weighted average
Light Source                    : Flash
Focal Length                    : 0.0 mm

You can extract the image profile (ICC Profile) from an image like this with exiftool:

exiftool -icc_profile -b foo.jpg > profile.icc

If you're hardcore, you can get the Windows Imaging Component (WIC) Tools and run WICExplorer. WPF uses WIC to decode images. WICExplorer will report the error with this image as you load it.

Loading Images in WPF

When you're using WPF (Windows Presentation Foundation) to display an image on Windows, you might do something like this:

<Image Width="300" Height="300" ImageFailed="Image_ImageFailed">
<Image.Source>
<BitmapImage UriSource="http://hanselman.com/blog/images/JPGwithBadColorProfile.jpg"/>
</Image.Source>
</Image>

Except with this particular image, I'll get an exception the Color Profile (the image metadata) is corrupted. "ArgumentException: Value does not fall within the expected range." This is a corrupted file.

at System.Windows.Media.ColorContext.GetColorContextsHelper(GetColorContextsDelegate getColorContexts)
at System.Windows.Media.Imaging.BitmapFrameDecode.get_ColorContexts()
at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
at System.Windows.Media.Imaging.BitmapImage.OnDownloadCompleted(Object sender, EventArgs e)
at System.Windows.Media.UniqueEventHelper.InvokeEvents(Object sender, EventArgs args)
at System.Windows.Media.Imaging.LateBoundBitmapDecoder.DownloadCallback(Object arg)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

If I get this exception, I can try to load the image again and ignore its color profile. Here's how I'd do that in XAML:

<Image Width="300" Height="300" ImageFailed="Image_ImageFailed"  >
<Image.Source>
<BitmapImage CreateOptions="IgnoreColorProfile" UriSource="http://hanselman.com/blog/images/JPGwithBadColorProfile.jpg"/>
</Image.Source>
</Image>

If you're loading from code, you can ignore color profile information by adding the BitmapCreateOptions.IgnoreColorProfile flag to CreateOptions.

As an aside, Andrew Eichacker has a nice post on how to read all the BitmapMetadata in WPF. There's lots in there!

Here's loading the Bitmap into an image Control called "Foo."

var bi = new BitmapImage();
bi.BeginInit();
bi.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
bi.UriSource = new Uri("http://hanselman.com/blog/images/JPGwithBadColorProfile.jpg");
bi.EndInit();

foo.Source = bi;

Knowing about possible corruption is important to be aware of, especially if you're loading arbitrary images from all over the place. If you don't care about color profiles, I'd just ignore them by default in your image loading code. If you are writing an image editor or you care about profiles, I'd catch the exception, let the user know, then load the image again without the profile.

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

Microsoft "Daily Build" Nerd Dinner - August 4th in Seattle, Redmond

July 30, '10 Comments [9] Posted in ASP.NET | IIS | NerdDinner
Sponsored By

Are you in King County/Seattle/Redmond/Bellevue Washington and surrounding areas? Are you a huge nerd? Perhaps a geek? No? Maybe a dork, dweeb or wonk. Maybe you're in town for an SDR (Software Design Review) or VSLive! Quite possibly you're just a normal person and a member of the general public.

We're holding a Nerd Dinner (it's like dinner, except with nerds) next week on Weds, Aug 4th at Crossroads Bellevue Mall Food Court at 6pm.

This one will be different from usual. Why?

It's a Daily Build Nerd Dinner!

We'll have Program Managers and Developers directly from Microsoft who'll bring their laptops with "Daily Builds" of stuff they are working on. Daily Builds mean literally stuff they've built that day that's cool. You'll give them feedback and they'll show you cool new stuff like the Razor View Engine and Visual Studio Tooling.

If you are a member of the public, be here!

Nerd Dinners are for us. All are welcome. Just come on by. We'll be near the Chess Board in the Food Court. Bring your co-workers and your social media friend!

Please spread the word! RSVP and tweet about this dinner at http://nrddnr.com/2770

Add to your calendar now...here's an iCal link for your Outlook or other calendar.

See you soon!

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

Windows Phone 7 - First Impressions

July 29, '10 Comments [43] Posted in WinPhone
Sponsored By

Windows Phone EmulatorDisclaimer: I work for Microsoft in MSDN. I don't work for or with the Windows Phone 7 team in any capacity. I do know one guy over there, though. That said, I personally have an iPhone 3G (dead, the kids play Monkey Island on it), a iPhone 3GS (the wife won't use it, it's on a shelf) and an iPhone 4 (my non-work phone). I also have a work Samsung Blackjack (WinMo 6.5). I signed up and paid for a Windows Phone 7 developer account and I have ideas for 3 apps. No one has asked me to blog about the phone, my opinions are my own. Also, this is a developer prototype with whatever build they shipped it with.

A Windows Phone 7 developer phone showed up in the mail today. Inside the battery door it said "MS Asset" so it looks like I won't be able to keep it. Still, it's cool. I pulled the MicroSIM out of my iPhone 4 and shoved it, ungracefully, into the normal-sized SIM slot and while it's not kosher, it totally works. I'll go get an converter/adapter at some point.

Here's some things I was impressed with:

  • Windows Live, Google, Yahoo, and Exchange are all peers. I was able to add my work Exchange account, my own Gmail (Google Apps), my wife's email and Google Calendar, and my Windows Live in less than 5 minutes. I customized the calendar colors as well.
  • When I added Windows Live, it automatically figured out I had Xbox and downloaded my Avatar and Achievements. This was particularly cool because I had just won "Limbo" the night before and my little Avatar dude had a Limbo T-shirt on.
  • My wife's Zune Pass just worked. Leasing music rocks. I put 6 gigs of music and podcasts on it.
  • There's a dedicated camera button (this is apparently in the hardware spec) so one button gets  you a 5 megapixel camera with flash.
  • The screen is really clear. I don't know the DPI (maybe 200?) but the typography/fonts aliases really nicely.
  • Speech recognition for Bing Search is nice and tiny Excel, Word and PowerPoint are cool.
  • Everything is extremely "fluid' and smooth. I was worried when I saw things at Mix 10 stuttering. I didn't see any of that on this hardware.
  • The browser doesn't suck at all, actually. This was a pleasant surprise. It's speedy and useful. I wish that when the pages got pinn'ed to the home page that it used the iphone-touch-icon.png or some kind of favicon rather than a thumbnail of the page though.

Some things I had trouble with:

  • I have 568 Windows Live Contacts and >3500 Facebook Contacts, so integrating these was a mistake. It took the phone 20 minutes in the background (I didn't realize it was doing in) to put all my "friends" in a Contact List. That's what I get for not keeping Facebook for just friends. Even then, assuming I had a few hundred "friends" I'm trying to figure out how many "frequently dialed" phone numbers I'd want to keep, vs. internet friends.  How many friends do normal people have on Facebook? I'm still trying to figure out the usage pattern for this. I'm not sure how I can use the People Hub without un-friending 3000 people
  • I miss my must-have apps. Hopefully they are listening...
    • FourSquare
    • Evernote
    • Remember the Milk
    • No twitter client yet. This is crippling me.
    • Kindle
  • The ringtones and alarms are really ethereal. I need a jangly and jarringly classic old rotary phone alarm. I'll need to figure out custom ringtones.
  • No copy-paste. Yet.
  • The fine-tuned-hold-the-cursor-to-select gesture currently requires you to hold to select, then move down to move a floating-above-you selection iBar.
  • I haven't figured out how to "mount" the phone in Windows Explorer and look at my photos. That said, it appears they automatically show up in My Photos in a folder called "From <My Phone's Name>" and they can optionally be automatically uploaded to the web. There's a lot of "it just works" stuff going on. I'm used to everything being configurable.

It'll take a while to get used to "it just works" from Microsoft. All in all, I'm pleasantly surprised as everything has just worked.

The wife thought it was cool too, although she wants a hardware keyboard that flips out. Apparently Dell is making one like that. I keep forgetting that the software and the hardware are separate. I am looking forward to seeing what HTC does with this. Those guys are nuts.

I took a few moments and filmed some guerilla video of me exploring the phone. Again, this is just the build that was mailed to me today, not the final stuff.

Windows Phone 7 - June 29th - Walkthough of Developer Phone from Scott Hanselman on Vimeo.

In my spare time, I'm going to be working on BabySmash for WP7, as well as a Diabetes application and maybe a few others. You can get the free developer tools at http://developer.windowsphone.com and sign up to sell your apps as well. I'm optimistic. This is quite a bit cooler than I expected. Looking forward to what's next.

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

Ultimate Developer PC 2.0 - Part 3 - UPDATE on Building a WEI 7.9 and RFC for building a GOM (God's Own Machine)

July 27, '10 Comments [28] Posted in Hardware | Podcast
Sponsored By
Big Ass Mobo As a reminder, if you're just turning in, here's our glossary:

  • WEI - Windows Experience Index. How fast is your machine? If you say "I've got a WEI 6.0" you've got a good machine, for example.
  • RFC - Request for Comments. This is crowdsourcing. I want to know what YOU think we need to do to make a machine that is so fast that it'll max out at WEI 7.9 and be a GOM.
  • GOM - God's Own Machine. If the Good Lord had a computer, it'd be a 7.9. We want to build that machine.

There have been two posts so far:

There were lots of great comments on both posts, and arguably there is more content in the comments than the posts! I want to give a big thank you to all the thoughtful people who have commented. You all know more than I do about this topic.

The point of this exercise is several-fold.

  • First, I haven't built a machine in 3 years, since the first Ultimate PC, lead by Jeff Atwood. Every Jedi should build their own lightsaber.
  • Second, it'd be interesting to see if it's easy (or how hard) to get a 7.9 WEI (the current maximum) on a machine given a $3000 limit. It's also interesting to see what a $1000 PC gets. Yes, we all realize that WEI is just one benchmark, but it's a public one and it's built into Windows, so it's interesting.
  • Third, I am not much of a gamer (I have a Xbox for that) but I do run several large 24" to 30" monitors and don't like waiting for my Windows to repaint, so do like a faster video card.

Here's some scores, some results, and some commentary.

Baseline. My Laptop.

This is the WEI my stock Lenovo W500 8Gb with an aftermarket OCZ Vertex 256gig SSD.

My W500 is a 4.6.

Using Visual Studio 2010 and building the trunk of the NerdDinner project (a smallish sized ASP.NET app) is about 3 to 4 seconds. On my new PC, building NerdDinner from scratch happens before I can say "one one-thousand." I could try it from MSBuild and the command line...

Measuring Commands with PowerShell

Here's a better way to measure. Taking Chris Tavares' vsvars32.ps2, changed slightly for Visual Studio 2010 and run under PowerShell x86, I add this to my local machine's Microsoft.PowerShell_profile.ps1. (As well as running "set-executionpolicy unrestricted" as admin. Or set it to whatever you like).

function Get-Batchfile ($file) {
$cmd = "`"$file`" & set"
cmd /c $cmd | Foreach-Object {
$p, $v = $_.split('=')
Set-Item -path env:$p -value $v
}
}

function VsVars32($version = "10.0")
{
$key = "HKLM:SOFTWARE\Microsoft\VisualStudio\" + $version
$VsKey = get-ItemProperty $key
$VsInstallPath = [System.IO.Path]::GetDirectoryName($VsKey.InstallDir)
$VsToolsDir = [System.IO.Path]::GetDirectoryName($VsInstallPath)
$VsToolsDir = [System.IO.Path]::Combine($VsToolsDir, "Tools")
$BatchFile = [System.IO.Path]::Combine($VsToolsDir, "vsvars32.bat")
Get-Batchfile $BatchFile
[System.Console]::Title = "Visual Studio " + $version + " Windows Powershell"
}

Thanks to Chris, now I can type "VsVars32" at any PowerShell prompt and I'm immediately setup with a Visual Studio Command Line environment. Just as an FYI, while MSBuild does report timings, since I'm using PowerShell, I can surround any command with "measure-command" as in.

measure-command { msbuild /t:rebuild .\NerdDinner.sln }

In this case from the command line, NerdDinner takes 1900ms on my laptop and 900ms on my desktop, so this isn't a good test as the app is far too small.

Of course, I can also run msbuild with the /m switch and get parallel builds on multi-core machines. However, since NerdDinner only has two projects, I only get a 10% performance increase. Let's try a more significant project.

The Upfront Conclusion: How about building yesterday's release of NHibernate 3.0 Alpha?

Here's the results, building NHibernate 3.0 Alpha using NHibernate.Everything.sln:

Times are in seconds Lenovo W500 w/ SSD Ultimate PC 1.0 Ultimate PC 2.0
MSBuild /t:rebuild 36.05 35.52 16.12
MSBuild /t:rebuild /m 24.98 25.57 12.53
MSBuild 6.17 6.99 3.11
MSBuild /m 5.91 6.66 2.72

Interesting that last year's laptop is very competitive with the original "Ultimate PC" from 2007 (still a beefy Quad Core) due to the laptop's new SSD.

Still, against the best numbers the new PC is effectively twice as fast or more at everything. Yesterday I was encoding a large HD video for Channel 9 and while the Lenovo took 3 hours, the new Ultimate PC 2.0 took 15 minutes. In some cases, it'll save hours on computationally intensive tasks, I believe. Additionally, for computationally intensive multi-tasking that have caused me to use multiple computers in the past, this machine has handled easily. For example, while I was encoding that video, I was also streaming live 720p HD video over Office Communicator. This takes at least 2 procs working full and slowed my Ultimate PC 1.0 down to the point of uselessness. The aggregate CPU on the new machine never went above 12% while just streaming video.

While I did go overboard on the Video Card, I'm extremely happy with the computer so far. I threw in an NVidia GTX275 I had laying around to run another 22" monitor while the GTX480 is running the 30" and a 24". The GTX480 does run hot. For you, dear reader, a GTX275 or any decent $100 card would do you just fine and you'd save a lot of money.

Here's the final parts list along with some caveats. Remember, building your own PC does come with risks, as you're sometimes putting together different companies parts and things don't always work perfectly. You can get a great 7.x WEI machine for $1000 from just about anyone.

The Parts List

Also, Shay Erlichmen wrote some Google Apps Javascript and put up a LIVE Google Spreadsheet that will scrape NewEgg's site and put up the current total of all the components. Thanks to Shay!

The Build

I built the case over two 4 hour sessions and broadcasted live to 80 of my close internet friends on UStream. A lot of really smart people helped me out on this build and offered a lot of interesting points.

The first day build went bad because of the power supply issue so we got it built, then spent hours thinking it was a motherboard issue. It was the power supply.

After we assembled the machine and before we installed any drivers, here was the first WEI score. The 1.0s happened because the standard VGA driver loaded.

1.0 WEI

After installing the Intel Chipset drivers for the Motherboard and the latest NVidia drivers, we were at 7.8 for video and 7.4 all up with the SSD holding us back.

 7.4 WEI

I moved the SSD to another SATA port as this motherboard has multiple SATA chipsets (Intel, Marvel) and installed the latest drivers. In one case, setting the BIOS to IDE instead of AHCI seemed to stick me at 5.9 for disk.

 5.9 WEI

Once I moved onto the Marvel SATA 3 controller with 6 GB/s I got 7.9 on disk. Interestingly the same drive on the Intel SATA 2 controller gets 7.7. The Marvel gets 310MB/s out of the Crucial SSD while the Intel controller gets 270MB/s.

7.8 WEI 

At this point, running everything stock and air-cooled, I have a nice 7.8 machine. I suspect I won't be able to get the Processor to 7.9 without overclocking to 4Ghz. As it is, the machine is running lovely. I wouldn't mind overclocking but I have decided against water cooling as I'm just too old and I need a machine to work 100% of the time. Pete Brown will be water cooling his, he says, so I'll be following his build. That said, if anyone wants to sit with me and chat about if it's possible to get this machine to 4Ghz using air-cooling, give me a holler. As for the graphics, I don't see how I can get to 7.9 without something drastic.

All in all, a great time was had by all. Thanks so much to everyone who helped and to all the wonderful (and waspish) commenters who made this a better experience.

Related Links:

Obligatory Taskman Screenshot!

12 procs in Taskman

Woohoo!

.

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

ASP.NET MVC 3 Preview 1 Released – Channel 9 Video and Hanselminutes Podcast 224, Oh My!

July 27, '10 Comments [4] Posted in ASP.NET | ASP.NET MVC | Channel9 | Podcast | VS2010
Sponsored By

Phil and friends released ASP.NET MVC 3 Preview 1 today. I snuck into the office of Phil Haack and Morgan the Canadian Intern to talk about the release of ASP.NET MVC 3 Preview 1 and some of the cool "futures" stuff that Morgan (and our fleet of interns) is working on. This video isn't only about MVC as Morgan's working on some cool CSS Sprites stuff that works nicely in WebForms that you should check out as well.

image

Also, my two-hundred-and-twenty-fourth podcast is up and I talk more in depth with, yes, you guessed, it, Phil Haack. More detail in a less shaky-camera format.

What's new in ASP.NET MVC 3?

Note that installing ASP.NET MVC 3 won't mess up your ASP.NET MVC 2 applications.

  • Razor Syntax View Engine - Cleaner view syntax
  • Dynamic View and ViewModel properties - passing data between controllers and views using dynamic rather than a dictionary
  • "Add View" Dialog Box Supports Multiple View Engines - You two can be in this box.
  • Service Location and Dependency Injection Support - Get your DI hooked into controller factories, dependency injection, action filters and View Pages.
  • Global Filters - put filters on the all control methods
  • New JsonValueProviderFactory Class - Model bind directly to JSON-encoded data
  • Support for .NET Framework 4 Validation Attributes and IValidatableObject - Easier validation including validating one property based on another.
  • New IClientValidatable Interface - Discovering at runtime if the client supports validation.
  • Support for .NET Framework 4 Metadata Attributes - Support .NET 4 specific attributes like DisplayAttribute
  • New IMetadataAware Interface - Write your own attributes to contribute to the ModelMetadata creation process.
  • New Action Result Types - HttpNotFoundResult, HttpStatusCodeResult.
  • Permanent Redirect - More easily return 301s for Actions, Routes or any URL.

ASP.NET MVC Preview 1 Link Round-Up

Telerik is our sponsor for this show.

Hansel_Promo

Hanselminutes podcasts listeners can get $50 off any Telerik product this summer. All interested listeners should drop an email to podcast@telerik.com and mention the Hanselminutes promo and their sales team will reply with the special $50-off coupon code.

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. Visit  www.telerik.com.

Enjoy!

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.