AllYourGiftCardsBelongTeMe - fixing random ERROR_SHARING_VIOLATION in tests that use HttpListener

Functional tests using HttpListener tend to fail randomly with the "System.Net.HttpListenerException : The process cannot access the file because it is being used by another process" exception. This error indicates that the port a test is trying to use is already in use. Tests choose ports randomly from the 8000 to 9000 range. The problem is that on some machines some ports from this range are already in use e.g.:

The following two tests failed with the exception from above:

ConnectionFacts.RequestHeadersCanBeSetOnceConnected.HttpListener.LongPolling.89.test.trace.log                   --> HttpListener url: http://localhost:8678
ConnectionFacts+Start.ManuallyRestartedClientMaintainsConsistentState.HttpListener.Websockets.742.test.trace.log --> HttpListener url: http://localhost:8675

However netstat -ano shows that ports 8675, 8677, 8678 were already in use
TCP    10.74.232.16:8675      10.74.232.80:80        ESTABLISHED     3436   WindowsAzureGuestAgent
TCP    10.74.232.16:8677      10.74.232.80:80        ESTABLISHED     2944   WaAppAgent
TCP    10.74.232.16:8678      168.62.33.142:443      ESTABLISHED     3436   WindowsAzureGuestAgent

The fix is to verify if the port is in use before using it and if it is choose a different port from the range