public static void Snippet29()
        {
            // <Snippet29>
            BasicHttpBinding binding = new BasicHttpBinding();
            EndpointAddress  address = new EndpointAddress("http://localhost:8000/ChannelApp");
            Uri via = new Uri("http://localhost:8000/Via");

            ChannelFactory <IRequestChannel> factory =
                new ChannelFactory <IRequestChannel>(binding, "http://fsHost/fs/endp");

            IRequestChannel channel = factory.CreateChannel(address, via);

            channel.Open();
            Message request = Message.CreateMessage(MessageVersion.Soap11, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
            factory.Close();
            // </Snippet29>
        }
        public static void Snippet31()
        {
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            Object[] bindingParams = new Object[2];

            // <Snippet31>

            EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp");
            IRequestChannel channel = ChannelFactory <IRequestChannel> .CreateChannel(binding, address);

            channel.Open();
            // </Snippet31>

            Message request = Message.CreateMessage(MessageVersion.Default, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
        }
Beispiel #3
0
        public void SendRequestWithoutSecurity()
        {
            string uri = "http://localhost:8888";

            // Open frontend
            Uri             listenUri = new Uri(uri);
            Binding         binding   = new BasicHttpBinding(BasicHttpSecurityMode.None);
            MockBrokerQueue queue     = new MockBrokerQueue();

            queue.DirectReply = true;
            RequestReplyFrontEnd <IReplyChannel> target = new RequestReplyFrontEnd <IReplyChannel>(listenUri, binding, null, queue);

            target.Open();

            // Build channel to send request
            IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>();

            factory.Open();
            IRequestChannel channel = factory.CreateChannel(new EndpointAddress(uri));

            channel.Open();

            Message request = Message.CreateMessage(MessageVersion.Soap11, "UnitTest", "Test");

            try
            {
                Message reply = channel.Request(request);
            }
            catch (FaultException fe)
            {
                Assert.AreEqual(fe.Code.Name, "DummyReply");
            }

            channel.Close();
            factory.Close();
            target.Close();
        }
        public virtual HelloWCFResponse HelloWCF(HelloWCF req)
        {
            // Create request header
            String action;

            action = "http://localhost/ServiceHelloWCF/IServiceHelloWCF/HelloWCF";
            WsWsaHeader header;

            header = new WsWsaHeader(action, null, EndpointAddress, m_version.AnonymousUri, null, null);
            WsMessage request = new WsMessage(header, req, WsPrefix.None);

            // Create request serializer
            HelloWCFDataContractSerializer reqDcs;

            reqDcs             = new HelloWCFDataContractSerializer("HelloWCF", "http://localhost/ServiceHelloWCF");
            request.Serializer = reqDcs;
            request.Method     = "HelloWCF";


            // Send service request
            m_requestChannel.Open();
            WsMessage response = m_requestChannel.Request(request);

            m_requestChannel.Close();

            // Process response
            HelloWCFResponseDataContractSerializer respDcs;

            respDcs = new HelloWCFResponseDataContractSerializer("HelloWCFResponse", "http://localhost/ServiceHelloWCF");
            HelloWCFResponse resp;

            resp = ((HelloWCFResponse)(respDcs.ReadObject(response.Reader)));
            response.Reader.Dispose();
            response.Reader = null;

            return(resp);
        }
Beispiel #5
0
        public static void Snippet16()
        {
            // <Snippet16>
            CustomBinding binding = new CustomBinding();
            HttpTransportBindingElement element    = new HttpTransportBindingElement();
            BindingParameterCollection  parameters = new BindingParameterCollection();
            BindingContext context = new BindingContext(binding, parameters);

            IChannelFactory <IRequestChannel> factory = element.BuildChannelFactory <IRequestChannel>(context);

            factory.Open();
            EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp");
            IRequestChannel channel = factory.CreateChannel(address);

            channel.Open();
            Message request = Message.CreateMessage(MessageVersion.Default, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
            factory.Close();
            // </Snippet16>
        }
 protected override void OnClose(TimeSpan timeout)
 {
     inner.Close(timeout);
 }
Beispiel #7
0
        /// <summary>
        /// Network download from IOActive server for hosted reloc's
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        bool Reloc(string[] args)
        {
            if (args.Length != 4)
            {
                var done = Task.Run(() =>
                {
                    return(PrintHelp(args));
                });
                return(done.Result);
            }

            var Is64            = false;
            var time            = uint.MinValue;
            var Region          = string.Empty;
            var dt              = DateTime.MinValue;
            var KnownAsName     = string.Empty;
            var OrigLoadAddress = ulong.MinValue;

            var TimeStr = args[3];

            Region = args[2];

            if (!bool.TryParse(args[1], out Is64))
            {
                WriteLine($"Error parsing a Boolean value (True or False) from [{args[1]}], unable to continue.");
                return(false);
            }

            if (string.IsNullOrWhiteSpace(Region) || Region.Contains(Path.GetInvalidFileNameChars().ToString()))
            {
                WriteLine($"Must provide a value for the DLL/EXE name to search for (region), provided value [{Region}], unable to continue.");
                return(false);
            }

            if (!uint.TryParse(TimeStr, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out time)
                &&
                !uint.TryParse(TimeStr, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out time)
                &&
                !DateTime.TryParse(TimeStr, out dt)
                )
            {
                WriteLine($"Error parsing a TimeDateStamp value (numeric (hex allowed) or in text form e.g. (8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15) from [{TimeStr}], unable to continue.");
                return(false);
            }
            // if the argument was not a number or string value for date
            // maybe it's a filename to use as a reference? ;)??
            if (dt == DateTime.MinValue && time == uint.MinValue)
            {
                time = PETimeDateStamp(TimeStr);
            }

            // The FinalFileName is only known after the server responds with additional metadata
            var DestName = $"{Region}-?####?-{time:X}.reloc.7z";

            WriteLine($"Contacting, dest file [{DestName}]: 64bit:{Is64}, Region(dll):{Region}, TimeDateStamp:{time:X}.");

            InterWeb          = new Net(@"http://blockwatch.ioactive.com:8888/");
            InterWeb.UserName = "******";
            InterWeb.PassWord = "******";

            //
            // Sending the "Online" packet doesn't really matter since the cred's are sent always.
            // It's more of an application ping/test that you're good to go.
            //
            // Aside from the downloaded .reloc file.  You will also get the preferred load address
            // which can sometimes be missing or altered by due to loader artifacts ? :(
            //

            var FinalFileName =
                Task.Factory.StartNew(() => InterWeb.Online())
                .ContinueWith((isOn) =>
            {
                Task <byte[]> data = null;
                if (isOn.Result)
                {
                    data = Task.Factory.StartNew(() => InterWeb.NetRelocCheck(Region, time, Is64, ref OrigLoadAddress, ref KnownAsName));
                }
                return(data);
            }).Unwrap().ContinueWith((bytez) =>
            {
                var FinalName = $"{KnownAsName}-{OrigLoadAddress:X}-{time:X}.reloc.7z";
                File.WriteAllBytes(FinalName, bytez.Result);
                return(FinalName);
            });

            if (OrigLoadAddress == ulong.MaxValue)
            {
                Write("An error reported from server: ");
            }

            if (!File.Exists(FinalFileName.Result))
            {
                WriteLine("No .reloc available, request an import of the reloc data you need, we will expand the table based on feedback.");
                return(false);
            }

            WriteLine($"Downloaded to {FinalFileName.Result}, size {new FileInfo(FinalFileName.Result).Length}.");
            return(true);


#if FALSE
            var LC = new LoginCredsText()
            {
                username = InterWeb.UserName, password = InterWeb.PassWord
            };
            WriteLine("test1...");
            IChannelFactory <IRequestChannel> factory = new BasicHttpBinding().BuildChannelFactory <IRequestChannel>(new BindingParameterCollection());
            factory.Open();
            IRequestChannel channel = factory.CreateChannel(new EndpointAddress("http://blockwatch.ioactive.com:8888/Buffer/Text/wsHttp"));
            channel.Open();
            Message requestmessage = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IElmerBuffer/Online", LC, new DataContractSerializer(LC.GetType()));
            //send message
            Message replymessage = channel.Request(requestmessage);
            WriteLine("Reply message received");
            WriteLine("Reply action: {0}", replymessage.Headers.Action);
            string data = replymessage.GetBody <string>();
            WriteLine("Reply content: {0}", data);
            //Step5: don't forget to close the message
            requestmessage.Close();
            replymessage.Close();
            //don't forget to close the channel
            channel.Close();
            //don't forget to close the factory
            factory.Close();
#endif
        }
Beispiel #8
0
        protected SecurityToken DoNegotiation(TimeSpan timeout)
        {
            SecurityToken token2;

            this.ThrowIfClosedOrCreated();
            SecurityTraceRecordHelper.TraceBeginSecurityNegotiation <T>((IssuanceTokenProviderBase <T>) this, this.targetAddress);
            TimeoutHelper   helper     = new TimeoutHelper(timeout);
            IRequestChannel rstChannel = null;
            T        negotiationState  = default(T);
            TimeSpan span = timeout;
            int      num  = 1;

            try
            {
                negotiationState = this.CreateNegotiationState(this.targetAddress, this.via, helper.RemainingTime());
                this.InitializeNegotiationState(negotiationState);
                this.InitializeChannelFactories(negotiationState.RemoteAddress, helper.RemainingTime());
                rstChannel = this.CreateClientChannel(negotiationState.RemoteAddress, this.via);
                rstChannel.Open(helper.RemainingTime());
                Message       nextOutgoingMessage = null;
                Message       incomingMessage     = null;
                SecurityToken serviceToken        = null;
                while (true)
                {
                    nextOutgoingMessage = this.GetNextOutgoingMessage(incomingMessage, negotiationState);
                    if (incomingMessage != null)
                    {
                        incomingMessage.Close();
                    }
                    if (nextOutgoingMessage == null)
                    {
                        break;
                    }
                    using (nextOutgoingMessage)
                    {
                        TraceUtility.ProcessOutgoingMessage(nextOutgoingMessage);
                        span            = helper.RemainingTime();
                        incomingMessage = rstChannel.Request(nextOutgoingMessage, span);
                        if (incomingMessage == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("FailToRecieveReplyFromNegotiation")));
                        }
                        TraceUtility.ProcessIncomingMessage(incomingMessage);
                    }
                    num += 2;
                }
                if (!negotiationState.IsNegotiationCompleted)
                {
                    throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NoNegotiationMessageToSend")), incomingMessage);
                }
                try
                {
                    rstChannel.Close(helper.RemainingTime());
                }
                catch (CommunicationException exception)
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                    }
                    rstChannel.Abort();
                }
                catch (TimeoutException exception2)
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information);
                    }
                    rstChannel.Abort();
                }
                rstChannel = null;
                this.ValidateAndCacheServiceToken(negotiationState);
                serviceToken = negotiationState.ServiceToken;
                SecurityTraceRecordHelper.TraceEndSecurityNegotiation <T>((IssuanceTokenProviderBase <T>) this, serviceToken, this.targetAddress);
                token2 = serviceToken;
            }
            catch (Exception exception3)
            {
                if (Fx.IsFatal(exception3))
                {
                    throw;
                }
                if (exception3 is TimeoutException)
                {
                    exception3 = new TimeoutException(System.ServiceModel.SR.GetString("ClientSecurityNegotiationTimeout", new object[] { timeout, num, span }), exception3);
                }
                EndpointAddress targetAddress = (negotiationState == null) ? null : negotiationState.RemoteAddress;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(IssuanceTokenProviderBase <T> .WrapExceptionIfRequired(exception3, targetAddress, this.issuerAddress));
            }
            finally
            {
                this.Cleanup(rstChannel, negotiationState);
            }
            return(token2);
        }
        GenericXmlSecurityToken DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
        {
            if (target == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("target");
            }
            if (operation == SecuritySessionOperation.Renew && currentToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("currentToken");
            }
            IRequestChannel channel = null;

            try
            {
                SecurityTraceRecordHelper.TraceBeginSecuritySessionOperation(operation, target, currentToken);
                channel = this.CreateChannel(operation, target, via);

                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                channel.Open(timeoutHelper.RemainingTime());
                object requestState;
                GenericXmlSecurityToken issuedToken;

                using (Message requestMessage = this.CreateRequest(operation, target, currentToken, out requestState))
                {
                    EventTraceActivity eventTraceActivity = null;
                    if (TD.MessageReceivedFromTransportIsEnabled())
                    {
                        eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(requestMessage);
                    }

                    TraceUtility.ProcessOutgoingMessage(requestMessage, eventTraceActivity);

                    using (Message reply = channel.Request(requestMessage, timeoutHelper.RemainingTime()))
                    {
                        if (reply == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.FailToRecieveReplyFromNegotiation)));
                        }

                        if (eventTraceActivity == null && TD.MessageReceivedFromTransportIsEnabled())
                        {
                            eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(reply);
                        }

                        TraceUtility.ProcessIncomingMessage(reply, eventTraceActivity);
                        ThrowIfFault(reply, this.targetAddress);
                        issuedToken = ProcessReply(reply, operation, requestState);
                        ValidateKeySize(issuedToken);
                    }
                }
                channel.Close(timeoutHelper.RemainingTime());
                this.OnOperationSuccess(operation, target, issuedToken, currentToken);
                return(issuedToken);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (e is TimeoutException)
                {
                    e = new TimeoutException(SR.GetString(SR.ClientSecuritySessionRequestTimeout, timeout), e);
                }

                OnOperationFailure(operation, target, currentToken, e, channel);
                throw;
            }
        }
 protected override void OnClose(TimeSpan timeout)
 {
     _innerChannel.Close(timeout);
 }
    public static void ChannelShape_TypedProxy_InvokeIRequestChannelAsync()
    {
        CustomBinding customBinding = null;
        ChannelFactory <IRequestChannel> factory = null;
        EndpointAddress endpointAddress          = null;
        IRequestChannel channel            = null;
        Message         requestMessage     = null;
        Message         replyMessage       = null;
        string          replyMessageAction = null;
        string          actualResponse     = null;

        try
        {
            // *** SETUP *** \\
            customBinding = new CustomBinding(new BindingElement[] {
                new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
                new HttpTransportBindingElement()
            });
            endpointAddress = new EndpointAddress(Endpoints.DefaultCustomHttp_Address);
            // Create the channel factory for the request-reply message exchange pattern.
            factory = new ChannelFactory <IRequestChannel>(customBinding, endpointAddress);
            // Create the channel.
            channel = factory.CreateChannel();
            channel.Open();
            // Create the Message object to send to the service.
            requestMessage = Message.CreateMessage(
                customBinding.MessageVersion,
                action,
                new CustomBodyWriter(clientMessage));
            string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";

            // *** EXECUTE *** \\
            // Send the Message and receive the Response.
            IAsyncResult ar = channel.BeginRequest(requestMessage, null, null);
            replyMessage       = channel.EndRequest(ar);
            replyMessageAction = replyMessage.Headers.Action;

            // *** VALIDATE *** \\
            Assert.True(String.Equals(replyMessageAction, action + "Response"),
                        String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}",
                                      action + "Response", replyMessageAction));

            // *** EXECUTE *** \\
            var replyReader = replyMessage.GetReaderAtBodyContents();
            actualResponse = replyReader.ReadElementContentAsString();

            // *** VALIDATE *** \\
            Assert.True(String.Equals(actualResponse, expectedResponse),
                        String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}",
                                      expectedResponse, actualResponse));

            // *** CLEANUP *** \\
            replyMessage.Close();
            channel.Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            replyMessage.Close();
            ScenarioTestHelpers.CloseCommunicationObjects(channel, factory);
        }
    }
        public void MessageSecurityManualProtection()
        {
            SymmetricSecurityBindingElement sbe =
                new SymmetricSecurityBindingElement();

            sbe.ProtectionTokenParameters =
                new X509SecurityTokenParameters();
            RequestSender sender = delegate(Message input)
            {
                MessageBuffer buf = input.CreateBufferedCopy(0x10000);
                using (XmlWriter w = XmlWriter.Create(Console.Error))
                {
                    buf.CreateMessage().WriteMessage(w);
                }
                return(buf.CreateMessage());
            };

            CustomBinding binding = new CustomBinding(
                sbe,
                new TextMessageEncodingBindingElement(),
                new HandlerTransportBindingElement(sender));

            EndpointAddress address = new EndpointAddress(
                new Uri("http://localhost:37564"),
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono")));

            ChannelProtectionRequirements reqs =
                new ChannelProtectionRequirements();

            reqs.OutgoingSignatureParts.AddParts(
                new MessagePartSpecification(new XmlQualifiedName("SampleValue", "urn:foo")), "urn:myaction");
            BindingParameterCollection parameters =
                new BindingParameterCollection();

            parameters.Add(reqs);

            /*
             *                      SymmetricSecurityBindingElement innersbe =
             *                              new SymmetricSecurityBindingElement ();
             *                      innersbe.ProtectionTokenParameters =
             *                              new X509SecurityTokenParameters ();
             *                      sbe.ProtectionTokenParameters =
             *                              new SecureConversationSecurityTokenParameters (
             *                                      innersbe, false, reqs);
             */

            IChannelFactory <IRequestChannel> cf =
                binding.BuildChannelFactory <IRequestChannel> (parameters);

            cf.Open();
            IRequestChannel ch = cf.CreateChannel(address);

            ch.Open();
            try
            {
                ch.Request(Message.CreateMessage(MessageVersion.None, "urn:myaction", new SampleValue()));
            }
            finally
            {
                ch.Close();
            }
        }
Beispiel #13
0
 public void closeChannel()
 {
     m_requestChannel.Close();
 }
Beispiel #14
0
 public void Close(TimeSpan timeout)
 {
     _innerChannel.Close(timeout);
 }
Beispiel #15
0
 public void CloseAfterFault(TimeSpan timeout)
 {
     _channel.Close(timeout);
 }
Beispiel #16
0
        // It is almost identical to http-low-level-binding
        public void LowLevelHttpConnection()
        {
            HttpTransportBindingElement lel =
                new HttpTransportBindingElement();

            // Service
            BindingContext lbc = new BindingContext(
                new CustomBinding(),
                new BindingParameterCollection(),
                new Uri("http://localhost:" + NetworkHelpers.FindFreePort()),
                String.Empty, ListenUriMode.Explicit);

            listener = lel.BuildChannelListener <IReplyChannel> (lbc);

            try {
                listener.Open();

                svcret = "";

                Thread svc = new Thread(delegate() {
                    try {
                        svcret = LowLevelHttpConnection_SetupService();
                    } catch (Exception ex) {
                        svcret = ex.ToString();
                    }
                });
                svc.Start();

                // Client code goes here.

                HttpTransportBindingElement el =
                    new HttpTransportBindingElement();
                BindingContext ctx = new BindingContext(
                    new CustomBinding(),
                    new BindingParameterCollection());
                IChannelFactory <IRequestChannel> factory =
                    el.BuildChannelFactory <IRequestChannel> (ctx);

                factory.Open();

                IRequestChannel request = factory.CreateChannel(
                    new EndpointAddress("http://localhost:" + NetworkHelpers.FindFreePort()));

                request.Open();

                try {
                    try {
                        Message reqmsg = Message.CreateMessage(
                            MessageVersion.Default, "Echo");
                        // sync version does not work here.
                        Message msg = request.Request(reqmsg, TimeSpan.FromSeconds(5));

                        using (XmlWriter w = XmlWriter.Create(TextWriter.Null)) {
                            msg.WriteMessage(w);
                        }

                        if (svcret != null)
                        {
                            Assert.Fail(svcret.Length > 0 ? svcret : "service code did not finish until this test expected.");
                        }
                    } finally {
                        if (request.State == CommunicationState.Opened)
                        {
                            request.Close();
                        }
                    }
                } finally {
                    if (factory.State == CommunicationState.Opened)
                    {
                        factory.Close();
                    }
                }
            } finally {
                if (listener.State == CommunicationState.Opened)
                {
                    listener.Close();
                }
            }
        }
 public void Close()
 {
     _innerChannel.Close();
 }
        /*
         *   Negotiation consists of the following steps (some may be async in the async case):
         *   1. Create negotiation state
         *   2. Initialize channel factories
         *   3. Create an channel
         *   4. Open the channel
         *   5. Create the next message to send to server
         *   6. Send the message and get reply
         *   8. Process incoming message and get next outgoing message.
         *   9. If no outgoing message, then negotiation is over. Go to step 11.
         *   10. Goto step 6
         *   11. Close the IRequest channel and complete
         */
        protected SecurityToken DoNegotiation(TimeSpan timeout)
        {
            ThrowIfClosedOrCreated();
            SecurityTraceRecordHelper.TraceBeginSecurityNegotiation(this, this.targetAddress);
            TimeoutHelper   timeoutHelper = new TimeoutHelper(timeout);
            IRequestChannel rstChannel    = null;
            T        negotiationState     = null;
            TimeSpan timeLeft             = timeout;
            int      legs = 1;

            try
            {
                negotiationState = this.CreateNegotiationState(this.targetAddress, this.via, timeoutHelper.RemainingTime());
                InitializeNegotiationState(negotiationState);
                this.InitializeChannelFactories(negotiationState.RemoteAddress, timeoutHelper.RemainingTime());
                rstChannel = this.CreateClientChannel(negotiationState.RemoteAddress, this.via);
                rstChannel.Open(timeoutHelper.RemainingTime());
                Message       nextOutgoingMessage = null;
                Message       incomingMessage     = null;
                SecurityToken serviceToken        = null;
                for (;;)
                {
                    nextOutgoingMessage = this.GetNextOutgoingMessage(incomingMessage, negotiationState);
                    if (incomingMessage != null)
                    {
                        incomingMessage.Close();
                    }
                    if (nextOutgoingMessage != null)
                    {
                        using (nextOutgoingMessage)
                        {
                            EventTraceActivity eventTraceActivity = null;
                            if (TD.MessageSentToTransportIsEnabled())
                            {
                                eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(nextOutgoingMessage);
                            }

                            TraceUtility.ProcessOutgoingMessage(nextOutgoingMessage, eventTraceActivity);
                            timeLeft        = timeoutHelper.RemainingTime();
                            incomingMessage = rstChannel.Request(nextOutgoingMessage, timeLeft);
                            if (incomingMessage == null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.FailToRecieveReplyFromNegotiation)));
                            }

                            if (eventTraceActivity == null && TD.MessageReceivedFromTransportIsEnabled())
                            {
                                eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(incomingMessage);
                            }

                            TraceUtility.ProcessIncomingMessage(incomingMessage, eventTraceActivity);
                        }
                        legs += 2;
                    }
                    else
                    {
                        if (!negotiationState.IsNegotiationCompleted)
                        {
                            throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoNegotiationMessageToSend)), incomingMessage);
                        }

                        try
                        {
                            rstChannel.Close(timeoutHelper.RemainingTime());
                        }
                        catch (CommunicationException e)
                        {
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);

                            rstChannel.Abort();
                        }
                        catch (TimeoutException e)
                        {
                            if (TD.CloseTimeoutIsEnabled())
                            {
                                TD.CloseTimeout(e.Message);
                            }
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);

                            rstChannel.Abort();
                        }

                        rstChannel = null;
                        this.ValidateAndCacheServiceToken(negotiationState);
                        serviceToken = negotiationState.ServiceToken;
                        SecurityTraceRecordHelper.TraceEndSecurityNegotiation(this, serviceToken, this.targetAddress);
                        break;
                    }
                }
                return(serviceToken);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (e is TimeoutException)
                {
                    e = new TimeoutException(SR.GetString(SR.ClientSecurityNegotiationTimeout, timeout, legs, timeLeft), e);
                }
                EndpointAddress temp = (negotiationState == null) ? null : negotiationState.RemoteAddress;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WrapExceptionIfRequired(e, temp, this.issuerAddress));
            }
            finally
            {
                Cleanup(rstChannel, negotiationState);
            }
        }