Can you spot the problem?

Check out this code:

static void Main(string[] args) { string test = null; Console.WriteLine("Is test null: " + test == null); Console.ReadLine(); }

And guess the output without running the code.


iTunes developers should start using iTunes

If you have an iPod you are more or less stuck with iTunes. If iTunes was perfect this wouldn’t be that bad. However, it isn’t perfect, far from it. Apple is creating superior software, right? Wrong. Just take for example this problem I’ve found.

Let’s say you subscribe to a podcasts source and you want to download 10 episodes. iTunes will schedule all 10 episodes for download and first three episodes will start downloading immediately (looks like they have three simultaneous downloads parameter hardcoded). Nothing wrong here? From my experience there are sources that won’t let you download more than one or two episodes at the same time. But iTunes will try downloading three downloads at same time nevertheless. What gives? Third episode won’t download and will be simply marked as not downloaded. Then the fourth episode will start downloading and the same fate will happen to it. All the episodes at the third slot won’t make it as long as first two are being downloaded. And if you want to download not downloaded episodes again, you’ll have to click Get button over and over again – or pay attention to click only two episodes from the same source in a round. Highly annoying – it looks like Apple developers don’t use iTunes, otherwise they would notice this stupidity. And remedy? Simple simultaneous downloads limit parameter per podcasts source. Or per entire iTunes if the former is too hard to achieve.

But perhaps the most funny is the answer from experts in the iTunes forums:

“When downloading episodes just click the pause button on the episodes that won’t make it, wait for the downloading episodes to finish and click start for paused episodes two or one at a time.”

IOW you have to play download limiter role. Sounds like fun, even more so when you download 20 episodes from the same source. New form of entertainment? Should we forget game consoles?

Hey, iTunes is at version 7.2. Let’s hope they add simultaneous download limitation feature before version 15.0. And note that there are other annoyances within iTunes, this is just one of the most ridiculous one. But let’s look at the bright side: at least this time iTunes didn’t try to destroy your computer.


To Dispose or not to Dispose

The question whether “I need to Dispose some object” appears fairly often in newsgroup, wrong answers and myths appear even more often. So I thought of writing my comments on the issue – it is not supposed to be a detailed and complete reasoning and I won’t dig into garbage collection more than necessary.

(Spoiler ahead) if you don’t want to read the entire post here is the answer: Do dispose everything that implements IDisposable. IDisposable is a contract and it means I need disposing.

From this point on I will assume that Dispose is properly implemented (Dispose is just an interface method that has to be implemented by developer – it is not some sort of magic method).

What do I (possibly) gain by calling Dispose by code (note that Dispose is automatically called on all controls and components placed on WinForms Form or UserControl):

  1. The most important aspect of Dispose implementation: release of unmanaged resources. While Dispose is called from a finalizer, too, there are problems leaving it to finalizer – it might be delayed quite a bit (you certainly don’t want to hold a lock on a resource for days, do you) and it might not be called at all or it might be interrupted before end – finalization is much more delicate process.
  2. If a class implements a finalizer, than Dispose implementation will remove the object from the finalization queue thus saving memory and CPU cycles. You see, garabage collector will place such objects, once they are not in live objects graph anymore, in a finalization queue and it will (or it may not) invoke their finalizers before removing the object from memory and this might be a costly operation. Relatively speaking of course.
  3. it will release references to other objects and thus allow sooner garbage collection of them.

Pretty clear, isn’t it? So, what are the myths and attitudes holding people back from calling Dispose:

  • Class X is derived from class Y that implements IDisposable but it does nothing within Dispose. Calling Dispose on class X would just waste CPU cycles.

There are several problems against such thinking.

  1. Are you sure that the Dispose of class Y does nothing at all? Let’s take DataTable for an example – it derives from MarshalByValueComponent. Common perspective is that DataTable does not hold unmanaged resources nor it does MarshalByValueComponent. While that’s true (Dispose won’t release any unmanaged resource) there is another feature everybody seems missing – point 2: MarshalByValueComponent implements a finalizer and object is removed from finalizing queue imeediately when Dispose is called thus saving CPU cycles.
  2. Even if Dispose really doesn’t do anything, who exactly guarantees that the implementation won’t change in future? If such change occurs at some point in time you’r application might start to behave strangely due to ignoring Dispose. And pinpointg these kind of problems is not exactly an easy process.
  3. If Dispose really doesn’t do anything then CPU cycles won’t be lost. At least not in significant extent.
  • Lack of knowledge that dispose has to be called/being lazy.

I guess developers needs more education.

  • Calling Dispose is messing with garbage collector and won’t do any good.

Yeah, well, see my list above.

  • Cleaning memory takes time and gives nothing back. So let it be done in the proper time, when there  is nothing else to be done, something the GC is standard doing.

Calling Dispose has nothing to do with cleaning the managed memory (it might just speed up a bit the process, as described in point 3). It has everything to do with cleaning unmanaged memory though. Actually Dispose by itself doesn’t do anyhting. It is just a method that is left to developer to implement.

  • Calling Dispose does not release memory. It marks the object instance as “unused” so the GC can release the memory back to the pool.

Wrong from many point of views.

  1. It might release unamnaged memory.
  2. It doesn’t mark anything at all by itself. It just disposes child objects and releases unmanaged memory. It doesn’t affect the GC in any way for the object Dispose is being called. The implementation should remove object from the finalization queue if it implements a finalizer – thus GC will take less time for removing the object from memory.

I am sure that I’ll add more myths and wrong decisions in the future. The above ones are just from top of my head and from a recent thread in adonet newsgroup. And I have yet to hear a good argument against disposing.

The bottom line is: do dispose everything that implements IDisposable. No excuses.

And the question is whether you are a good guy or a bad guy by not disposing resources.


Windows Genuine Advantage is legal user’s worst enemy

I've never ever been a supporter for online activation process for any product. Ever. On the one hand it is usually cracked the same day it is released, so no big benefits against piracy. On the other hand it is only a burden (at best) for a legitimate user and a time waster at worst. See, it happened to me, too. I have a legal and activated Vista Ultimate x86 version happily running. One day I decided to install PowerShell, so I went downloading it. Even though it is a free download, one has to validate the Windows for genuinity using Genuine [MS] Software tool as shown in picture below:


This is an annoyance at best (it takes time, installs an ActiveX, etc.) and a stupid problem at worst as it happened to me, see the picture below.


The tool doesn't recognize that my Windows is in fact activated, see the picture from System properties below:


So the only obstacle between me and PowerShell is this stupid tool. Of course I went googling and soon found this forum support message to same problem:


 WTF? I have to phone around and mess with activation phone process (once again) just to fix [MS] tool bugs? Now, this is ridicolous – I have to loose valuable time if I want to download anything that requires this kind of validation (not to mention time spent on writing this post). Great job [MS]. I'll post an update when I fix the problem.

UPDATE: I didn't fix it the same day beacuse it was too late for [MS] support phone center. Instead, I hibernated my computer when I've finished working. Today, when I woke up the computer from coma, I got a new message box saying something like: "Your Windows is not genuine thus a lot of features will stop working (i.e. Aero)". Apparently ActiveX validator nuked my genuinity, too. Red alarm started to ringing in my head. I immediately called support I ended up with phone activation as it was mentioned in this support message. Everything works again, I just lost a cople of hours due to this problem. BTW, Slovene [MS] support people are good guys 🙂

Hardware Windows

Intel Matrix Storage driver, production version

Intel has put its Matrix Storage driver, official production version, online. Among other improvements, it is supposed to fix iTunes/QuickTime problems for good. I have to say: finally – it was about time! Hopefully this ends months long saga of destroyed RAID drives. I guess we'll soon find it out if the problem is fixed. As a precaution I'll make a copy of my disk content using excellent Acronis True Image software right before installing this driver and later iTunes. Just in case. May the force be with the brave.

Go get it here.

UPDATE: I've been running the above RAID driver and iTunes 7.2 for a couple of days now and there are no problems. Not sure about the disk speed when using iTunes though.


SQL Compare 6 beta

Red Gate is preparing SQL Compare 6 product. The interesting thing about this version is that they are getting ready for supporting source control for storing database schemas. Unfortunatelly the source control support won’t be a part of version 6 but they are laying the foundations for it. And now is the perfect time to speak up about your idea of source control support. Read more about SQL Compare 6 beta, the challenges of database and source control and post your opinions and suggestions in SQL Compare forum.


Answer to Dictionary<> fun trivia

Here is an answer to my previous post about Dictionary<>.

The answer is yes, it is possible that added instance can't be found later on. Consider this, a bit modified, piece of code:

class Program { static void Main(string[] args) { Dictionary<Tubo, object> dictionary = new Dictionary<Tubo, object>(); Tubo tubo = new Tubo(); dictionary.Add(tubo, new object()); // some code here and there tubo.Value = 1; bool keyExists = dictionary.ContainsKey(tubo); Console.WriteLine(keyExists); Console.ReadLine(); } } public class Tubo { public int Value; }

Will I get true as an output? Yes, I will. Now, let's take a look at this, further enhanced, piece of code (only class Tubo as class Program remains same):

public class Tubo { public int Value; public override bool Equals(object obj) { Tubo other = obj as Tubo; if (other == null) return false; if (!base.GetType().Equals(obj.GetType())) return false;

return this.Value.Equals(other.Value);

} public override int GetHashCode() { return Value.GetHashCode(); } }

What I did here is that I've override GetHashCode to return internal Value's one instead of hash code generated out from instance reference by default. I've also implemented Equals operator to check for the equality based on type and  value match.

What output do I get now? The output is false. But let's add keys instance comparison to the output before explaining the result.

static void Main(string[] args) { Dictionary<Tubo, object> dictionary = new Dictionary<Tubo, object>(); Tubo tubo = new Tubo(); dictionary.Add(tubo, new object()); // some code here and there tubo.Value = 1; bool keyExists = dictionary.ContainsKey(tubo); Console.WriteLine("KeyExists: " + keyExists); // get enumerator for keys Dictionary<Tubo, object>.KeyCollection.Enumerator enumerator = dictionary.Keys.GetEnumerator(); // move to the first record (there is only one key anyway) enumerator.MoveNext(); // reference the "original" key Tubo originalKey = enumerator.Current; Console.WriteLine("Equality operation:" + (tubo == originalKey)); Console.ReadLine(); }

And the output is:

KeyExists: False
Equality operation:True

Funny, isn't it?

The answer lies in the way that Dictionary works. When you add a key it firsts obtain its hash code (by calling key.GetHashCode()). Then it uses the obtained hash code to pick a bucket where the key will be stored. Note that hash code isn't a unique value – it is used only to pick the bucket to speed up the search. Once the bucket is picked or created, the key-value pair is stored there. You see where I am going? The search works in similar way. First, the hash code is obtained from key value being searched, then it is used to pick the bucket and finally the key.Equals method is used to compare the instances. Let's modify further method Main to see the root of the problem:

tic void Main(string[] args) { Dictionary<Tubo, object> dictionary = new Dictionary<Tubo, object>(); Tubo tubo = new Tubo(); // obtain original hashcode Console.WriteLine("Original hashcode: " + tubo.GetHashCode()); dictionary.Add(tubo, new object()); // some code here and there tubo.Value = 1; // obtain modified hashcode Console.WriteLine("New hashcode: " + tubo.GetHashCode()); bool keyExists = dictionary.ContainsKey(tubo); Console.WriteLine("KeyExists: " + keyExists); // get enumerator for keys Dictionary<Tubo, object>.KeyCollection.Enumerator enumerator = dictionary.Keys.GetEnumerator(); // move to the first record (there is only one key anyway) enumerator.MoveNext(); // reference the "original" key Tubo originalKey = enumerator.Current; Console.WriteLine("Equality operation:" + (tubo == originalKey)); Console.ReadLine(); }

The output is not that surprising:

Original hashcode: 0
New hashcode: 1
KeyExists: False
Equality operation:True

It is obvious that two hashcodes don't match and thus Dictionary fails to pick the proper bucket when key is used for search operation. So here is the answer to my trivia. Note also that in this case hashcodes are the same as original values. This is not a rule – it just happens in our sample. Also note that there can be more values that corresponds to same hashcode as hashcode is an int and it has a fixed range of values. This means that our sample application might actually work sometimes, when a proper int value (one that has the same hashcode as the original) is assigned to tubo.Value. This would be a hard problem to spot.

Anyway, the morale of this story is that you should override GetHashCode only if really needed and if you do so, you have to know what you are doing very well. Another lesson is that it is a good thing to know how the stuff really works behind the curtains.


Dictionary<> fun

Here is a brief trivia. Take a look at this piece of code:

Dictionary<Tubo, object> dictionary = new Dictionary<Tubo, object>(); Tubo tubo = new Tubo(); dictionary.Add(tubo, new object()); // some code here and there bool keyExists = dictionary.ContainsKey(tubo);

Basically I create a Dictonary instance and I use a class Tubo as a key type. I create an instance of Tubo (which is used as a key), add it to dictionary, run some code and then check whether key (same instance as above) is still there.

Is it possible that I get keyExists == false (note that Tubo instance is the same)?

.net 3.5

Want to build your own IDE?

No problem. [MS] announced Visual Studio Shell product. Just use the pieces and parts of Visual Studio, put them together and voila, there is your IDE. At least theoretically.

Anyway, this is an interesting and I would say very welcome move even for “normal” applications that support scripting or something like that (if you’ve ever supported scripting in your app you would know how hard is to include a proper IDE). I wonder what will be the licensing like.

And in the same post there is a notice that Orcas will be officially called Visual Studio 2008:

“That doesn’t say anything about the release of VS 2008 – only that it will be released in the FY08 financial year (as the naming convention is normally managed). “

I don’t know why but I have a slight suspect that it actually might happen in real, not financial, year 2008. I hope I am wrong though.

.net ASP.Net

Accessing controls in OnPreInit method might be tricky when MasterPage is used

Today I've come across an odd problem. I had to set SkinID property of a control dynamically and this step can be achieved only during PreInit event (OnPreInit method). It is a no brainer implementing the code on standalone Page.

protected override void OnPreInit(EventArgs e) { SomeControl.SkinID="TuboSkin"; base.OnPreInit(e); }

But when the page is hosted on MasterPage the code above throws a Object reference not set to an instance of an object, yep, SomeControl is null for some reason that has to do with MasterPage composition. After googling around for quite some time I've found the solution and explanation to the problem, thanks to Simon's post. The solutions is to call Page.Master property before accessing any of the controls, like this:

protected override void OnPreInit(EventArgs e) { System.Web.UI.MasterPage dummy = Master; SomeControl.SkinID="TuboSkin"; base.OnPreInit(e); }