When do I need to implement a finalizer or IDisposable?

Recently another developer was experimenting with structs we are using to serialize a class for eventual mapping into an XmlDocument to transmit to a vendor. I noticed he had derived from IDisposable but had not implemented any Dispose pattern for the struct. I queried him on it, "What is the rationale for implementing IDisposable on a struct (a value type)?" (I just love to challenge other developers, even when I haven't a clue what the hell I'm talking about).

Fact of the matter is, this is one of the most esoteric areas of working with the .NET Framework, and if you search around, you will find a lot of people simply parroting what they have seen elsewhere, which of course leads you on a wild goose chase to nowhere pretty fast.

The Nitty-Gritty: Finalizers only need to be implemented when you hold onto resources that need cleaning up.

FileStream holds onto a native file handle and implements a finalizer to release the handle when the FileStream is garbage collected. Finalizers place a lot of pressure on the garbage collector and should be used only when absolutely needed.

Dispose generally goes with Finalizers. The IDisposable interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. Any class that implements a finalizer should also implement IDisposable. But, not all classes that implement IDisposable need to or even should implement a finalizer. Look at the various classes that actually have a Dispose method to get more insight (Ex. SqlConnection).

Let's say a managed class has a FileStream as a private member. FileStream holds onto unmanaged resources and implements both IDisposable and a finalizer. When no more references to the instance exist, the FileStream will be unreachable and will be available for finalization. There's no reason for the class having FileStream as a member to be in the queue of objects that have registered for finalization since the instance of FileStream will be there. But the class should provide a way for a user to immediately release all resources it holds onto, either directly or indirectly, and so the class should implement IDisposable. Your implementation of Dispose will simply call the FileStream's Dispose method. Be careful not to dispose of shared resources (resources used by other instances, for example).

If you do need to implement a finalizer in your class, your Dispose method should use the GC.SuppressFinalize method to ensure that finalization of your instance is suppressed. This will remove the instance from the set of objects that require finalization, reducing the pressure on the garbage collector during a collection. A common pattern implemented throughout the Microsoft® .NET Framework is to add to a class a Dispose method that takes a Boolean as a parameter. This Boolean indicates whether the class is being disposed because the IDisposable.Dispose method is called or because the finalizer is run (both the finalizer and IDisposable.Dispose delegate to this method). If it's being disposed deterministically, GC.SuppressFinalize is invoked. If it's being called from a finalizer, avoid using managed members of your class that implement finalizers as they may have already been finalized.

The Patterns and Practices Book provides an excellent code example of how to implement an IDisposable Pattern in your code.

The following table provides guidelines on when to implement these constructs in your classes:

Your Class Has IDisposableFinalizer
Only managed resources that don't implement IDisposable or have any way of being closed
Only managed resources, but some of them implement IDisposable or can be closed in some wayX
Both managed resources and unmanaged resources XX
Only unmanaged resources XX

Short answer is, you will be hard - pressed to find a good reason to implement IDisposable on a struct! IDisposable is not some magical chicanery behind the scenes. It's simply an Interface that allows you to provide a standardized way for callers to tell your class they want it to go away and clean up it's room before it leaves. If it doesn't have a lot of junk in it's room to clean up, you can just close the door instead and everything will be fine. Rest assured, their room will disappear in the next mudslide. A more detailed treatment of this issue, including a revealing "gotcha" about the SqlConnection class and Close vs. Dispose, can be found in this article.

Sql Server Resources - SQL Server 2005

SQL Server 2005 is coming shortly (November 7, to be exact). Are you ready?

I was reading up in my Feedreader on some new resources and one that came up was Gert Drapers, SQL Server guru extraordinaire. I've already UnBlogged about Gert based on what I learned from his Tech-Ed 2004 presentation here (boy I liked San Diego and that super geeky W Hotel).

Turns out that Mr. Drapers has a web site where he features lots more resources. Good reading.

You can also check out a recent interview with Drapers from PASS here.

There are experts, and then there are gurus. The gurus are the guys that you hike through the mountains for 20 years just to ask them the meaning of life. Gert Drapers is one.

BTW, If you do and he tells you that "Life is a fountain", umm.... don't mention my name.

Visual Studio.NET 2005: Got a Bug? Get Crackin' !!!

You are getting into the "home stretch" for Visual Studio.NET 2005 Release on Nov. 7.

So, if you think you found a bug, go to the product feedback center and put it in!

I've submitted a number of them since the site was started, and I can tell you from personal experience that the kind folks in Redmond are VERY INTERESTED and you will get quick feedback - plus access to published / submitted workarounds if they apply.

This is going to be a nerdalicious release, help make it the best it can be.

Weird Science:

It only takes one brain cell to recognize a Hollywood celebrity, according to a study into how the human mind recalls a familiar face.

Scientists have shown that the faces of stars such as Halle Berry, Jennifer Aniston and Brad Pitt can each stimulate a nerve cell in the brain which seems to recognize that face alone.

Of course, to recognize things like your Significant other, or Mother in Law, much more complex interactions of thousands of brain cells is required. Fortunately, I've lost most of those cells so I can have more fun focusing on Halle Berry...

419 Vigilantes Redux

This morning on way to work I hear a short piece about some 419 "Baiters" who are beating the low-life Nigerian Bank Scammers at their own game. IMHO This is an exception and a noble cause, especially in light of the fact that the FBI et al have 419'ers low on their priority list. These people are baiting the scammers at their own game and making them burn up their resources until they have nothing left.

If you support these guys and add Microsoft Anti-Spyware plus McAfee Viruscan Enterprise, you can almost have a life again.


The day I set Hi-Tor on fire

Recently the Significant Other came in one Sunday morning and asked, What are the two most memorable things that happened to you when you were a kid? It didnt take me long to remember. . .

When I was still quite young, the family moved north from New York City to Rockland County, on the west side of the Hudson River, just north of New Jersey. At that time, Rockland was "the country" -- it was nowhere near as built-up as it is now. We had some friends in Spring Valley that had a farm, and I used to go riding there.

Our first place in Rockland County was in Garnerville a small town about 10 minutes west of Haverstraw, known in older times for its brickyards. Stony Point is a few miles north, famous for the Battle of Stony Point during the Revolutionary War, and home of the late composer John Cage. Further north is Bear Mountain, where there is pretty good skiing in winter and a popular ski-jump competition. Even further north is the famous West Point military academy campus. It was here I made friends, went to elementary school, and later to Spring Valley, NY for high school.

I remember the day clearly. It was a hot summer Saturday. Tommy Lockhart and I had agreed to take a hiking trip to Hi-Tor, a high mountain that overlooks the town of Haverstraw and the Hudson River. You start out in Garnerville near Lo-Tor, a smaller mountain, and you hike a trail along the mountain ridge for about 2 hours to get to the bigger mountain.

We brought some hot dogs, matches, a couple of canteens of water, and other stuff like knives, cookies and general hiking gear that 14 year old kids would take on a hiking trip. After a long hike, we arrived at the peak of Hi-Tor, which is a grassy rocky area at the top of the mountain. In its center was a large metal radio beacon tower to warn planes.

Of course, if youve made the trip that far, there are two things to do: you sit in the Indian Chair, a rocky outgrowth that juts right out over a steep precipice on the side of the top of the mountain, and you climb up the tower to stand on the deck about 150 steps up the ladder, and enjoy the incredible view of Haverstraw and the Hudson River below.

the day I set Hi-Tor on fire

Town of Haverstraw and Hudson River as seen from the peak of Hi-Tor mountain

It had been a hot summer, and all the high grass on the mountain top was dry. We got our little fire going for our hot dogs, and decided to climb up the narrow metal stairway to the top of the radio tower. The day was clear and there were no clouds in the sky. It's an eery feeling, being at the top of a tower on a mountain top, with no sound at all except the faint bustle of the town far below. I remember there was considerable wind, which is unusual for such a hot sunny day.

Suddenly Tommy pointed to the ground far below and said "Look! The Fire!" I looked down and saw that our fire had blown onto some of the high dry grass nearby and was already out of control! My first thought was, "Holy Shit. We're gonna go to jail!"

We scrambled down the nasty metal ladder steps like greased lightning, jumped onto the ground, grabbed whatever we could, and tried to put out the fire. It was too late. The whole top of the mountain was on fire, and the flames were already 10 feet high! I said to Tommy, "We gotta get out of here!" Tommy decided to try to go down the face of the mountain and make it into town to get help. I hiked back to Garnerville as fast as I could.

When I arrived home, tired and scared, I resolved not to say anything to my parents. That night, in my room, I finished soldering in an illegal 40 watt power tube into my CB set and got on the horn to some older men in Peekskill across the river. They were already talking about the fire on Hi-Tor. Apparently, Tommy made it into Haverstraw and they sent up a helicopter with a bunch of water and were able to put it out. The guys in Peekskill were amazed at how loud I was. They said I was crossing over 3 CB channels. I just told them I had a new CB antenna I was experimenting with. (Actually, that's mostly true; thanks to me, we had more wire in our back yard than Barnum and Bailey have under the Big Tent).

I was one relieved 14 year old geek with a CB set that had a 40 Watt power tube. Now that I think about it, history does repeat itself. Blogs,  IM and social media are just the "new" CB! One thing is for sure. I'm never gonna grow up, man. Being a kid is just too much fun!


SQL SERVER 2005 June CTP Install Tricks Department

Contrary to what you read in the Readme file, you DO NOT have to uninstall Visual Studio.Net 2005 Beta 2 in order to install SQL Server 2005 JUNE CTP.

Just use the Buld Uninstall wizard ( "sqlbuw.exe") from the Tools subfolder to remove your previous beta. Then UNINSTALL .NET Framework 2.0, and
Install the .NET Framework 2.0 from the \Redist\2.0 subfolder. Then the regular Setup.exe from the JUNE 2005 CTP for SQL Server 2005 Enterprise will work perfectly!


Podcasting For Dummies 101

OK so podcasting is supposed to be the next big thing, right? This is about 95% of it:

<enclosure url="http://yourserver.com/download/coolvideo.wmv" length="131" type="video/x-ms-wmv" />

the enclosure element in the RSS item has 3 parts; URL, Length, and type (MIME type). That's it!

Your feedReader simply looks for an enclosure element, parses it, perhaps checking it against a hashtable of stuff that's already been downloaded (so you don't download it over and over) and you pretty much got it.

You decide where you want to save it, and with what player you want to play it, and how to display the play feature ("play" button, whatever). You could even render a Windows Media object player tag with the URL to the resource if you wanted to be really cool.

Now you watch. This is only a couple months old. Some dood from Maladaptive Pathetic or whatever will give it a newer, even different buzzword name, and start giving seminars and summits about it.

My Aunt Minnie will get suckered into spending 500 bucks for some seminar and end up having WMVs of her apartment in Queens on her blog. Podcasting, Schmodcasting!


Note to Self: Windows 64-Bit Dual Boot, ChkDsk.exe and Strategy

I run a dual boot machine at my home office, Windows 2003 Server 64-Bit on the big drive, and Windows XP Pro 32-bit on the smaller second drive. I have it set up to dual boot and it provides me with a lot of flexibility - not to mention a fail-safe way to boot into an alternate OS if I ever have a problem.

This past evening I decided to run Chkdsk. I usually do this about once a month, it's a good practice. It's a new machine and I hadn't run it before. To run chkdsk.exe properly you must set it to run on the next boot, since that's the only way it can get exclusive access to the media and be able to fix any problems it finds.

While rebooting I decided to hit the DEL key and check my BIOS. I hit the key to "Load Optimized Defaults", saved and let the box reboot.

It came up in Windows XP. That's not what it is supposed to do. Tried again--- Windows XP. Hmmm. Bottom Line, I spent a half an hour fiddling around with boot.ini, copied my backups of NTLDR etc. from the secondary drive onto the primary, and got pretty frustrated.

Finally I went back to the BIOS. When I chose "Load Optimized Defaults", it had changed the primary boot media from my big drive (Windows 2003 Server 64-bit) to my secondary drive (Windows XP).

What's the lesson? It's one I know well, and I didn't follow it:

If you are going to change something, ONLY CHANGE ONE THING AT A TIME.


When in doubt, Refactor (or, the Blind Man and the Matzo)

Have you ever "inherited" code written by someone else, usually somebody who doesn't even work there anymore, and been told to "Make it do X"? And you look at this code and it is UGLY! It's so ugly it could scare the chrome off a bumper! Not only that, you can't even figure out what the hell it does! This code is like the blind man and the matzo. (Joe takes his Passover lunch to the park. A blind man comes up and sits down on the bench besids him. Joe, feeling neighborly, hands the blind man a sheet of matzo. The blind man handles the matzo carefully for a minute, then looks up and says, "Who wrote this CRAP?")

Well you have three choices, usually:

1) Add more spaghetti code to it, attempting to make it do "X", which it was probably never designed for.
2) Refactor.
3) Quit and go work someplace else, with no guarantee that you won't be jumping from the frying pan into the fire...

What is Refactoring?

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. The general idea behind refactoring is to make a series of small changes, in such a manner that the "System" keeps functioning after each change. Each change is supposed to make the code more manageable, easier to understand, and easier to extend and re-use.

However there also exists a "broader definition" (although it isn't the "official" one), and that is to refactor / rewrite code. Usually what this means is that there are "too many pieces" tied up in one class, and because of this complexity, it has become difficult or even impossible to do the "spaghetti code thing" to it in order to get it to do "X" (which of course, remember, it was never designed to be able to do in the first place.) You can usually tell that you need to do an "RR" (refactor / rewrite) when you are forced to put in a lot of conditional "if / else" blocks in an existing class in order to make it "jump over" blocks of legacy code when a certain "new condition" that you have added to the class is true. Another hint is when you see methods in there that, to any logical mind, should not be "locked up" inside this class; they should really be in their own separate class (Occasionally you can do that XP thing and "Smell the code". If it stinks, it usually means you've got some old data in there that's gone bad-- another reason to refactor).

Generally speaking, what you want to do in this case is to break out the various methods and or fields that really don't belong there under your "new vision" (which hopefully is a bit more inspired than that of its predecessor) and put them in separate classes that can be referenced by the code in the target class of the refactoring effort. And you want to do the classic "small step" refactorings too. In some ways, refactoring is like database normalization.

Refactoring, like other techniques, has been reduced to a science, and there is a lot of published information on it, which I won't bore you with here. The two key words are "disciplined", and "technique". Suffice to say that the Microsoft folks thought it important enough to put it into Visual Studio.NET 2005. Oh, it's far from a complete implementation, but there are some pretty good basics they managed to get in there.

Another big advantage of making decision number 2 (from above) early on in your effort, is that it forces you to "learn while doing" -- in the process of your refactoring, you will actually begin to understand what the hell that nameless "predecessor developer" from whom you inherited this awful mess was attempting to do.

Bask in your new-found superiority. Refactor Mercilessly. Oh, and -- pass the matzos, would you?

Outlook 2003 Junque Email Filter Update

As spam fiilters go, it's pretty good;



Tech-Ed Orlando MVP Session

Just got back from the Peabody Hotel where I met up with MVP luminaries such as Daniel Cazzulino, Ingo Rammer, Victor Garcia Aprea, DonXML, Billy Hollis and members of the various Microsoft developer evangelist teams. Sean O'Driscoll gave a nice presentation, there will be a new MVP logo out on June 14, and I had a chance for a nice chat with our C# MVP lead, Rafael Munoz.

Daniel and Victor are busy working on the PAG (Platform Architecture Guidance) group, putting out some amazing new things.

DonXML, I and Cory Smith were having a fun discussion about Visual Basic. Don said whenever he has to write code in VB.NET, the first thing he does is remove any references to the Visual Basic namespaces, and that his VB.NET code looks like C#. I found that particularly amusing.


The "Value Proposition" and Web Marketing

I first started marketing on the web in 1996 when the multilevel marketing long distance reseller company that I founded needed an efficient way to communicate information to our representatives (and to the public) about "what was happening". At the time, we had produced 8,000 reps marketing long distance services, some of them making over $20,000 a month, and if the service provider that invested in my company hadn't mismanaged their finances and gone upside-down, it would most likely still be around today. (Hey, i did all the database programming in FoxPro 2.6, which, at the time, in all it's 16-bit glory, was the greatest thing since sliced bread!).

So, by Internet standards, I could be regarded as an "old-timer". But the marketing proposition techniques I learned and used then haven't changed at all. Oh, the landscape has changed, to be sure. But not "what turns people on" -- because that's human nature. I've never failed at a web marketing venture, and my standards are high. They are, in order of importance, most important first: 1) provide a bona-fide service, 2) Have FUN doing it, and 3) Make money at it! If you keep these standards in mind, and don't mess up the order of importance, YOU CANNOT FAIL.

There are really three principles in web-site marketing for business owners:

1) Your "Value Proposition" -- What's your unique selling proposition? What benefits do you offer that differentiate your business? What features or services do you offer that build value while giving you a definitive edge over the competition? Distilling your unique value proposition and communicating it quickly and clearly on your Web site is the cornerstone of profitable e-commerce Web design.

2) Your "Target Audience" -- Understanding your market -- and defining the needs of your target demographic -- is a critical component of any business enterprise. Online, you design for your target audience. Articulate meaningful benefits and orient your style and content to the context of your customers' immediate needs and desires. At our developer site, eggheadcafe.com, my partner Robbe Morris and I work constantly to analyze, re-think, and test various business elements based on well-established principles of traffic patterns, user interest, and revenues. If we try something and it is not working, we put our egoes in our back pockets and TRASH IT, fast. And, we make notes about why we think it didn't work. But, we are not afraid to try something new, even if it takes many hours of preparation and programming.

3) "Task Analysis" -- Achieving a Defined Objective. Once your value proposition is being communicated effectively to your target customer, you need a clear, focused sales process. You must analyze the components of your sales channels, provide the necessary educational steps and requisite product information, and design a Web site that optimizes action while eliminating distraction. In other words, provide a logical, sequential story that makes it easy for customers to buy from you. Customers should feel confident and secure when they arrive at that buying decision, even if it is as simple as staying on your site to view some new information, which provides you the opportunity for more ad views and potential click-thrus.

In the case of an Information site that achieve revenue production through contextual or sponsored advertising, it becomes even more important to study the market and your customers and be in a position to perform what I call "deep analysis".

Recently at eggheadcafe.com we decided to promote our messageboard forums, which are already heavily trafficked, by offering a monthly award that is shared among the "top posters". It's another experiment that I expect will work very well, becoming a win-win proposition for our visitors, members, and us, the site owner-operators. Hope you'll visit and contribute!

Recently I took some comment-poster heat from readers of my eggheadcafe.com articles about Remote Scripting technologies, which had a sarcastic tone about what I call the "AJAX clone" promoters. One poster even accused me of attempting to start a flame war. Bottom line is, it violates my standards. One should never have to justify one's annoyance at people who, having no real stake in the evolution of a technology or technique, misappropriate it, give it a new name and act "as if" they invented it, and then proceed to hype it for gain. This is an example of the comment-poster heat, which, to me, is almost incomprehensible! :

"I stumble on your articles every now and then. It seems you like always take a very arrogant tone. I am glad that you understand the code and can boil it down to the real underlying technologies. Usally the articles are decent. This one however went over the top. If you don''t want comments like this then don''t start the flame war Hamburger boy. Yes I am an anonymous coward. Attack the technology don''t sneer. Remote Scripting can be knocked down by itself."

"It seems you like always take a very arrogant tone". -- I've written over 200 short articles on eggheadcafe.com alone. How many of these have "a very arrogant tone"?
"Attack the technology don't sneer" -- I wasn't attacking the technology. I was WRITING ABOUT IT, with examples!
"Remote Scripting can be knocked down by itself" -- I was PROMOTING Remote Scripting, dude!