Just in time to welcome in the new year, Desk Drive 1.7 adds three new translations and a cool little feature suggested by one of our users.
Version 1.7 adds additional information to the shortcut label of removable drives (i.e. USB sticks) indicating the total size and free space available on that drive. The example image below shows a 1GB flash drive with 500MB of free space.
Also, three new languages join this release thanks to friends in Russia, Hungary and Poland. That boosts the total number of supported languages to 18.
The community support for Desk Drive has just been amazing. I may write the code, but the testing, features and language support come from you, the user.
So keep them cards and letters coming. No idea is too trivial that it won’t get consideration. Enjoy.
There’s a great post on Stackoverflow about hidden features in C#. I prefer to think of these as idioms rather than hidden features since most are actually documented. Here are my favorites.
From CLR via C#:
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.
From Rick Strahl:
You can chain the ?? operator so that you can do a bunch of null comparisons.
string result = value1 ?? value2 ?? value3 ?? String.Empty;
I think one of the most under-appreciated and lesser-known features of C# (3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.
For example, let's say that I want to register a method with an API and that API needs to get the method name
Given this class:
public class MyClass
{
public void SomeMethod() { /* Do Something */ }
}
Before, it was very common to see developers do this with strings and types (or something else largely string-based):
RegisterMethod(typeof(MyClass), "SomeMethod");
Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:
RegisterMethod(cl => cl.SomeMethod());
In which the RegisterMethod class uses Expression> like this:
void RegisterMethod(Expression> action) where T : class
{
var expression = (action.Body as MethodCallExpression);
if (expression != null)
{
// TODO: Register method
Console.WriteLine(expression.Method.Name);
}
}
This is one big reason that I'm in love with Lambdas and Expression Trees right now.
My favorite trick is using the null coalesce operator and parens to automagically instantiate collections for me.
private IList _foo;
public IList ListOfFoo { get { return _foo ?? (_foo = new List()); } }
If you're trying to use brackets inside a String.Format expression...
int foo = 3;
string bar = "blind mice";
String.Format("{{i am in brackets!}} {0} {1}", foo, bar);
//outputs "{i am in brackets!} 3 blind mice"
InternalsVisibleTo attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly
If you want to exit your program without calling any finally blocks or finalizers use
Environment.FailFast()
I just found out about this one today -- and I've been working with C# for 5 years!
It's the namespace alias qualifier:
extern alias YourAliasHere
You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won't work in some old code, but you need to upgrade it to the new version. Slap on a namespace alias qualifier, and the compiler will let you have both types in your code.
There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.
More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default, but server is much faster on multicore machines.
Be careful. The server gc requires more memory.
The Environment.UserInteractive property.
The UserInteractive property reports false for a Windows process or a service like IIS that runs without a user interface. If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with.
My favourite is the
global::
keyword to escape namespace hell with some of our 3rd party code providers...
One feature that I only learned about here on StackOverflow was the ability to set an attribute on the return parameter.
[AttributeUsage( AttributeTargets.ReturnValue )]
public class CuriosityAttribute:Attribute
{
}
public class Bar
{
[return: Curiosity]
public Bar ReturnANewBar()
{
return new Bar();
}
}
This was trully a hidden feature for me :-)
The generic event handler:
public event EventHandler MyEvent;
This way you don't have to declare your own delegates all the time.
There are many others in the post. What are your favorites?
Don’t know how long this one is going to last but you can get a free commercial version of Parallels Workstation. Check out the link below.
Parallels Workstation for Windows & Linux – Free
Parallels Workstation sells for $50 but you can request a licensed activation key for free using this Lunarpages offer. Key in your email address and they’ll immediately send you the download links for the trial version and serial number to convert the trial into a full retail version.
In case the above offer expires by the time you read this, you can always download the free Virtual PC (Microsoft) or Sun’s VirtualBox which is available for Mac as well.
I just loves me some free software.
Silverlight has no event for handling double-clicks. Here’s an excellent article detailing a way to add double click detection and handling by Andrea Boschin. While the code is acceptable, I couldn’t resist refactoring the code a bit to make a few improvements and add testability.

Here’s the original code.
public class MouseClickManager
{
public event MouseButtonEventHandler Click;
public event MouseButtonEventHandler DoubleClick;
private bool Clicked { get; set; }
public Control Control { get; set; }
public int Timeout { get; set; }
public MouseClickManager(Control control, int timeout)
{
this.Clicked = false;
this.Control = control;
this.Timeout = timeout;
}
public void HandleClick(object sender, MouseButtonEventArgs e)
{
lock(this)
{
if (this.Clicked)
{
this.Clicked = false;
OnDoubleClick(sender, e);
}
else
{
this.Clicked = true;
ParameterizedThreadStart threadStart = new ParameterizedThreadStart(ResetThread);
Thread thread = new Thread(threadStart);
thread.Start(e);
}
}
}
private void ResetThread(object state)
{
Thread.Sleep(this.Timeout);
lock (this)
{
if (this.Clicked)
{
this.Clicked = false;
OnClick(this, (MouseButtonEventArgs)state);
}
}
}
private void OnClick(object sender, MouseButtonEventArgs e)
{
MouseButtonEventHandler handler = Click;
if (handler != null)
this.Control.Dispatcher.BeginInvoke(handler, sender, e);
}
private void OnDoubleClick(object sender, MouseButtonEventArgs e)
{
MouseButtonEventHandler handler = DoubleClick;
if (handler != null)
handler(sender, e);
}
}
The idea here is to capture the first click and spawn a thread that waits for the given timeout. If another click is detected during the wait, the double click handler is called. If the timer expires, the click event is called. This works well but it has some issues I don’t care for.
- lock(this) – Essentially an antipattern. Locking this is considered harmful and can lead to dead locks.
- Handlers are locked – Locking handler code just seems dangerous
- Every time the Click property is accessed it’s set to !Click – Seems like something that could go in a function
- It’s not testable
Here’s my refactoring.
public class MouseClickAdapter
{
bool _clicked;
Control _control;
int _timeout;
object _syncObject = new object();
public event MouseButtonEventHandler Click;
public event MouseButtonEventHandler DoubleClick;
public MouseClickAdapter(Control control, int timeout)
{
_control = control;
_timeout = timeout;
}
public void ClickHandler(object sender, MouseButtonEventArgs e)
{
if (Clicked())
OnDoubleClick(sender, e);
else
ThreadPool.QueueUserWorkItem(ClickWaitThread, e);
}
bool Clicked()
{
lock (_syncObject)
{
_clicked = !_clicked;
return !_clicked;
}
}
void ClickWaitThread(object state)
{
Thread.Sleep(_timeout);
if (Clicked())
OnClick(this, (MouseButtonEventArgs)state);
}
void OnClick(object sender, MouseButtonEventArgs e)
{
if (Click != null)
{
if (_control != null)
_control.Dispatcher.BeginInvoke(Click, sender, e);
else
Click(sender, e);
}
}
void OnDoubleClick(object sender, MouseButtonEventArgs e)
{
if (DoubleClick != null)
DoubleClick(sender, e);
}
}
The Clicked() method encapsulates the toggling of the click state when it is accessed and returns the previous state for testing. Also, an object is added to handle locking. This is considered a safer practice than locking the instance. Also, the handlers are no longer locked. So what about testability?
The issue is that a Control object is needed to handle the BeginInvoke dispatch. This is necessary because the OnClick handlers must be called from a UI thread. Unit testing does not employ UI threads so you’re seemingly stuck.
When you commit to writing tests for your code as I have done, you often run into these situations. However, with a little creative thinking, you can work around many of these issues. Sometimes, the best course of action is to modify the code slightly to handle conditions unique to testing.
In this case, the OnClick handler checks if _control is null and calls the click handlers directly if that’s the case. It’s a bit hacky but it gets the job done. Now I can easily write my tests.
[TestFixture]
public class MouseClickAdapterTests
{
[Test]
public void ClickTest()
{
bool called = false;
var mouseClickAdapter = new MouseClickAdapter(null, 150);
mouseClickAdapter.Click += (sender, eventArgs) => called = true;
mouseClickAdapter.ClickHandler(null, null);
Thread.Sleep(500);
Assert.IsTrue(called);
}
[Test]
public void DoubleClickTest()
{
bool called = false;
var mouseClickAdapter = new MouseClickAdapter(null, 500);
mouseClickAdapter.DoubleClick += (sender, eventArgs) => called = true;
mouseClickAdapter.ClickHandler(null, null);
mouseClickAdapter.ClickHandler(null, null);
Assert.IsTrue(called);
}
[Test]
public void TwoClicksSeperatedByLongPeriod()
{
bool called = false;
var mouseClickAdapter = new MouseClickAdapter(null, 150);
mouseClickAdapter.Click += (sender, eventArgs) => called = true;
mouseClickAdapter.DoubleClick += (sender, eventArgs) => Assert.Fail();
mouseClickAdapter.ClickHandler(null, null);
Thread.Sleep(900);
mouseClickAdapter.ClickHandler(null, null);
Assert.IsTrue(called);
}
}
I find I almost always refactor code I find on the Internet. Most of the time I do this to make code testable but sometimes I find it’s the best way to understand code.
FreeSnap 1.5 includes these new features:
- Task switcher: Another task switcher? Yes, but this is faster and easier. No fancy thumbnails. It simply switches to the next/previous task. After all, do you want to go the the next task or do you want to be entertained with 3D graphics?
- Half screen sizing: mimics the Windows 7 feature of snapping a window to a half or quarter screen. A previous post illustrates the concept.
- Settings via config file: – The command line was getting a bit overloaded so I’ve moved all settings to configuration file
There’s more documentation on these new features on the FreeSnap page. Enjoy and send feedback.
previous | next
powered by Bloget™