public async Task ServerCloseOnSslNegotiationCompleteAsyncTest()
        {
            using (FaultyServer server = new FaultyServer())
            {
                server.OnConnectionEvent += (sender, args) =>
                {
                    if (args.EventType == FaultyServer.ConnectionEventType.SslNegotiationComplete)
                    {
                        RntbdTests.RandomSleep();
                        args.Close = true;
                    }
                };
                try
                {
                    await server.StartAsync();

                    Dictionary <OperationType, ResourceOperation> operationMap =
                        new Dictionary <OperationType, ResourceOperation>
                    {
                        [OperationType.Read]   = ResourceOperation.ReadDocument,
                        [OperationType.Upsert] = ResourceOperation.UpsertDocument,
                    };
                    foreach (OperationType operationType in new OperationType[]
                    {
                        OperationType.Read,
                        OperationType.Upsert
                    })
                    {
                        TimeSpan  runTime = TimeSpan.FromSeconds(10.0);
                        Stopwatch sw      = Stopwatch.StartNew();
                        while (sw.Elapsed < runTime)
                        {
                            Guid activityId = Guid.NewGuid();
                            Trace.CorrelationManager.ActivityId = activityId;

                            using (Rntbd.Channel channel = new Rntbd.Channel(
                                       server.Uri,
                                       new Rntbd.ChannelProperties(
                                           new UserAgentContainer(),
                                           certificateHostNameOverride: "localhost",
                                           timerPool: new TimerPool(1),
                                           requestTimeout: TimeSpan.FromSeconds(1.0),
                                           openTimeout: TimeSpan.FromSeconds(1.0),
                                           maxChannels: ushort.MaxValue,
                                           maxRequestsPerChannel: 100,
                                           receiveHangDetectionTime: TimeSpan.FromSeconds(2.0),
                                           sendHangDetectionTime: TimeSpan.FromSeconds(0.5))))
                            {
                                channel.Initialize(activityId);

                                try
                                {
                                    ResourceType      resourceType      = ResourceType.Document;
                                    ResourceOperation resourceOperation = operationMap[operationType];
                                    StoreResponse     response          = await channel.RequestAsync(
                                        DocumentServiceRequest.Create(
                                            operationType,
                                            resourceType,
                                            AuthorizationTokenType.SecondaryReadonlyMasterKey),
                                        new Uri(server.Uri, "foo/bar/baz"),
                                        resourceOperation,
                                        activityId);
                                }
                                catch (DocumentClientException e)
                                {
                                    Assert.AreEqual(activityId.ToString(), e.ActivityId);
                                    if (!string.Equals("ServiceUnavailable", e.Error.Code) &&
                                        !string.Equals("Gone", e.Error.Code))
                                    {
                                        Assert.Fail("Unexpected error code: {0}", e.Error.Code);
                                    }
                                    Exception rootCause     = e;
                                    Exception nextRootCause = e.InnerException;
                                    while (nextRootCause != null)
                                    {
                                        rootCause     = nextRootCause;
                                        nextRootCause = nextRootCause.InnerException;
                                    }
                                    SocketException socketException = rootCause as SocketException;
                                    if (socketException != null)
                                    {
                                        if (socketException.SocketErrorCode != SocketError.ConnectionReset &&
                                            socketException.SocketErrorCode != SocketError.ConnectionAborted)
                                        {
                                            Assert.Fail(
                                                "Expected connection reset or " +
                                                "connection aborted. Actual: {0}",
                                                socketException.SocketErrorCode.ToString());
                                        }
                                    }
                                    else
                                    {
                                        GoneException goneException = rootCause as GoneException;
                                        IOException   ioException   = rootCause as IOException;
                                        Assert.IsTrue(goneException != null || ioException != null,
                                                      "Expected GoneException or IOException. Actual: {0} ({1})",
                                                      rootCause.Message, rootCause.GetType());
                                    }
                                }
                            }
                        }
                    }
                }
                finally
                {
                    await server.StopAsync();
                }
            }
        }
        public async Task CallInitializeFailedChannelAsyncTest()
        {
            TimeSpan  totalRunTime   = TimeSpan.FromSeconds(15.0);
            TimeSpan  channelRunTime = TimeSpan.FromSeconds(5.0);
            Stopwatch outerSw        = Stopwatch.StartNew();

            while (outerSw.Elapsed < totalRunTime)
            {
                Guid activityId = Guid.NewGuid();
                Trace.CorrelationManager.ActivityId = activityId;
                using (Rntbd.Channel channel = new Rntbd.Channel(
                           new Uri("rntbd://localhost:25"),
                           new Rntbd.ChannelProperties(
                               new UserAgentContainer(),
                               certificateHostNameOverride: null,
                               timerPool: new TimerPool(1),
                               requestTimeout: TimeSpan.FromSeconds(1.0),
                               openTimeout: TimeSpan.FromSeconds(1.0),
                               maxChannels: ushort.MaxValue,
                               maxRequestsPerChannel: 100,
                               receiveHangDetectionTime: TimeSpan.FromSeconds(2.0),
                               sendHangDetectionTime: TimeSpan.FromSeconds(0.5))))
                {
                    channel.Initialize(activityId);
                    Stopwatch innerSw = Stopwatch.StartNew();
                    while (innerSw.Elapsed < channelRunTime)
                    {
                        try
                        {
                            StoreResponse response = await channel.RequestAsync(
                                DocumentServiceRequest.Create(
                                    OperationType.Read,
                                    ResourceType.Document,
                                    AuthorizationTokenType.SecondaryReadonlyMasterKey),
                                new Uri("rntbd://localhost:25/foo/bar/baz"),
                                ResourceOperation.ReadDocument,
                                activityId);
                        }
                        catch (DocumentClientException e)
                        {
                            Assert.AreEqual(activityId.ToString(), e.ActivityId);
                            Assert.AreEqual("Gone", e.Error.Code);
                            Exception rootCause     = e;
                            Exception nextRootCause = e.InnerException;
                            while (nextRootCause != null)
                            {
                                rootCause     = nextRootCause;
                                nextRootCause = nextRootCause.InnerException;
                            }
                            SocketException socketException = rootCause as SocketException;
                            if (socketException != null)
                            {
                                if (socketException.SocketErrorCode != SocketError.ConnectionRefused)
                                {
                                    Assert.Fail(
                                        "Expected connection reset or " +
                                        "connection aborted. Actual: {0}",
                                        socketException.SocketErrorCode.ToString());
                                }
                            }
                            else
                            {
                                GoneException goneException = rootCause as GoneException;
                                IOException   ioException   = rootCause as IOException;
                                Assert.IsTrue(goneException != null || ioException != null,
                                              "Expected GoneException or IOException. Actual: {0} ({1})",
                                              rootCause.Message, rootCause.GetType());
                            }
                        }
                    }
                }
            }
        }