How To: Get UITesting methods working outside the TestMethod of Coded UI Test

This is another questions that I have got asked multiple times -

How do I use the methods in Microsoft.VisualStudio.TeamTest.UITesting namespace outside the TestMethod of Coded UI Test?  For example, I want to do a one time initialization of my application settings in ClassInitialize method.  How can I do that?

The answer is to wrap the code with Playback.Initialize() and Playback.Cleanup() calls something like below -

 [ClassInitialize]
public static void MyClassInitialize(TestContext context)
{
    Playback.Initialize(); 
    try
    {
        // Your one time per class initialization code goes here
    }
    finally
    {
        Playback.Cleanup(); 
    }
}

Note that Playback.Initialize() and Playback.Cleanup() calls are NOT needed for TestInitialize and TestCleanup methods where this is done implicitly by the Coded UI Test framework.