Scott Hanselman

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

October 12, '07 Comments [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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

The Weekly Source Code 7

October 11, '07 Comments [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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

ScottGu MVC Presentation and ScottHa Screencast from ALT.NET Conference

October 9, '07 Comments [78] Posted in ASP.NET | ASP.NET MVC | Microsoft | Programming | Ruby | Screencasts | Silverlight | Speaking
Sponsored By
ScottHaOnDLRandMVCatALTNET

I attended the ALT.NET Conference last weekend in Austin, TX. I personally find the name "Alt" as in "Alternative" too polarizing and prefer terms like "Pragmatic.NET" or "Agile.NET." At the conference I suggested, partially in jest, that we call it "NIH.NET" as in "Not Invented Here.NET." ;)

Ultimately this is a group that believes in:

  • Continuous Learning
  • Being Open to Open Source Solutions
  • Challenging the Status Quo
  • Good Software Practices
  • DRY (Don't Repeat Yourself)
  • Common Sense when possible

I asked "Why is this alternative," and Martin Fowler echoed those sentiments. When I was at Corillian we were using NAnt, NUnit, Subversion, NCover, NDoc, NDepend, CruiseControl, Watir/Watin and Ruby and we practiced Scrum with an Agile Coach. Did that make us alternative or were we just getting the job done? We made practical and pragmatic decisions and it worked out OK.

Whether this is Alternative .NET or just Practical .NET, it's a conversation and that's a a good thing.

ScottGuOnMVCatALTNETScottGu gave an hour long presentation on the upcoming MVC Framework and I took some guerilla video. ScottGu's presentation is here in Silverlight and it's about 60 minutes long. Considering it's so long, the video squished nicely.

This was the first time the MVC Framework was shown publicly.  Note that this was a Prototype, not the Production code and both ScottGu and I make that point a number of times to drive home that it's early. Some of the code was written on a plane, just to give you an idea.

After The Gu did his piece on the MVC Framework, I showed some prototype hacking that I'd done over the previous few days along with some work Phil Haack did. My presentation is here as Silverlight and it's about 30 minutes long. I showed the Model View Controller with Controllers in IronPython and an IronPython view using a WebFormViewEngine. Then I talked about the possibilities of alternate ViewEngines and showed Phil Haack's prototype RubyViewEngine.

Both talks show lots of code. Of course, this is prototype madness. No warranty, express or implied. Features come and go, but I hope this shows that we're committed to aiming for as much awesomeness as is humanly possible. I hope you enjoy them, even though my webcam hand was shaky after an hour. I used a new Microsoft NX-7000 Lifecam for the recoding - it's a great camera for the Alpha Geek. ;)

Here's the videos I promised:

If you want to link to these, link to this post, not those links, as the videos might move around. Thanks.

Here's some of the buzz around the new Framework. I hope this framework is a harbinger of things to come in future frameworks.

Things are looking up.

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

REMINDER: Register TODAY for the Fight Diabetes with Halo 3 Big Screen Party

October 9, '07 Comments [3] Posted in Diabetes | Gaming
Sponsored By

Just a reminder if you're in Portland or SW Washington that now is the time to register for the Halo at Cinetopia for Diabetes Party. You need to pre-register and please, do tell your friends and family! Let's fill it up!

WHAT

We're renting out TWO SUPER HIGH DEF (2048p) 50 foot Movie Theaters and playing Halo. There will be soda and popcorn and pownage. Eighteen and older please.

WHERE

The Glory and Wonder that is Cinetopia just over the bridge in Vancouver.

WHEN

The event is this Thursday, October 11th from 7pm to Midnight.

HOW

Your donation of $25 or more at the door will go straight to the America Diabetes Association. You can also pre-donate and bring your printed receipt to the door. We have room for only 120 people so register today!

Register for this event at http://iammasterchief.com/ with the RSVP code "FIGHTDIABETES". The event is Thursday, October 11th from 7pm to Midnight.

Note that the banner in the upper left of the reservation site does mention the “PRELAUNCH PARTY 09 24 07” even though the center box shows “10/11/07 – Cinetopia”. Just make sure to use the right RSVP code.

WHY

Because it's Halo. And to Fight Diabetes.

We'll see you there!

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

Mixing Languages in a Single Assembly in Visual Studio seamlessly with ILMerge and MSBuild

October 6, '07 Comments [13] Posted in ASP.NET | Microsoft | Programming | XML
Sponsored By

I really like the new LINQ to XML direct language support in VB9. However, while it's cool, I'm not ready (or willing) to dump C# and start using VB. But, if I could only use VB9 just for the XML stuff...

Sure, I could create a VB assembly and a C# assembly and add them to a solution, but then I'd have two assemblies. I could add a PostBuildEvent batch file and call ILMerge myself (merging the two assemblies into one), but that just doesn't seem pure enough.

solutionWhat I really want is to be able to mark an assembly as merge-able and have it automatically merged in just because it's referenced.

Here's what I came up with. Thanks to Dan Moseley and Joshua Flanagan for their help. Thanks to Jomo Fisher for the Target File.

First, here's the sample project. There's a C# MergeConsole.exe that references a C# MainLibraryILMerge.dll that references a VB XmlStuffLibrary.

If I compile it as it is, I get a folder structure that includes three resulting assemblies.

folder1

Now, here's were we start messing around. Remember, we don't want to have the extra VB-specific XmlStuffLibrary right? We just want to use the XML features.

First, download and install ILMerge in the standard location.

Now, go to C:\Program Files\MSBuild (or C:\Program Files (x86)\MSBuild on x64) and make a new text file called "Ilmerge.CSharp.targets". This file is the start of a hack we're going to borrow from Jomo Fisher.

Note the red bits in the file below. We're creating an "AfterBuild" target...a Post Build Event in the MSBUILD world.

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">   <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> 
    
  <Target Name="AfterBuild">
    <CreateItem Include="@(ReferencePath)" Condition="'%(CopyLocal)'=='true' and '%(ReferencePath.IlMerge)'=='true'">
      <Output TaskParameter="Include" ItemName="IlmergeAssemblies"/>
    </CreateItem>
    <Message Text="MERGING: @(IlmergeAssemblies->'%(Filename)')" Importance="High" />
    <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(IlmergeAssemblies->'&quot;%(FullPath)&quot;', ' ')" />
  </Target>
  <Target Name="_CopyFilesMarkedCopyLocal"/>
</Project>

In this target, we're going to look for assemblies that are marked CopyLocal but also that have IlMerge equal to true. Then we'll call IlMerge passing in those referenced assemblies.

Is this some undocumented MSBUILD thing? No, you can put whatever you want in an MSBUILD file and refer to it later. Since CSPROJ files (Visual Studio Projects) are MSBUILD files, we can open it in Notepad.

Open the CSPROJ for the C# project that references the VB one and make these changes: 

... 
<ItemGroup>
   <ProjectReference Include="..\XmlStuffLibrary\XmlStuffLibrary.vbproj">  
    <Project>{someguid}</Project>    
    <Name>XmlStuffLibrary</Name>
    <Private>True</Private>
    <IlMerge>True</IlMerge>
  </ProjectReference>
</ItemGroup>  
<Import Project="$(MSBuildExtensionsPath)\Ilmerge.CSharp.targets" />
<!-- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> -->
...

At the bottom there, we're commenting out Microsoft.CSharp.targets (but notice that it's included back in at the top of the new  Ilmerge.CSharp.targets.

Then a totally made-up element <IlMerge> is added. That's the most important part. We're saying we want this specific Reference (or References) merged into the final assembly. This made-up element is referenced in the conditional "'%(ReferencePath.IlMerge)" above in the AfterBuild.

The addition of this IlMerge element to Jomo's original hack gives me the flexibility to pick which references I want to merge in, and in my specific case, I'll use the VB9 new XML hotness inside my C# assemblies. Schwing.

Close and save. If you're running Visual Studio, switch back there and it'll prompt you to Reload your project file.Because we've messed it it, you'll get this warning dialog. Select "Load project normally" and click OK.

Security Warning for MainLibraryILMerge

At this point we can build either from the command-line using MSBUILD on the Solution (SLN) file, but more importantly we can (of course) build from inside Visual Studio.

MergeConsole - Microsoft Visual Studio

You can see the output in the Output Window in VS.NET.

MERGING: XmlStuffLibrary
"C:\Program Files (x86)\Microsoft\Ilmerge\Ilmerge.exe"
  /out:bin\Debug\MainLibrary.dll "obj\Debug\MainLibrary.dll"   
  "C:\dev\CSharpVBTogetherAtLast\MergeConsole\XmlStuffLibrary
  \bin\Debug\XmlStuffLibrary.dll"

And the results in the bin folder:

folder2

Looks like the VB XmlStuffLibrary is gone! But where it is? Let's load up MainLibrary in Reflector:

reflector1

Looks like they are both in there. To refresh, if I want to merge in VB assemblies:

  • Change the referencing CSPROJ to import "IlMerge.CSharp.targets"
  • Add <IlMerge>True</IlMerge> to the references you want merged in.
  • Save, Reload, Build

C# and VB, living together, mass hysteria!

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.