Desk Drive 1.7 Released

tinytags 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.

Example of new information label

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. 

 

Friday Links #32

The Best Websites for Kids Packed inside a Browser – Kido’Z – With that new computer, they have to go somewhere.

Practical Family Nutrition: Just Eat the Food – Shocking news! Eat a variety foods in moderation and be healthy. Who knew?

CodeProject: Unmanaged arrays in C# - No problem - Easy way to replicate C type heap arrays that use the malloc, free, calloc, and realloc methods, but in native C#.

How to secure your Vista PC in 10 easy steps – Actual sound, practical advice for a change.

BillP Studios: WinPatrol 2008 – Nice collection of tools and system monitoring. Works great on Vista.

Coding Horror: Programming: Love It or Leave It – Agreed. You can’t program effectively (IMHO) without having some degree of passion for the profession.

Parallels Workstation for Windows & Linux – Free - I blogged about this one yesterday. Get it while you can.

 

Favorite C# Idioms

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?

Posted  Friday, January 02, 2009  |   0 Comments
Tags  C# 

 

Parallels Workstation for Windows & Linux - Free

FreeDon’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.

kick it on DotNetKicks.com

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.

 

Friday Links #31

Brad Abrams : Silverlight 2 DataGrid December 2008 Release - This updated DataGrid contains almost 30 fixes to the top issues that we heard, including:

  • Rows containing focus no longer disappear when the ItemsSource changes
  • ComboBox and other controls opening a popup now work as expected
  • DataGrid Selection is preserved when sorting
  • Buttons outside the DataGrid work as expected when they are clicked while the DataGrid is in editing mode
  • Improved FrozenColumn behavior
  • Improved cell currency
  • SelectedItem is updated before the CurrentCellChanged event is raised
  • Many more...

What You Said: Best Places to Find Multi-Monitor Wallpaper – Handy list.

360desktop | Get wide - With 360desktop, slide wide for almost unlimited desktop space; clip the web & put it on your desktop, then create & share, stunning 360° interactive wallpaper. New version 0.7 released.

Media Portal home theater PC app for Windows hits 1.0 - Open Source media center application Media Portal, under development for 5 years, is finally released.

Dilbert comic strip for 12/24/2008 – Scott has found my funny bone as of late.

FileForum | HashTab – I love this little guy and have used it for years. Just keeps getting better.

Lights Out | Popular Science - On March 1, the Republic of Ireland becomes the first democratic country in the world to ban the traditional incandescent light bulb.

Geeknews » Eartha Kitt (Catwoman) – RIP - She was also the only black villain to appear on the Batman TV series from the 1960’s.

Catwoman - Eartha Kitt 3  

A Double Handful of Programming Quotes – Some funny quotes from notable programmers including Bill Gates and Alan Kay.

 

Friday Links #30

Dilbert comic strip for 12/14/2008

Silverlight 3 - What we Know So Far & What We Can Predict – MPEG-4, 3D Support and hardware acceleration. I’m loving it.

New Features in Windows Live Writer 2009 - Microsoft has released an upgraded version of Windows Live Writer 2009 as part of the Live Essentials suite.

IPhone: LogMeIn Ignition Brings Simple Remote Control to the iPhone – LogMeIn.com is my favorite remote control program. This is just icing on the cake.

Cleveland Clinic Performs First Face Transplant in the United States – Obviously not a cosmetic procedure. Amazing technology.

How To Download and Play Flash Games Offline | MakeUseOf.comVector TD has ruined my life. This just adds to my habit.

Why you should choose sex, not the Internet | Technically Incorrect - CNET News – As if us guys don’t have enough competition already.

Google maps out Chrome's RSS support | Webware – CNET – A huge scar on an otherwise good browser. Come on guys, get it done.

Evernote now syncs your files across devices | Webware – CNET – Note taking just keeps getting better and better.

Toolmonger » Blog Archive » 2,000-Year-Old Computer Brought to Life – Computer or not, this one one very cool piece of ancient technology. Check out the video.

Exploring Time – Television special from the Science Channel. Watch it on line.

Geeknews » Majel Barrett-Roddenberry "First Lady of Star Trek" – RIP – This really surprised and truly saddened me. It just doesn’t seem right somehow that she’s gone. I was 7 years old at the time the show first aired. My parents would let me stay up until 10pm to watch. It’s still my favorite Star Trek.

Majel Barret-Roddenberry

Sara Ford's WebLog : Did you know that today’s tip on msinfo32.exe ends the series? –#382 – How can this be? Two blows in one day.

Nikhil Kothari's Weblog : Fluent Animations in Silverlight – Cool idea of they pull it off.

 

Handling Double Clicks in Silverlight

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.

kick it on DotNetKicks.com

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.

 

Friday Links #29

Head First Design Patterns : Steve Smith's Blog – According to the reviewer, this seemingly light-weight book is actually a serious programming book. Who knew?

Enhance Your Windows Vista Start Menu Search Functionality With Start++ – Adds shortcuts to the Vista start menu similar to Launchy.

Sara Ford's WebLog : Did you know… You can use F1 to get Help anywhere, even in a web browserThere’s more to F1 than meets the eye.

K. Scott Allen : Identity Maps - There are a couple of important patterns in play when you use a persistence framework. These patterns have been around for quite some time but are relatively new to .NET developers who are jumping into LINQ to SQL and the ADO.NET Entity Framework.

Genetic Programming: Evolution of Mona Lisa – Using a simple DNA algorithm and 50 polygons, the author creates an amazing replica of the Mona Lisa. The images of the progress are way cool.

Google Code Blog: Native Client: A Technology for Running Native Code on the Web - These components make it possible to build applications that run in a web browser but incorporate native code modules. Is this Google’s challenge to Adobe Air and Silverlight?

Closeup of mouse image - Engelbart's demo, 40 years later - CNET News – Hard to believe this humble little device started the “revolution”.

Closeup of mouse

Oxite: Microsoft’s new Blogging and CMS Platform – A Microsoft built CMS targeted at developers. Casual users should stick with Wordpress.

Smiling, glasses and hats taboo for driver's license photos – Indiana is using facial recognition software and needs you to not smile or wear glasses.

Balsamiq Studios, makers of plugins for Web Office applications | Balsamiq – Lets you create software mockups in minutes. It deliberately produces images that look hand drawn to keep people focused on the idea and not the presentation. At $80 it’s not for a occasional use but sure would be handy for any UI developer.

Balsamq screen shot 

70 Beautiful Dual-Screen Desktop Wallpapers | Graphics | Smashing Magazine – Very nice collection.

Download McAfee Antivirus Software for Free – Get a free year by following the link. I’m sticking with NOD32.

Advices on partitioning code through .NET assemblies - Patrick Smacchia – The grammar is a bit off but the idea is sound. I’ve made this point over and over to my colleagues at work with little avail. Maybe they’re reading this?

Is F# faster than C# – A bet with a coworker that C# would out perform F# in a simple counting exercise yields some very interesting results. Great detective work and explanation.

Movage – The only way to archive digital information is to keep it moving. Discusses the issues of long term digital storage.

 

FreeSnap 1.5 Released

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.

 

Friday Links #28

Friday Fun: Solve Puzzles to Help Out Scientists - Foldit attempts to predict the structure of a protein by taking advantage of humans' puzzle-solving intuitions and having people play competitively to fold the best proteins. Improve your problem solving skills and the world at the same time.

Worker dies at Long Island Wal-Mart after being trampled in Black Friday stampede – Even more amazing when you consider this was a healthy and large man.

CodeThinked | Taking the Magic out of Expression<T> -  Great summary of what expression trees are and why they are useful.

Sara Ford's WebLog : Did you know… You can double-click on the properties folder in the Solution Explorer to open the project properties page - #368 – This one wins the award for being the most hidden.

Free Web Plan Being Pushed by FCC Head - WSJ.com – Our government actually proposing something useful for a change.

The Best Online Storage Service - Windows SkyDrive – 25GB is great but they still can’t upload an entire folder which makes it somewhat useless.

image

Jeff Blankenburg | Blankenthoughts: Keeping Your Head In The Cloud - Your applications are hosted inside Microsoft's global datacenters, and are automatically distributed and managed.

Python 3.0 Release – New features but no backwards compatibility. Gutsy move but sometimes you have to break things to make them better.

Featured Firefox Extension: OpenXML Viewer Opens Word 2007 Docx Files in Your Browser – Anything to keep Microsoft Word off my computer.

First superconducting transistor promises PC revolution - tech - 03 December 2008 - New Scientist – Still not room temperature but they’re getting closer.

Featured Windows Download: Wordpad 2009 Offers Windows 7-Like Ribbon Interface – Anything to keep Microsoft Word off my computer, anything.

moq – The simplest mocking library for .NET 3.5 with deep C# 3.0 integration - Moq is designed to be a very practical, unobtrusive and straight-forward way to quickly setup dependencies for your tests. Its API design helps even novice users to fall in the "pit of success" and avoid most common misuses/abuses of mocking. Checkout the QuickStart.

 

previous | next

powered by Bloget™