I got a new domain name and moved to wordpress. If you're subscribed to the Feedburner RSS (or email), you don't need to do anything, theoretically you should be still subscribed.
If you encounter any problems, please let me know.
01 October 2008
Done with Blogger
19 September 2008
A Good Question
C# programmers - you should read this question and its many answers, I'm sure you'll learn a thing or two. For example, ThreadStaticAttribute - a clean, type-safe way to get thread local storage in C#.
18 September 2008
Stackoverflow.com
A few days ago, stackoverflow.com launched in public beta. I've played with it a bit and I think it has the potential to become a great tool for programmers.
It's basically a combination of blog/wiki/digg/forum. Seems like a most questions get answers (on various degrees of relevance) within minutes-hours. Here are some of the questions I've asked, in case you're interested.
Here's a review of the beta site (about a month old), but instead of reading it I encourage you to just try it next time you need a programming question answered and Google fails you (don't forget to subscribe to your question's RSS feed).
12 September 2008
Once Upon a Time in ...
Take a look at all these once upon a time movies. Holy crap, I didn't know there were so many!
Silly titles, they just show a lack of interest in thinking of a name that actually relates to the plot of the movie.
BTW, this is post number 200 :)
09 September 2008
Unhandled Exceptions Crash .NET Threads
A little something I learned at DSM today. It appears if any thread in .NET crashes (lets a thrown exception fly through the top stack level), the process crashes. I refused to believe at first, but testing on .NET 2.0 showed it to be true:
(I should really switch to another blog platform, I didn't find a decent way to write code in Blogspot).
class ThreadCrashTest
{
static void Main()
{
new Thread(Foo).Start();
for (int i = 0; i < 10; ++i)
{
Console.WriteLine(i);
Thread.Sleep(100);
}
}
private static void Foo()
{
Console.WriteLine("Crashing");
throw new Exception("");
}
}
According to Yan, the behavior on .NET 3 is to crash the AppDomain instead of the entire process.
Gmail Server Error
Wow, a first for me (not the first time Gmail is causing problems, but the first time I see this error page admitting it's a bug)
08 September 2008
11 Tips for Beginner C# Developers
Today I sat with a friend (let's call him Joe), who just switched from a job in QA to programming, and passed on to him some of the little tips and tricks I learned over the years. I'm sharing it here because I thought it could be useful to other people that are new to programming. The focus of this post is C#, but analogous tools and methods exist for other languages of course.
Refactorings (A.K.A Resharper)
(This is just a short introduction. I recommend the book Refactoring: Improving the Design of Existing Code as further reading)
As I've written here before, I just love Resharper. It is the best refactoring tool for C# I know of (even though it's a bit heavy sometimes - make sure to get enough RAM and a strong CPU). Joe asked me about a C# feature called partial classes. He said his class was just too big (4000 lines) and becoming unmanageable, and he wanted some way to break it to smaller pieces. He also said that at his workplace, they lock the file whenever anyone edits it, because it's very hard to avoid merge conflicts on such huge files.
I was happy he wanted to simplify and clarify his code by splitting the file, but the way he thought of doing this was the wrong way.
Tip I: Single Responsibility and Information Hiding
You should strive to minimize the information you require at place in your program. Joe had dozens of unit tests, which all derived from a single base class that contain methods required for all the tests. In a second look, we saw that some of the methods were in fact only needed by some subset of the tests, that were actually logically close.
To solve Joe's problem, we created an intermediate class, which inherited from the common test base class, and changed these classes to inherit from the intermediate class. We then used Resharper's Push Down Member refactoring, which removed the methods from the test base class into the intermediate class. No functionality was changed, but we removed code from the huge 4000 lines class! By continuing this process, we can break down the huge class into separate related classes with Single Responsibilities, and no class would have access to uneeded information (like methods it doesn't care about).
Tip II - Duplicate Code Elimination
I believe the world of software would be a better place if people were not allowed to Copy-Paste code more than a few times a day. Many coders abuse this convenient shortcut and thus create unmaintainable code. The effective counter-measure to the Copy-Paste plague is elimination of duplicate code.
I saw in Joe's long file code that looked similar to this:
alice = Configuration.Instance.GetUsers("alice");Even though this is a rather simple example of code duplication, I strongly believe even such minor infractions should be dealt with. Every line of the above code snippet knows how to obtain users from the configuration. This knowledge has to be read and maintained by developers. Instead, why not get all the "user getting" code into one place and let us simply write what we want to do, instead of how?
bob = Configuration.Instance.GetUsers("bob");
charlie = Configuration.Instance.GetUsers("charlie");
diedre = Configuration.Instance.GetUsers("diedre");
...
To solve this, I use one of these two techniques:
Extract Method, Tiger Style
- Choose a single instance of duplication, and locate any parameters or code that is not the same among all the instances of the duplicated code. In our examples, the username (and the assignment variable) are the only two different things between the four lines of code.
- For every such parameter, use Introduce Variable. The end result of this phase should look something like this:
string username = "alice";
alice = Configuration.Instance.GetUsers(username);
bob = Configuration.Instance.GetUsers("bob");
charlie = Configuration.Instance.GetUsers("charlie");
diedre = Configuration.Instance.GetUsers("diedre");
... - Now, use Extract Method on this code (the first line in our example). This creates a new method that I would call GetUsers, that simply gets a string argument username and reads it from the configuration.
- Perform Inline Variable on the variable you created in step 1.
- Now, change all the other instances to use this new method and delete the redundant code.
alice = GetUsers("alice");Another way to achieve the same refactoring is Crane Style (I'm just enjoying using kung-fu styles here because I saw Kung-Fu Panda not too long ago :). You can use immediately without creating the temporary user, but then you get a method that specifically returns the username for "alice", which is not what you wanted. Nevertheless, this method can be refactoring by applying Extract Parameter on "alice", netting us the same result.
bob = GetUsers("bob");
charlie = GetUsers("charlie");
diedre = GetUsers("diedre");
Of course these two examples do not begin to cover the myriad of ways you can and should refactor the code. What's important is that you always keep an eye out on how you can make your code more concise, which in turns leads to readability and maintainability.
Tip III: Code Cleanup
Resharper sprinkles colors to the right of your currently open file. Every such colored line is either a compilation error (for red lines), or a cleanup suggestion. Go over such suggestions and hear what Resharper has to say (in the example below it seems nobody is using the var xasdf, so a quick alt-Enter while standing on it will remove it).

Another thing which you should do is define and run FXCop
rules to perform a deeper analysis on your entire project/solution and spot potential problems.
Source Control
Tip IV - Use Source Control
I almost left this out as this goes without saying, but properly using source control can probably save you more time and money than all the other tips (or cost you if you don't use it). The best source control tool I know of for Visual Studio is of course Team Foundation Server, as it has the best integration with the IDE. Other tools are possible, but you have to have a good reason for choosing something other than TFS (One good reason might be cross-platform development and the desire to keep all your code base in a single repository).
Automatic Unit Tests
At Delver, we use NUnit to write unit tests. In past projects I've used Visual Studio's built in test tool, but I found NUnit to be slightly better, mainly due to the integration with Resharper. Resharper adds a small green button next to every test, and allows you to run your test directly from there instead of looking for the "Test View" window. Tomer told me just last week that he uses a keyboard shortcut for running tests, but for me, this is one shortcut I don't think I'll bother learning (the brain can only hole so much).
Another benefit of NUnit is that it runs the test suite in place in your current source folder, instead of copying everything aside to a separate folder like Visual Studio's tool (this used to takes me gigs of space of old unit test sessions which were rarely if ever used).
Tip V - Write Autonomous Unit Tests
Back to Joe, he has a few tests that don't work right out of the box. Before running tests, he has to manually run a separate application used by his test suite. As his project contains hundreds of tests, I would love seeing this added as an automatic procedure in his TestInit() method. Automating a manual operation, besides saving time for developers, enables you to:
Tip VI - Use Continuous Integration
Tests that nobody runs are no good. Tests that are run once when written and then forgotten are only slightly better. By the same logic, tests that run all the time are the best. Pick and use a Build Automation System. I wrote before about our chosen solution, TeamCity, and to sum it up - we're extremely happy about it. TeamCity runs our tests on every commit, on multiple configurations and build agents, and helps us detect bugs faster.
Know thy IDE
Visual Studio is one powerful tool (not belittling java IDEs like IntelliJ and eclipse which in many cases are better). Learn how to use it's features to your advantage:
Tip VII - Edit And Continue
Suppose that while debugging, you found a bug. You can edit the code, save, and continue the debug session without losing the precious time you took getting to this point.
Tip VIII - Move Execution Location
See the little yellow marker that signifies the current location inside the program being debugged? This arrow can be moved! It took me quite a while to discover this (actually heard about it from Sagie), but if you take and drag this arrow, Visual Studio will rewind or "fast forward" your execution to the desired point. None of the code gets executed, you just skip to where you want to go. Excellent for going back after executing a critical method, and rerunning it as many times as you wish.
Tip IX- Use Conditional Breakpoints
Don't waste your time waiting for some specific value to appear in the watch for an interesting variable - set your breakpoints to stop only when the desired conditions are met (right-click on the red breakpoint circle and choose "Condition").
Tip X - Attach to Process
Got a bug that only happens on production machines? You can attach your IDE to any running process (preferably one that is compiled in debug mode), and debug away. You can also programmatically cause a debugger to attach using System.Diagnostics.Debugger.Lau
Tip XI - Use The Immediate Window
The Immediate window is a great tool for executing short code snippets solely for debugging. You can place a breakpoint inside a method you wish to debug, and then call the method directly from the immediate window (saves you from doing this through Edit And Continue)
23 August 2008
Beware of Windows XP SP3 !!!
Especially during test season.
While helping Aya study for a test, I stupidly agreed to install XP SP3 (offered by automatic updates). The nagging box asking me to restart kept appearing. During one of our study breaks, the box appeared, and having no one to tell it "No" for 5 minutes, it rebooted the computer.
When we came back, the computer was in a boot loop. Starting up in safe mode didn't help, nor did "Last known configuration". The solution was, oddly enough, to remove all USB devices! We used an old PS2 keyboard to run System Restore (God bless System Restore). The full solution might be here, I didn't bother reading the rest of the thread right now.
22 August 2008
A Cartoon Proof of Löb's Theorem
Recommended for hardcore logicians only (or just people who like to think).
Löb's Theorem apparently states that "if it is provable that 'if X is provable, then X', then X itself is provable". The cartoon helps you (just a bit) to avoid getting trapped in an endless loop of logic.
There's also a bonus exercise at the end, quite refreshing.
20 August 2008
Gmail Supports SSL!
Quick - go to your Gmail account --> Options --> Always Use HTTPS
And your future sessions with Gmail will be SSL secured.
(This came as a response to a tool that automatically breaks into Gmail accounts, and is a long time overdue IMO).
12 August 2008
The Ultimate Embarresment
Update - Boaz claims his Avast anti virus detected a virus after following the link below. My AVG doesn't detect anything, but follow at your own peril (you should be safe with Firefox & NoScript anyway)
A Blue Screen of Death project in the 2008 Olympics :) (while Bill Gates was attending it)
11 August 2008
Thesis Complete!
Finally, after years of research, months of writing and correcting, and weeks of bureaucracy, I finished my M.Sc thesis!
10 August 2008
Regex Complexity
Today I got a shocker.
I tried the not-too-complicated regular expression:
| href=['"](?<link>[^?'">]*\??[^'" >]*)[^>]*(?<displayed>[^>]*)</a> |
I worked in the excellent RegexBuddy, and ran the above regex on a normal size HTML page (the regex aims to find all links in a page). The regex hung, and I got the following message:
| The match attempt was aborted early because the regular expression is too complex. The regex engine you plan to use it with may not be able to handle it at all and crash. Look up "catastrophic backtracking" in the help file to learn how to avoid this situation. |
I looked up “catastrophic backtracking”, and got that regexes such as “(x+x+)+y” are evil. Sure – but my regex does not contain nested repetition operations!
I then tried this regex on a short page, and it worked. This was another surprise, as I always thought most regex implementations are compiled, and then run in O(n) (I never took the time to learn all the regex flavors, I just assumed what I learned in the university was the general rule).
It turns out that one of the algorithms to implement regex uses backtracking, so a regex might work on a short string but fail on a larger one. It appears even simple expressions such as “(a|aa)*b” take exponential time in this implementation.
I looked around a bit, but failed to find a good description of the internal implementation of .NET’s regular expression engine.
BTW, the work-around I used here is modify the regex. It’s not exactly what I aimed for, but it’s close enough:
| href=['"](?<link>[^'">]*)[^>]*>(?<displayed>[^>]*)</a> |
04 August 2008
Addicted To Resharper
Well, aren't we all? Go get your banner now.
Heh, I still remember the days when I only programmed in C++, and Tomer told me how great C# is (one of the major benefits he listed was Resharper 2.0).
I didn't believe him then, but now, I don't understand how anyone can program in C++ (except realtime/embedded programmers).
01 August 2008
The Dark Knight
Well, everyone that's told me in the recent week how good the new Batman movie couldn't prepare me - it is really that good, and better.
I rate it 5 on movielens (must see).
28 July 2008
My Arrogance in Finding Bugs
Last night I discovered this piece of code (simplified version):
private void Foo()
{
bool b = false;
new Thread((ThreadStart)delegate { b = true;}).Start();
WaitForBool(b);
}
private void WaitForBool(bool b)
{
while (!b)
{
Thread.Sleep(1000);
}
}
I was immediately filled with disgust. How could someone write such a function (WaitForBool), which is one big bug? Of course the waiting will never be over, because bool is a value type, and no external influence can modify its value.
Later, I realized the fool is me.
I ran into this code a while back, and it did have a "ref" bool, which means it can be modified by the external thread. Resharper helpfully displayed a tip "this parameter can be declared as a value" , which I took without thinking too much about the consequences (I trust Resharper too much sometimes, it appears). So I deleted the "ref" with Resharper's help and created the bug myself without noticing.
(As a side note, of course this method of waiting for a bool should never be used - use ManualResetEvent instead).
Update
Fixed in the next Resharper build (Resharper 4.0.1, build 913), within a few hours of reporting it. Cool.
17 July 2008
15 July 2008
Delver is Online
Still alpha, but starting today we are open for business - try it out yourself at www.delver.com.
I won’t write about the user experience much because I want you to try for yourselves, and because many others have done so already.
09 July 2008
Gmail Sessions
Gmail recently added a nice feature: Down the page (near the space usage stats) there is the text "Last account activity". If you click on details, you get the recent gmail sessions you've had, and can even disconnect them. Useful for checking that nobody's using your credentials from anywhere...
Embedding the above image link doesn't work, and I have no idea why :(
Here is a link to the image.
P.S.
Thanks to Eran for the tip.
02 July 2008
HTTP/1.0 Is Dead
Update - it seems the pesky problem we were having for HTTP/1.1 is actually still relevant to us. The problem is we cannot force .NET framework to properly close a response stream within the HttpWebResponse - the thread just waits forever. Sucks, but it appears we have to use HTTP/1.0 for the time being, at least until we manage to hack it someway (understand how the class works internally and hack it away).
Working for the Diggers team in a search engine, a large chunk of our tasks is writing sophisticated web crawlers.
We were using HTTP/1.0 because we didn’t need any features in 1.0, and to circumvent a problem we thought we had with 1.1. On such a crawl mission, I discovered today that MSN’s site does not support HTTP/1.0.
After another check we found that the above problem does not affect us, because it is only relevant the Microsoft Compact Framework. But it’s still a rather shock to find a large site (even though it’s Microsoft) that utterly does not support HTTP/1.0.
Try it yourself – go to about:config in Firefox and set network.http.version to 1.0, and then surf to MSN. You’ll get a blank page. What actually happens is MSN assumes you’re using HTTP/1.1, and sends you a chunked response. Your web browser will not parse a chunked response, and rightly so.
(Needless to say that HTTP is supposed to be backward compatible).

