The Mistery of Failing Tests – Or how to implement IDisposable correctly


Some days ago my Visual Studio tests started failing randomly. Curiously, the same tests which failed in a previous run would succeed if ran again. There seemed to be nothing wrong with the tests, except for the message “The agent process was stopped while the test was running” appearing the Test Results window.

It turns out this message tends to appear whenever an object throws an exception inside its destructor.

Luckly, only about a dozen classes in Accord.NET do need to implement finalizers. After a few searches, it turned down the symptoms were being caused by a NullReferenceException being thrown in one of those classes.

The solution is to always implement the Disposable pattern correctly.

Disposing managed code correctly

To do so, first, implement IDisposable. Consider, for example, the Metronome class, which makes use of timers:

Then, implement the required Dispose method, but do not write the dispose code right away. Instead, write:

Always check if a member is not null before disposing it. Alternatively, after disposing, always set it to null so you can’t accidentaly dispose it twice. The GC.SuppressFinalize instructs the Garbage Collector that the object has already been disposed, so it won’t be required to call its finalizer. The GC will be trusting you have already cleaned the room; so don’t fail on it!

Finally, write the finalizer as:

Disposing unmanaged code

The disposal of unmanaged code follows exactly the same pattern as above, but some care is required when disposing unmanaged resources. Consider the Signal class, which represents an audio signal in PCM format:

Note that this class uses an unmanaged memory block to store the audio signal. To dispose it properly, the Disposable pattern has to be implemented as it follows:

Here we have almost the same pattern. However, note that unmanaged code should always be freed, even if Dispose has not been called explictly. So the code for releasing unmanaged resources is executed unconditionally in the Dispose(bool) method.

Recuperando Informações de Papel Termosensível

samsung_srp-350plus_black O papel termosensível é o papel utilizado em impressoras térmicas como aquelas encontradas em caixas eletrônicos, aparelhos de fax, caixas registradoras ou maquininhas de cartão de crédito. São uma maneira rápida e barata de imprimir informações pois não requerem tinta como impressoras comuns. O cabeçote da impressora esquenta e marca o papel, que fica preto marcando as letrinhas que contrastam com seu fundo branco, amarelo ou azul.

Pois bem, o que muita gente não sabe que este tipo de papel tem um prazo de validade para manter o texto que é impresso.

Em condições ideais, dizem os fabricantes, o texto pode se mantêr legível por um prazo de até 5 anos. Mas, como bem se sabe, quaisquer condições ideais são realmente difíceis de se atingir num mundo tão real, ainda mais quando ninguém diz ao consumidor exatamente quais seriam essas tais condições. Na maioria dos casos, o texto acaba sobrevivendo por, no máximo, dois meses até se transformar num simples pedaço de papel em branco dentro da sua pasta de documentos importantes.

Para preservar a informação, só há uma solução permanente: tirar uma fotocópia do documento antes que o texto se perca para sempre.

Mas é claro, como ninguém acha que vai precisar dessa informação no futuro, certamente o arrependimento só ira bater quando aquele produto que você comprou ano passado estiver começando a dar defeito à um mês de acabar a garantia e seu único comprovante de compra fora impresso neste tipo de papel. E acredite, isto acontece com mais frequência do que se imagina.

Mas e agora?

Existe um método para recuperar o texto deste tipo de papel, mas é um tanto arriscado, pois você pode perder o texto pra sempre. Esta manhã, consegui recuperar parciamente um papel de 4 anos atrás, o suficiente para ler a informação que eu estava procurando.

ironcart2O truque é utilizar alguma fonte de calor para aquecer o papel novamente, como o secador de cabelos ou o ferro de passar roupa. Como não tinha um secador potente à mão, optei pelo bom e velho ferro de passar roupas para recuperar meu documento. Antes de começar, certifique-se de estar usando a função “à seco” (sem vapor) para roupas de algodão (deve haver uma indicação no termostato).

A seguir, comece praticando em partes não importantes do papel, como as bordas, para verificar os resultados. O papel deve tornar-se escuro, e as partes que antes continham texto devem agora permanecer na cor original, num efeito alto-contraste.

Mas cuidado, pois permanecer tempo demais com o ferro sobre o papel borra também as partes escritas e o texto se perde novamente. Pratique e fique atento a cada passada do ferro, pois a próxima pode, literalmente, queimar o papel para sempre!

Essential Software for Windows


Here is a list of useful software I usually install whenever I do a fresh Windows (XP) install. Most of them are free or have free versions available, while others do not.

For a list of essential software for linux, click here.



System Tools

  • ClamWin – The free, open source ClamAV antivirus port for clamwinWindows. It doesn’t have a real time scanner, but who needs one, anyways? Very lightweight and doesn’t get in your way at all.
  • Spybot – Search & Destroy – Third party option for protection agains malware/adware. But I usually leave the TeaTimer (realtime scanner) option disabled.
  • Microsoft Bootvis – Formerly offered on Microsoft’s Website, BootVis is a “is a performance tracing and visualization tool” for helping “identify performance issues for boot/resume timing“. Some says it cannot speed up startup time, but it definitely does for me. All you have to do is install it then click on the “Optimize” button and wait while it does its magic.
  • Macrium Reflect Free – The best backup solution I’ve ever seem. Its worth paying for the full version, but the free one does just as well – it creates images of your entire disk or entire partitions in less than 5 minutes, copying either only the used sectors or making a bitwise copy of your drive, has backup verification, can create Linux or Windows based rescue CDs, backups even your MBR and backups directly from Windows, without needing to reboot using a bootable CD.

    The only regret I have is missing its full version for free when it was available through GiveAwayOfTheDay back in June.

  • WinDirStat – Creates a map of your harddrive so you can see exacly how your disk space is being used. Very useful to discover why your 250GB HD has only 1.7GB free.


File Tools

  • 7-Zip – Archiver (file compressor) with one of the best compression rates out there. Can employ ultra compression at the cost of extra amounts of memory and processor time, but its normal compression is just fine. Plus it is open-source and free, unlike WinRAR.



  • OperaOpera – The Fastest Browser on Earth! Has integrated email, chat, BitTorrent support and is incredibly fast! Has other cool features like mouse gestures, popup blocking and password manager already built in. Definitively my browser of choice, be it in Windows, Linux, mobile phones, game consoles, televisions or fridges.


  • Google Chrome – Because its always good to keep asimonn alternative browser to your alternative browser lying around.




  • PuTTY – The best free Secure SHell (SSH) client for Windows.
  • TrueCrypt – Opensource software for transparent, on-the-fly, realtime encryption. Can hide entire drives and even boot partitions making them completely invisible if you don’t know how to reach them.
    • Update: TrueCrypt  was discontinued back in 2014 and has subsequently not been maintained. A number of security flaws have been uncovered and as a result we are reaching out to people to highlight a list of alternatives. Please see this page for more details and for a list of alternatives for TrueCrypt.



  • Winamp – Winamp has been my player of choice since 1997 on Windows. The AVS plugin is just fantastic, and together with DFX for Winamp and NowPlaying (for Live Messenger) it is a complete, feature rich and the sexiest player ever to sit docked on the top of my screen.

WinampBetter yet is enabling the AVS video overlay (so you can see it on your TV) and set it to change your desktop to the overlay color. Its an amazing effect. But of course, if you own a Geforce card, only if it is a model prior to the 8000 series, if your Windows is prior to Vista and your video driver is old, because NVIDIA, in its infinite wisdom, has completely disabled video overlay on TV for its newer cards and drivers, AFAIK.

  • Media Player Classic – I like Windows Media Player, but whenever it gets in my way its always good to have this alternative around. Plus it just works with my WinLIRC remote out-of-the-box.
  • ffdshow – The One decoder to rule them all. FFdshow decodes nearly everything, video and audio, from mp3 to AAC, mpeg to XVid. Has support for subtitles, postprocessing filters and more. You don’t have to install bloated codec packs which will just mess your system anymore.
  • Real Alternative – The DirectShow filter for watching Real Media videos without Real Player. Just like with QuickTime Alternative, you can view your videos on your player of choice, be it Windows Media Player or Media Player Classic. You just have to register the extensions with your choosen player the first time you open your media.
  • CDBurnerXP – After many years using Nero, and considering the bloatware is has become, I’ve ditched it in favour of this simpler, cheaper, free as in beer alternative and have not looked back ever since.



  • Microsoft Virtual PC – A must have if you like to test neat, cutting edge or just unknown dangerous stuff without risking compromise your main system, or if you need to make tedious testing with different operating systems all in one computer. In my opinion, better than VMWare.
  • .NET Reflector – Apparently, the free software from Lutz Roeder which enables us to peek into CLR assemblies and browse its source code was sold to Red Gate. I can only hope this excellent tool continues as a freeware for us developers.
  • CADSoft Eagle – The Easily Applicable Graphical Layout Editor, or EAGLE for short, is a very complete circuit designer and layout editor, a must have for the electronics hobbyist. The freeware version is enough for most people, but the full version is very worth paying too.
  • Proton DE – The Proton Development Suite for PICBASIC programming (BASIC for Microchip’s PICmicros®).


Internet Utils



  • Adobe Reader – The Standard Portable Document Format Reader. For some time I ditched Adobe Reader in favour of Foxit as it was becoming completely unusable due to the giant memory footprint and “resource hungryness” of its previous versions. But since it’s last version, it has improved a lot, so I’m giving it another try.
  • components-colorWinLIRC – Control your PC using your any infrared remove control. I’d post about how to craft your receiver but there are many good tutorials available on the internet. I may post about mine later in the future.

    The funny thing is, albeit this was originally a Linux program, I’ve never got it to work under Linux, even if it works great on Windows.

The Dreadful LG Burner Strikes Again


20760 As I’ve blogged about before, the DVD writer I bought from LG last year was giving me nothing else but coasters and headaches. But now I suspect I have some clues about the problem.

With this LG GSA-H22N DVD WRITER, I’ve encountered writing problems mostly burning to Sony and Nipponic media. (I’ve also had reading problems when I was using Windows XP x64 Edition, but they seem to begone since I’ve installed the common 32-bit version of Windows XP Professional with SP3).

Usually, the problems occur when the media is recorded using anything more than 4x, even if the media supports higher speeds. But it takes roughly 40 minutes to record a DVD, which is unacceptable in most ocasions. After I insert one of these coaster discs I receive the "X:/ not accessible – Incorrect Function" error under Windows Explorer.



But yesterday, my brother popped up one of those coasters on his notebook and -  guess what – it worked! It hasn’t worked even on my other desktop, which has a respectable Pioneer DVR-110D, but worked on his notebook, and also on a friend’s notebook. I suspect its either the way discs are hold in notebook drives that is enabling them to be read, or their drives have a higher error tolerance than my other desktop drives. Maybe my LG recorder fails to write a proper DVD-R Lead-In on those media and perhaps that only the Toshiba internal optical drives from their notebooks were able to read. In either case, I think it’s still LG’s fault for producing such crappy hardware.

GSA-T20N_HITypically, in the notebook kind of optical drives the discs are hold tightly through a small clip in the center of the tray, rather than loosely attached to the rotor like in conventional drives. I’ve noticed the discs also make a noise, like if they are unbalanced or something. The disc holder could be misaligned, and some media may aggravate the problem making burning (and/or reading) unreliable. Since the discs cannot be read from the start (isn’t like some files are corrupted), the problem must certainly be occuring during the writing of the Lead-In section of the disc.



While I can’t discover the real source of the problem, I think I will keep writing in painful 4x speeds.



Below are some other tips I found around to try to avoid the problem (I don’t know if they really make a difference, but nearly anything is worth trying at this point)

1. Disable Built-In Windows CD Burning

The original burning method that comes with Windows (the one that lets you drag and drop files directly to your DVD Drive under Windows Explorer) was not really meant to work with DVDs. It works, but I would not advice you to use it. Instead, grab some specialized media burning software like Nero or CDBurnerXP (I’ve been using the former lately, and it has been doing its job well).

  • Go to Start Menu > Run, type gpedit.msc then press Enter
  • Go to User Configuration > Administrative Templates > Windows Components > Windows Explorer
  • Find "Remove CD Burning Features", double click it, click "Enabled" then press OK. This will disable the built in CD Burning on Windows (remember you will no longer be able to drag and drop files to your media from explorer, but will have to use a third part media burning software instead).

2. Disable Digital Audio Output for your Drive

Some people reported the digital audio output was causing problems for some drives. I’m bit skeptcal about that, but since disabling it has no major drawbacks, this tip is worth a try.

  • Go to Start Menu > Control Panel > System > "Hardware" Tab > Device Manager.
  • Now find your optical drive on the device tree, double click it, then go to the Properties tab and uncheck the box "Enable digital CD audio for this CD-ROM device".

3. Update your firmware

I’ve updated the GSA-H22N firmware to the 1.02 version already; but it didn’t help. New LG firmwares can be downloaded from But be sure to select the right one for your drive or you may cause irreversible damage to your writer.



Some useful links to continue reading.
Thread depicting a similar problem with Lead-In writing with some burners.
A commercial software which can read data outsite the Data Zone of DVD discs and can be used to debug the problem.
Similar entries on Google about the "Incorrect Function" problem.
Nice thread depicting all the love customers have had for this drive.

Advice: Never link directly to a Microsoft page

Is it only me or nobody can reliably link to a Microsoft site without ending with a broken link less than two weeks after?

Also, adding to the fact that their search engine is totally utter crap, once you hit a dead link the only option left is to ask Google for that missing page. Well, whenever I feel like referencing Microsoft’s site again, I think I’ll just link to a Google query for the page title instead.