Scott Hanselman

Catching RedBits differences in .NET 2.0 and .NET 2.0SP1

October 15, 2007 Comment on this post [6] Posted in ASP.NET | Learning .NET | Microsoft | Programming
Sponsored By

When you install .NET 3.5 on your system, while the .NET CLR is the same and runs the same, there's some additional Properties and Methods that were added to the Base Class Libraries in order to make some 3.5 features like LINQ work as well as fix a few customer issues.

Daniel Moth has a very nice diagram explaining what "RedBits" and "GreenBits" mean.

"When we say red bits, those are Framework bits that exist in RTM today i.e. NetFx v2.0 and NetFx v3.0...When we say green bits, we mean brand new assemblies with brand new types in them. These are simply adding to the .NET Framework (not changing or removing) just like Fx 3.0 was simply adding to v2.0 without changing existing assemblies and without changing the CLR engine."

Krzysztof has a blog post about these new (kinda obscure) APIs and fortunately a nice FxCop Rule you can drop into your C:\Program Files\Microsoft Visual Studio 9.0\Team Tools\Static Analysis Tools\FxCop\Rules folder and you'll get a nice warning if you bump into one of these APIs. To be clear, they are not something you'll bump into in your regular life, but it's possible. Dan Moseley blogged about this from the MSBUILD point of view.

The situation you might get into would be that you'd develop on a Visual Studoi 2008 system with .NET 3.5 and targeted .NE T Framework 2.0 (but you have 2.0 SP1 with these new 2.0 methods), then you deploy to an older system that has only .NET 2.0 RTM (not Service Pack'ed). At this point you might get a MethodMissingException because that older system might not have the new method or property. Of course, you could just install the latest 2.0, but if you don't want to, then don't use the new methods/types/properties. Hence the optional FxCop Rule.

1473897382_374fc28d10_o

Krzysztof send me a text file with the list of new Properties and Methods and I wrote a little program to generate an HTML file that shows the additions (many are new overloads) and links them to MSDN help. I couldn't get to the exact method overloads so do make sure the parameters line up when you're reading the help.

http://www.hanselman.com/blog/content/binary/RedBitsChangesv2.html

NOTE: This is a different list from the original diff I did between 3.5 and 2.0. The original list was the differences between all of 2.0 and 3.5 and this list is JUST the BCL. Just the core.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

If your method can't do what it's name promises it can, throw

October 15, 2007 Comment on this post [19] Posted in ASP.NET | Learning .NET | Microsoft | Programming
Sponsored By

Patrick Cauldwell has a good list of Programming Guiding Principles he calls This I Believe: The Developer Edition. I've blogged about them before.

I got an email today that went something like this:

I have an interface called IStorageConnection and one of its methods is Save(...). The storage connection object available to user is configured through configuration files. The storage could be either the FileSystem or the Database. In that case, how is the consumer of the IstorageConnection interface going to know that exceptions to expect? If using the FileSystem, you can expect an IOException. If using the Database, you can expect a SQLException. Given this case, how can the customer get away from handling the base Exception and only handle specific exceptions. Also, keep in mind that other storage connections objects can be deployed and plugged into the system in the future.

This reminded me of a favorite rule of Patrick's that use a lot as well.

Simply stated, we say "If your method can't do what it's name promises it can, throw."

If your method is called "Save" and it can't Save, then throw. If it's called DoSomething and it can't DoSomething, throw. The idea is that the method name is a verb and a contract. It's promising to do its best and if it can't do it, it's very likely exceptional.

In this gentleman's example, I figure if you've got a pluggable storage interface underneath, I'd suggest creating a generic "StorageException," and put the actual exception in the InnerException property. However, the point is that it didn't work. Whether the consumer of the Exception cares more than that is a secondary issue.

What are your rules for when to throw and Exception? And please, don't say Exceptions are evil and that HResults should rule the day. Surely the Great .NET Exception Panic of 2001 is over, right? ;)

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Retrospective: Halo 3 Fights Diabetes

October 13, 2007 Comment on this post [4] Posted in Diabetes | Gaming
Sponsored By

It was epic. Truly epic. Thfe stuff you tell, if not your grandchildren, your middle-aged nerdy neighbor about. We had a great time at Cinetopia and raised a lot of money for the American Diabetes Association.

You can make a tax-deductible donation today!

Big Thanks to Everyone involved:

  • Jason Mauer and Microsoft Portland for the Xboxes, the Halo 3 games, organization, logistics and his tireless work and two 42" plasmas.
  • Rich Claussen for all things business, negotiations, and convincing Cinetopia we had a good idea.
  • Greg Hughes for his press-contacting expertise and for spreading the word in creative ways in the Oregonian, the Willamette Week and on KXL radio.
  • The SAO for their sponsorship and for all their help the evening of the event!
  • John Poore, Michael Willits, Jennifer Bernstein and everyone at Robert Half Technology for their sponsorship and their commitment to the community!
  • Wendy Fatz and Rodger DeGeorge from CompView for believing in the dream and loaning us two projectors.
  • Lee Williamson and PADNUG for the Food and Drinks!
  • Aivea for their sponsorship and generous donation!
  • Rudyard and the team at Cinetopia, a locally-owned rockin' sweet luxury theatre, for shutting down 2 of their 8 Super-HD screens!

And lastly, to everyone who donated and everyone who was powned or dispensed pownage all evening long!

CIMG7547 CIMG7542 

CIMG7523 CIMG7519 

CIMG7518 CIMG7517

CIMG7516 CIMG7511

Let's do it again 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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanselminutes Podcast 84 - Concurency Programming with .NET Parallel Framework Extensions

October 12, 2007 Comment on this post [4] Posted in ASP.NET | LINQ | Microsoft | Podcast | Programming
Sponsored By

image My eighty-fourth podcast is up. Scott chats on the Microsoft campus with Stephen Toub, a Microsoft Developer working on a team coming up with new ways to make concurrency programming easier with .NET. We get pretty deep and pretty philosophical about concurrency, threading, and parallelism. Also check out an older Channel 9 Video (just released) on the topic as well.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

If you have trouble downloading, or your download is slow, do try the torrent with µtorrent or another BitTorrent Downloader.

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.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

The Weekly Source Code 7

October 12, 2007 Comment on this post [8] Posted in ASP.NET | Learning .NET | Programming | Source Code
Sponsored By

In my new ongoing quest to read source code to be a better developer, I now present the seventh in an infinite number of a weekly series called "The Weekly Source Code." Here's some source I'm reading this week that I enjoyed.

I got a little sidetracked the recent trip to the ALT.NET conference, so forgive me for missing last week.

  • Joe Cheng's Schwartzian Transform in C# 3.0 - Whenever someone knows the official name for technique, be it in chess or in code, they're usually smarter than I. "You are using Bonetti's Defense against me, ah?" Joe is one of those guys. ;)
    "What’s a Schwartzian Transform? It’s a way of efficiently sorting a list of objects according to some potentially expensive-to-calculate property of those objects. For example, let’s say you have an array of filenames, and you want to sort them by their last modified dates"
    This is a very useful technique to know and nice and clean in C# 3.0.
  • public static List<TElement> SortBy2<TElement, TSortBy>(
            this List<TElement> coll,
            Converter<TElement, TSortBy> converter,
            Comparison<TSortBy> comparison)
        {
            return coll
                .ConvertAll(el => new { Key = converter(el), Value = el })
                .Sort((a, b) => comparison(a.Key, b.Key))
                .ConvertAll(x => x.Value);
        }
  • LINQ to Amazon - This is a little old, but it's still darn interesting to read. If you've been thinking about implementing LINQ over an object or web service that your company has, this is a good place to start. I'll let you go digging around, but here's some bits I found interesting. Note also that the code is very old and I haven't been able to find the latest stuff.
    This is what I call Left-Hand/Right-Hand code where we're pulling with one hand, in this case XML and handing off with the other hand, in this case, making a LINQ List.  It tends to be very tedious but LINQ sure makes it easy.
  • XNamespace ns = NAMESPACE_AWSECommerceService; 
    var books = from book in booksDoc.Descendants(ns+"Item") 
        select new Book { 
            Title = book.Element(ns+"ItemAttributes").Element(ns+"Title").Value, 
                                Publisher = book.Element(ns+"ItemAttributes").Element(ns+"Publisher").Value, 
                                Year = uint.Parse(((String)book.Element(ns+"ItemAttributes").Element(ns+"PublicationDate").Value).Substring(0, 4)), 
                                Authors = ( from author in book.Descendants(ns+"Author") 
            select (String) author.Value ).ToList() 
    };
  • Argotic Syndication Framework - Woof, a full implementation of Atom 1.0, OPML 2.0, RSD 1.0, and RSS 2.0 syndication formats. If you're looking for syndication source look no further. This is not only very clean code that's also well organized with a very interesting extension mechanism for including other namespaces within your syndication format.  It's also excessively well documented. I hate them. ;) Although, I'm not sure where the tests are, it's pretty clear that this reflects a huge amount of work.  Or a lot of code generation.
    There is far too much to paste much here, but what are the things I click away was a new attribute but I hadn't heard of yet. You can tell FxCop to relax as they do here with a naming rule.
  • [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rss")]
    public class RssFeedCreatedEventArgs : EventArgs, IComparable {...
  • LukeH and a fully LINQified RayTracer - Seriously, someone give this guy some money or a warm handshake or something. This is unreal...it's single line of LINQ. That means it's one expression. Luke is a glutton for punishment because I'm still trying to get my brain around the statement. This guy is a beast. I'm thinking of starting a cult around him. Here's his code, but go read his post for the explanation. Go! Right now! I'll wait here.
  • var pixelsQuery =
        from y in Enumerable.Range(0, screenHeight)
        let recenterY = -(y - (screenHeight / 2.0)) / (2.0 * screenHeight)
        select from x in Enumerable.Range(0, screenWidth)
               let recenterX = (x - (screenWidth / 2.0)) / (2.0 * screenWidth)
               let point = Vector.Norm(Vector.Plus(scene.Camera.Forward,                                                Vector.Plus(Vector.Times(recenterX, scene.Camera.Right),
                                                               Vector.Times(recenterY, scene.Camera.Up))))
               let ray = new Ray { Start = scene.Camera.Pos, Dir = point }
               let computeTraceRay = (Func<Func<TraceRayArgs, Color>, Func<TraceRayArgs, Color>>)
                (f => traceRayArgs =>
                 (from isect in
                      from thing in traceRayArgs.Scene.Things
                      select thing.Intersect(traceRayArgs.Ray)
                  where isect != null
                  orderby isect.Dist
                  let d = isect.Ray.Dir
                  let pos = Vector.Plus(Vector.Times(isect.Dist, isect.Ray.Dir), isect.Ray.Start)
                  let normal = isect.Thing.Normal(pos)
                  let reflectDir = Vector.Minus(d, Vector.Times(2 * Vector.Dot(normal, d), normal))
                  let naturalColors =                   from light in traceRayArgs.Scene.Lights
                      let ldis = Vector.Minus(light.Pos, pos)
                      let livec = Vector.Norm(ldis)
                      let testRay = new Ray { Start = pos, Dir = livec }
                      let testIsects = from inter in
                                           from thing in traceRayArgs.Scene.Things
                                           select thing.Intersect(testRay)
                                       where inter != null
                                       orderby inter.Dist
                                       select inter
                      let testIsect = testIsects.FirstOrDefault()
                      let neatIsect = testIsect == null ? 0 : testIsect.Dist
                      let isInShadow = !((neatIsect > Vector.Mag(ldis)) || (neatIsect == 0))
                      where !isInShadow
                      let illum = Vector.Dot(livec, normal)
                      let lcolor = illum > 0 ? Color.Times(illum, light.Color) : Color.Make(0, 0, 0)
                      let specular = Vector.Dot(livec, Vector.Norm(reflectDir))
                      let scolor = specular > 0 
                                   ? Color.Times(Math.Pow(specular, isect.Thing.Surface.Roughness), light.Color) 
                                   : Color.Make(0, 0, 0)
                      select Color.Plus(Color.Times(isect.Thing.Surface.Diffuse(pos), lcolor),
                                        Color.Times(isect.Thing.Surface.Specular(pos), scolor))
                  let reflectPos = Vector.Plus(pos, Vector.Times(.001, reflectDir))
                  let reflectColor =                   traceRayArgs.Depth >= MaxDepth
                      ? Color.Make(.5, .5, .5)
                      : Color.Times(isect.Thing.Surface.Reflect(reflectPos), 
                                    f(new TraceRayArgs(new Ray { Start = reflectPos, Dir = reflectDir }, 
                                                       traceRayArgs.Scene,                                                    traceRayArgs.Depth + 1)))
                  select naturalColors.Aggregate(reflectColor, (color, natColor) => Color.Plus(color, natColor)))                                  .DefaultIfEmpty(Color.Background).First())
               let traceRay = Y(computeTraceRay)
               select new { X = x, Y = y, Color = traceRay(new TraceRayArgs(ray, scene, 0)) };
    
    foreach (var row in pixelsQuery)
        foreach (var pixel in row)
            setPixel(pixel.X, pixel.Y, pixel.Color.ToDrawingColor());

Feel free to send me links to cool source that you find hasn't been given a good read.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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