comments suggest edit

Unbelievable!

Another blog linked to this post and mentioned watching the video up to the slow motion practice session.  Be sure to keep watching past it to see the woman juggling a soccer ball, while playing double dutch, with a flaming soccer ball and jump rope.  Ronaldinho never did that!

comments suggest edit

With the Subtext 1.9 release just around the corner, this is probably a good time to highlight some minor, but important, changes to skinning in Subtext.

We made some breaking changes to Skins.config file format to make the naming more consistent with the purpose.  There was a lot of confusion before.  The following is a snippet from a pre-Subtext 1.9 Skins.config file.

<?xml version="1.0"?>
<SkinTemplates xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Skins>
    <SkinTemplate SkinID="RedBook" 
                    Skin="RedBook" 
                    SecondaryCss="Red.css">
      <Scripts>
        <Script Src="~/Admin/Resources/Scripts/niceForms.js" />
      </Scripts>
      <Styles>
        <Style href="niceforms-default.css" />
        <Style href="print.css" media="print" />
      </Styles>
    </SkinTemplate>
  </Skins>
</SkinTemplates>

And here is how that snippet will change in Subtext 1.9.

<?xml version="1.0"?>
<SkinTemplates xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Skins>
    <SkinTemplate Name="RedBook" 
                  TemplateFolder="RedBook" 
                  StyleSheet="Red.css">
      <Scripts>
        <Script Src="~/Admin/Resources/Scripts/niceForms.js" />
      </Scripts>
      <Styles>
        <Style href="niceforms-default.css" />
        <Style href="print.css" media="print" />
      </Styles>
    </SkinTemplate>
  </Skins>
</SkinTemplates>

The key differences are in the SkinTemplate element. The following attributes have been renamed:

  • SkinID was changed to Name
  • Skin was changed to TemplateFolder
  • SecondaryCss was changed to StyleSheet

Another new change is that the Style element now supports a new attribute named conditional. If specified, Subtext will wrap the stylesheet declaration with an IE specific conditional comment. This is commonly used for stylesheets that contain IE specific CSS hacks. For example…

<Style href="IEHacks.css" conditional="if ie" />

Gets rendered as…

<!--[if ie]>
<Style href="IEHacks.css" conditional="if IE" />
<![endif]-->

Thus only IE will see that style declaration.

tags: Subtext, Skinning, Skins, Blogs

subtext, open source comments suggest edit

In my previous post, I outlined some minor changes to the skinning model for Subtext. In this post, I will give a high level overview of how skinning works in Subtext.

Subtext renders a Skin by combining a set of CSS stylesheets with a set of .ascx controls located in a specific skin folder.  If you look in the Skins directory for example, you might see a set of folders like this.

Subtext Skin
Folders.

Skin Template

A common misperception is that each folder represents a Skin.  In fact, each folder represents something we call a Skin Template, and can be used to render multiple skins.  One way to think of it is that each folder contains a family of skins.

Each folder contains a series of .ascx controls used to render each skin in that skin family as well as some CSS stylesheets and images used for individual skins or for the entire family.

For example, the Redbook template folder contains three skins, Redbook, BlueBook, and GreenBook.  In the screenshot below, we can see that there are three CSS stylesheets that specifically correspond to these three skins.  How does Subtext know that these three stylsheets define three different skins while the other stylesheets in this folder do not?

Redbook
Folder

The answer is that this is defined within the Skins.config file.

Skins.config

The Skins.config file is located in the Admin directory and contains an XML definition for every skin.  Here is a snippet of the file containing the definition for the Redbook family of skins. This snippet shows the definition of the BlueBook skin.

<?xml version="1.0"?>
<SkinTemplates  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Skins>
    <SkinTemplate Name="BlueBook" 
                  TemplateFolder="RedBook" 
                  StyleSheet="Blue.css">
      <Scripts>
        <Script Src="~/Admin/Resources/Scripts/niceForms.js" />
      </Scripts>
      <Styles>
        <Style href="~/skins/_System/csharp.css" />
        <Style href="~/skins/_System/commonstyle.css" />
        <Style href="~/skins/_System/commonlayout.css" />
        <Style href="niceforms-default.css" />
        <Style href="print.css" media="print" />
        </Styles>
    </SkinTemplate>
  </Skins>
</SkinTemplates>

There is a SkinTemplate node for each Skin within the system (I know, not quite consistent now that I think of it. Should probably be named Skin). 

The Name attribute defines the name of this particular skin. 

The TemplateFolder attribute specifies the physical skin template folder in which the all the ascx controls and images are located in. 

The StyleSheet attribute specifies which stylesheet defines the primary CSS stylesheet for this skin. 

For example, the GreenBook skin definition looks just like the BlueBook skin definition except that the StyleSheet attribute references Green.css instead of Blue.css.

Within the SkinTemplate node is a collection of Script nodes and a collection of Style nodes.  These specify any client scripts (such as Javascript) and other CSS files that should be included when rendering this skin.  As you can see, the tilde (~) syntax works for specifying a path to a file and a developer can specify a media and a conditional for each CSS stylesheet.

Controls

I keep mentioning that Subtext depends on a collection of .ascx user controls when it renders a family of skins. Let’s talk about them for a moment. 

In the second screenshot above, you may have noticed a directory named Controls.  This contains the bulk of the .ascx controls used to render a specific skin.  There was also a control named PageTemplate.ascx in the parent directory.

The
Controls

Each skin in a family of skins is rendered by the same set of UserControl instances.  The only difference between two skins within the same family is the CSS stylesheet used (which can account for quite a difference as we learn from CSS Zen Garden).

The PageTemplate.ascx control defines the overall template for a skin, and then each of these user controls in the Controls directory is responsible for archiving a specific portion of the blog.

Select a different skin from another skin family, and Subtext will load in a completely different set of UserControl files, that all follow the same naming convention.

Drawbacks and Future Direction

This is one of the drawbacks to the current implementation.  For example, rather than using data binding syntax, each .ascx file is required to define certain WebControl instances with specific IDs.  The underlying Subtext code then performs a FindControl searching for these specific controls and sets their values in order to populate them.  This naming convention is often the most confusing part of implementing a new skin for developers.

It used to be that if a WebControl was removed from an .ascx file (perhaps you didn’t want to display a particular piece of information), this would cause an exception as Subtext could not find that control. We’ve tried to remedy that as much as possible.

In the future, we hope to implement a more flexible MasterPage based approach in which the underlying code provides a rich data source and each skin can bind to whichever data it wishes to display via data binding syntax.

From a software perspective, this changes the dependency arrow in the opposite direction.  Rather than the underlying code having to know exactly which controls a skin must provide, it will simply provide data and it is up to the individual skin to pick and choose which data it wishes to bind to.

Conclusion

We provided the Naked skin so that developers creating custom skins could play around with an absolutely bare-bone skin and see just how each of the controls participates in rendering a blog.

tags: Subtext, Skins, Skinning, Blogs

comments suggest edit

This is my third post about Skinning in Subtext. Previously I talked about some breaking changes.  Then I gave a high level overview of skinning in Subtext.  In this post I want to mention one new feature for those who use custom skins.

Subtext 1.9 actually reduces the the number of pre-packaged skins that come with it out of the box.  That’s right, we got rid of the skins that screamed, “Hey! I was designed by a developer who wears plaid pants with flannel shirts!”.  Over time, we hope to add more polished designs.

Of course we don’t want to leave developers with custom developer designed skins out in a lurch.  Taking an informal poll I found that a majority of Subtext users deploy a custom skin typically based on one of the out-of-the-box skins. 

As I described in the overview, skins are configured via a file named Skins.config.  One problem with having all the skin definitions in this file is that any customizations a user might make are overwritten when upgrading to a new version of Subtext.

It is incumbent upon the user to merge new changes in.  We thought we could make this better so we have introduced the new Skins.User.config file.

The format for this file is exactly the same as the format for Skins.config.  The only difference is that we do not include such a file in the Subtext distribution.  Thus you can place your custom skin definitions in this file and it will not get overwritten when upgrading.

From now on, it is recommended that if you customize an existing skin, you should rename the folder and place your skin definition in Skins.User.config.

tags: Subtext, Skins, Skinning, Blogs

comments suggest edit

Gratuitious nature pic for no good reason other than I love Windows
Live
WriterJust sticking my head above water long enough to take a breath and to link to some rubbish called the Programmer’s Bill of Rights that Jeff Atwood declares on his blog.

I don’t understand this guy.  You let this sort of dangerous propaganda spread and software departments will become much more efficient and be able to build better systems with less money. 

You realize what that means, don’t you?  Companies will be able to get more done with less people

For those who lose their jobs because of this, blame Atwood.  Then again, if you’re reading his blog, you’re probably not the target audience that would get laid off due to increased efficiency.  Readers of my blog on the other hand …

comments suggest edit

This post is an ode to one of my favorite, albeit extremely minor, additions to .NET 2.0.  This is the method that I am sure we have all written in some sort of StringHelper library of some sort, but are now glad it is included in the framework as it makes our code a tad bit cleaner and shuts up that pesky FxCop warning about using the length of the string to test for empty strings.

And under the hood, it does the right thing.

public static bool IsNullOrEmpty(string value)
{
      if (value != null)
      {
            return (value.Length == 0);
      }
      return true;
}

If you haven’t met this method, do get well acquainted.

comments suggest edit

Tonight we had our first game of the new season against Hollywood United who now feature Alexi Lalas and Frank Le Boeuf, among several other former pro and national team players.  Let’s just say the result wasn’t pretty.  At least not pretty for us as they dismantled us 12 to 0.

As bad a beating as it was, it was exciting to be playing against such a high caliber team.  And we managed to put together some good plays, but pretty much looked erratic and rushed with the ball.

I asked one of my teammate’s wife to take some photos, but being a night game, none of them turned out too well.  Here is the best I got showing both these players.

Frank and Alexi on the
Pitch

I had one good play in which I dummied the ball, faking Alexi and taking him out of the play as he was hot on my back (I know, I’m reaching here).  Of course later in the game, he embarrassed me with a nutmeg.

After the game we were chatting with a player from their team who is going to be in a new TV show called Heros.  He told us his superpower in the show was that if he touches you he paralyzes you.  Now we know what happened on the field.

Next game we hope to hold them to single digits.  We’re in need of a keeper if you know any former standout keepers.

comments suggest edit

Stephen Colbert of Comedy Central’s The Colbert Report is in my opinion the funniest comedian on television right now. As Mugatu (played by Will Ferrell, the funniest comedian in movies) would say, “It’s that damn Stephen Colbert! He’s so hot right now! Stephen Colbert.”

This clip had me rolling on the floor laughing for its spot on parody of Dungeons and Dragons. It is probably funnier to those of us who geeked out with D&D back in the day than for the unitiated.

After watching it, one gets the sense that he really was a player. It turns out he is a true fan, based on this Gamespy report.

comments suggest edit

Interesting post on the 37Signals blog regarding competing against Google.  Harb references a post by Paul Graham about Kiko’s founders putting their site up on eBay. 

Long story short, it sounds like Kiko came out with a web-based calendar, but when Google came out with theirs, Kiko’s growth stopped, users defected, and they threw in the towel.

Paul’s solution is to stay out of Google’s way.

Kind of sounds like what could happen to Blogjet with the advent of Windows Live Writer.  However Harb offers a more optimistic take on the events.

No. Don’t run, don’t hide. Be different. You can’t outdo Google by trying to match them point-by-point, but you don’t have to. There are other, better ways to fight. Compete differently.

Perhaps the same can be said for the creator of BlogJet vs Microsoft.  I was chatting with Jon Galloway about this and I suggested this would really hurt BlogJet, perhaps even spell its demise in the long run.  How does a tiny company challenge Microsoft and compete against a free product?  Jon was more optimistic and pointed to SourceGear as a counterexample.

I was not convinced.  Writing software to post to a blog has a much lower bar of entry compared to a source control system.  But so does writing a Calendar app, no?

It will be interesting to see if Dmitry can competes differently and come out with some creative means to keep Blogjet viable.  Good luck.

comments suggest edit

Work on Subtext 1.9 is progressing well with more and more contributors chipping in. No firm release date yet, but hopefully soon.  The latest builds are pretty stable, but there a few more minor bug fixes to get in there. Also we plan to implement the MetaWeblog API newMediaObject method in order to better support Windows Live Writer.

If you like to live dangerously, you can download one of the latest builds and give it a twirl.  Please note that link is running off of a VMWare Server within a Shuttle box in my office/guest room. So if we have guests, that link is going down for the night.

Of course, should you find a bug, you know the drill.

In the meanwhile, you can track our status by checking out our CruiseControl.NET statistics page.  As you can see, our code coverage from unit tests is steadily climbing, currently at 34%.  There are 23584 lines of code with 1367 FxCop warnings.

comments suggest edit

That is a fine question in need of a good answer.  The answer for implementors is easily found in the spec.  For the rest of us there is the exceedingly sparse entry (at the time of this writing) in Wikipedia.

That entry is somewhat pathetic at the moment. I mean who wrote that crap?! Hmmm.. Well taking a look at the history… I see that the perpetrator was…oh! me.

Well I am sure one of you can do a much better job than I did of elaborating on the topic.

comments suggest edit

Since my blog has been getting a bit geek heavy for my wife’s taste (see comment

Blue
Skies

The above pic was taken by my brother-in-law when the in-laws visited this past spring.

Lazy Sea
Lions

On that same trip, we took a boat ride in Oceanside and took a pic of these orgyastic sea lions. In public no less! Shameful.

comments suggest edit

ChoirIn Jeff Atwood’s latest post entitled Source Control: Anything But SourceSafe he is preaching the gospel message to choose something other than Visual Source Safe and I am screaming amen in the choir section.

There are three common reasons I hear for sticking with Visual Source Crap (I sometimes swap that last word with one that doesn’t break the acronym).

1. It is free!

UPDATE: As a lot of people pointed out, VSS isn’t free. What I meant was that it comes with the MSDN Universal Subscription, so many companies already have a copy of VSS.

So is Subversion.  I was on a project recently in which VSS corrupted the code twice!  The time spent administering to it and time lost was a lot more costly than a license to SourceGear Vault.

2. We know how to use it and don’t want to learn a new system.

When I hear this, what I am really hearing is we like our bad habits and don’t want to spend the time to learn good habits.  Besides, Eric Sink already wrote a wonderful tutorial.

3. We have so much invested in VSS.

Well you had a lot invested in classic ASP (or other such technology) and that didn’t stop you from switching over to ASP.NET (Ruby on Rails, Java, etc…), did it?

The reason I spend time and energy trying to convince clients to switch is that it saves them money and saves me headaches.  It really is worth the effort.

For Open Source projects (or any project that receives user code contributions), Subversion and CVS have the nice benefit of a patching feature making it easy to contribute without having write access.

tags: Source Control

comments suggest edit

Book Oh boy are you in for a roller coaster ride now!

Let me start with a question, How do you iterate through a large collection of data without loading the entire collection into memory?

The following scenario probably sounds quite familiar to you. You have a lot of data to present to the user. Rather than slapping all of the data onto a page, you display one page of data at a time.

One technique for this approach is to define an interface for paged collections like so…

/// <summary>
/// Base interface for paged collections.
/// </summary>
public interface IPagedCollection
{
    /// <summary>
    /// The Total number of items being paged through.
    /// </summary>
    int MaxItems
    {
        get;
        set;
    }
}

/// <summary>
/// Base interface for generic paged collections.
/// </summary>
public interface IPagedCollection<T> 
    : IList<T>, IPagedCollection
{ 
}

The concrete implementation of a generic paged collection is really really simple.

/// <summary>
/// Concrete generic base class for paged collections.
/// </summary>
/// <typeparam name="T"></typeparam>
public class PagedCollection<T> : List<T>, IPagedCollection<T>
{
    private int maxItems;

    /// <summary>
    /// Returns the max number of items to display on a page.
    /// </summary>
    public int MaxItems
    {
        get { return this.maxItems; }
        set { this.maxItems = value; }
    }
}

A method that returns such a collection will typically have a signature like so:

public IPagedCollection<DateTime> GetDates(int pageIndex
    , int pageSize)
{
    //Some code to pull the data from database 
    //for this page index and size.
    return new PagedCollection<DateTime>();
}

A PagedCollection represents one page of data from the data source (typically a database). As you can see from the above method, the consumer of the PagedCollection handles tracking the current page to display. This logic is not encapsulated by the PagedCollection at all. This makes a lot of sense in a web application since you will only show one page at a time.

But there are times when you might wish to iterate over every page as in a streaming situation.

For example, suppose you need to perform some batch transformation of a large number of objects stored in the database, such as serializing every object into a file.

Rather than pulling every object into memory and then iterating over the huge collection ending up with a really big call to Flush() at the end (or calling flush after each iteration, ending up in too much flushing), a better approach might be to page through the objects calling the Flush() method after each page of objects.

The CollectionBook class is useful just for that purpose. It is a class that makes use of iterators to iterate over every page in a set of data without having to load every record into memory.

You instantiate the CollectionBook with a PagedCollectionSource delegate. This delegate is used to populate the individual pages of the data we are iterating over.

public delegate IPagedCollection<T> 
    PagedCollectionSource<T>(int pageIndex, int pageSize);

When iterating over the pages of a CollectionBook instance, each iteration will call the delegate to retrieve the next page (an instance of IPagedCollection<T>) of data. This uses the new **iterators feature of C# 2.0.

Here is the code for the enumerator.

///<summary>
///Iterates through each page one at a time, calling the 
/// PagedCollectionSource delegate to retrieve the next page.
///</summary>
public IEnumerator<IPagedCollection<T>> GetEnumerator()
{
  if (this.pageSize <= 0)
    throw new InvalidOperationException
      ("Cannot iterate a page of size zero or less");

  int pageIndex = 0;
  int pageCount = 0;

  if (pageCount == 0)
  {
    IPagedCollection<T> page 
      = pageSource(pageIndex, this.pageSize);
    pageCount = (int)Math.Ceiling((double)page.MaxItems / 
      this.pageSize);
    yield return page;
  }

  //We've already yielded page 0, so start at 1
  while (++pageIndex < pageCount)
  {
    yield return pageSource(pageIndex, this.pageSize);
  }
}

The following is an example of instantiating a CollectionBook using an anonymous delegate.

CollectionBook<string> book = new CollectionBook<string>(
    delegate(int pageIndex, int pageSize)
    {
        return pages[pageIndex];
    }, 3);

I wrote some source code and a unit test you can download that demonstrates this technique. I am including a C# project library that contains these classes and one unit test. To get the unit test to work, simply reference your unit testing assembly of choice and uncomment a few lines.

Technorati Tags: Tips, TDD, C#, Generics, Iterators

comments suggest edit

There is a lot of buzz around Windows Live Writer.  I Might as well throw my two cents into the fray.  Keep in mind that I do understand this is a beta.

The Good

  • It uses the paragraph tag <p> around your paragraphs rather than <br /> tags.
  • Keyboard shortcuts for switching views.
  • Integrates your blog’s style when previewing.  This is an impressive feature.  When I preview the post I am working on, it displays the post as if it was posted on my site.  I have seen a temporary blog post with the message This is a temporary post that was not deleted. Please delete this manually. (c3eaf4ab-0941-4881-9d17-d4f62bde069e)  in a few blogs related to obtaining a blog’s style. My guess is that Windows Live Writer posts to the blog, then deletes the post.  It takes a diff to figure out what changed.  That’s just my guess.
  • When adding a link, it has a field for the rel tag.  Nice!
  • It handles my unusual FTP setup using an FTP virtual directory. Not every tool deals with that correctly.
  • Inserting images allows you to apply a few simple effects. Very neat!
  • Support for Really Simple Discovery (RSD).  I just added RSD to Subtext.
  • Plugins!

The Needs Improvement

Since this is a beta, I didn’t feel right calling it “The Bad”.

  • Doesn’t let you specify the title attribute of a tag.
  • Inserts   all over the place as you edit text.
  • What key do I hit to Find Next?
  • No Find and Replace? Really?
  • Be nice to have HTML highlighting in the HTML View.
  • If I markup a word with the <code> tag, then cut and paste that word elsewhere in the Normal view, it marks up the pasted word with the font tag rather than using the underlying tag.

The Wish

  • Using typographic characters for singe quotes and double quotes ala MS Word.
  • Integration with CSS styles from the blog. Be nice to have a pulldown for various CSS classes.
  • Configurable shortcuts. I use the <acronym /> and <code /> tag all the time and have shortcuts for these configured in w.bloggar.

All in all, I really like it so far.  It has a nice look and feel to it and if they iron out a lot of these kinks, this may be the one to beat.

Unfortunately, this may cause some delays in Subtext 1.9 unless I can fight off the vicious urge to write some Microformat plugins. Why must these people introduce such interesting toys into my life! Where will I find the time? ;)

Speaking of which, Tim Heuer already has written a couple of plugins

[Download Windows Live Writer]

comments suggest edit

Subtext Logo No, this is not a case of breaking and entering. With preparations for the next release of Subtext, apparently our SourceForge ranking has climbed up into the top 15. Now keep in mind this is a ranking of the most active projects, and is not a ranking of the success or value of a project. It is an amalgamation of source control checkins, discussion forum activity, and other statistical factors.

Even so, it is satisfying to see our project listed as #13 in the most active projects last week. It is an indication that more and more people are getting involved and having fun building this puppy.

I hadn’t even noticed until several people pointed it out.

I imagine that number will dip after we release when we all take a collective sigh of relief.

comments suggest edit

Or did I?

JackAce, a former coworker of mine and total poker addict, happened upon this fine piece of artwork and astutely snapped this picture for posterity with his T-Mobile (click through to go to the original flickr pic).

Picture of my last name graffiti'd on a park
bench

Soon the entire city of Angels will know the name of Haack!!! BWAHAHA!

Unfortunately the idiot taggers didn’t follow my instructions. I told them to tag my URL, not my name.

Eeeeediots!

Good taggers are hard to find. You might promote your blog by writing good content, posting comments in other blogs, and other such nonsense, and hey that’s cool for you. But this is how we roll in L.A.

Westside!

comments suggest edit

Here are a couple of useful methods for getting information about the caller of a method. The first returns the calling method of the current method. The second returns the type of the caller. Both of these methods require declaring the System.Diagnostics namespace.

private static MethodBase GetCallingMethod()
{
  return new StackFrame(2, false).GetMethod();
}

private static Type GetCallingType()
{
  return new StackFrame(2, false).GetMethod().DeclaringType;
}

Pop Quiz! Why didn’t I apply the principle of code re-use and implement the second method like so?

public static Type GetCallingType()
{
    return GetCallingMethod().DeclaringType;
}

A virtual cigar and the admiration of your peers to the first person to answer correctly.

comments suggest edit

A while ago Ian Griffiths wrote about an improvement to his TimedLock class in which he changed it from a class to a struct. This change resulted in a value type that implements IDisposable. I had a nagging question in the back of my mind at the time that I quickly forgot about. The question is wouldn’t instances of that type get boxed when calling Dispose?

So why would I wonder that? Well let’s take a look at some code and go spelunking in IL. The following humble struct is the star of this investigation.

struct MyStruct : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Disposing");
    }
}

Let’s write an application that will instantiate this struct and call its Dispose method via the interface.

public class App
{
    public void DemoDisposable()
    {
        IDisposable disposable = new MyStruct();
        DisoseIt(disposable);
    }
    
    public void DisoseIt(IDisposable disposable)
    {
        disposable.Dispose();
    }
}

Finally we will take our trusty Reflector out and examine the IL (I will leave out the method header).

.maxstack 2
.locals init (
    [0] [mscorlib]System.IDisposable disposable1,
    [1] NeverLockThis.MyStruct struct1)
L_0000: ldloca.s struct1
L_0002: initobj NeverLockThis.MyStruct
L_0008: ldloc.1 
L_0009: box NeverLockThis.MyStruct
L_000e: stloc.0 
L_000f: ldarg.0 
L_0010: ldloc.0 
L_0011: call instance void 
    NeverLockThis.App::DisoseIt([mscorlib]System.IDisposable)
L_0016: ret 

Notice the bolded line has a boxing instruction. As we can see, our struct gets boxed before the Dispose method is called.

The using statement requires that the object provided to it implements IDisposable. Here is a snippet from the MSDN2 docs on the subject.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources.

I wondered if the using statement enforced the IDisposable constraint in the same way a method would. Let’s find out. We will add the following new method to the App class.

public void UseMyStruct()
{
    MyStruct structure = new MyStruct();
    using (structure)
    {
        Console.WriteLine(structure.ToString());
    }
}

This code now implicitely calls the Dispose method via the using block. Cracking it open with Reflector reveals…

.maxstack 1
.locals init (
    [0] NeverLockThis.MyStruct struct1,
    [1] NeverLockThis.MyStruct struct2)
L_0000: ldloca.s struct1
L_0002: initobj NeverLockThis.MyStruct
L_0008: ldloc.0 
L_0009: stloc.1 
L_000a: ldloca.s struct1
L_000c: constrained NeverLockThis.MyStruct
L_0012: callvirt instance string object::ToString()
L_0017: call void [mscorlib]System.Console::WriteLine(string)
L_001c: leave.s L_002c
L_001e: ldloca.s struct2
L_0020: constrained NeverLockThis.MyStruct
L_0026: callvirt instance void 
    [mscorlib]System.IDisposable::Dispose()
L_002b: endfinally 
L_002c: ret 
.try L_000a to L_001e finally handler L_001e to L_002c

As you can see, there is no sign of a box statement anywhere to be seen. Forgive me for ever doubting you .NET team. As expected, it does the right thing. I just had to be sure. But do realize that if you pass in a value type that implements IDisposable to a method that takes in IDisposable, a box instruction will occur.

comments suggest edit

Today I was thinking about how much I enjoy doing business with a particular company and realized my natural inclination was not to blog about it. Yet when a company really drops the ball, I have no problem airing my criticisms. I don’t know about you, but I don’t like to be around people who are only critical and never offer praise. It gets to be tiresome.

So today I would like to give a shout out to Paychex (I am not in any way affiliated with them other than being a customer). We signed up with them to handle our payroll and everything has been extremely smooth. We had a few problems (not related to them) when we initially started and they went way above and beyond to help us straighten our books related to payroll.

Not only that, the payroll specialist who handles our account is extremely courteous and helpful on the phone. Just an all around cool guy. It is very telling when you are looking forward to calling in payroll because you like talking to the rep. Paychex just seems to understand customer service and gets it right.

So tell me, who deserves your shout out today?