public override void Reply(Message message, TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     Message message2 = message;
     if (message != null)
     {
         CorrelationCallbackMessageProperty property;
         this.contextProtocol.OnOutgoingMessage(message, this);
         if (CorrelationCallbackMessageProperty.TryGet(message, out property))
         {
             ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(property, message, false);
             if (property.IsFullyDefined)
             {
                 message2 = property.FinalizeCorrelation(message, helper.RemainingTime());
                 message2.Properties.Remove(CorrelationCallbackMessageProperty.Name);
             }
         }
     }
     try
     {
         this.innerContext.Reply(message2, helper.RemainingTime());
     }
     finally
     {
         if ((message != null) && !object.ReferenceEquals(message, message2))
         {
             message2.Close();
         }
     }
 }
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, AsyncCallback callback, object state)
 {
     ThreadTrace.Trace("BC:BeginWrite");
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.Flush(helper.RemainingTime());
     return base.BeginWrite(buffer, offset, size, immediate, helper.RemainingTime(), callback, state);
 }
        internal async Task<Message> ParseIncomingResponse(TimeoutHelper timeoutHelper)
        {
            ValidateAuthentication();
            ValidateResponseStatusCode();
            bool hasContent = await ValidateContentTypeAsync();
            Message message = null;

            if (!hasContent)
            {
                if (_encoder.MessageVersion == MessageVersion.None)
                {
                    message = new NullMessage();
                }
                else
                {
                    return null;
                }
            }
            else
            {
                message = await ReadStreamAsMessageAsync(timeoutHelper);
            }

            var exception = ProcessHttpAddressing(message);
            Contract.Assert(exception == null, "ProcessHttpAddressing should not set an exception after parsing a response message.");

            return message;
        }
        public override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            base.OnOpen(timeoutHelper.RemainingTime());
            if (this.Factory.ActAsInitiator)
            {
                // 1. Create a token requirement for the provider
                InitiatorServiceModelSecurityTokenRequirement tokenProviderRequirement = CreateInitiatorTokenRequirement();

                // 2. Create a provider
                SecurityTokenProvider tokenProvider = this.Factory.SecurityTokenManager.CreateSecurityTokenProvider(tokenProviderRequirement);
                SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                if (this.Factory.SecurityTokenParameters.HasAsymmetricKey)
                {
                    this.initiatorAsymmetricTokenProvider = tokenProvider;
                }
                else
                {
                    this.initiatorSymmetricTokenProvider = tokenProvider;
                }

                // 3. Create a token requirement for authenticator
                InitiatorServiceModelSecurityTokenRequirement tokenAuthenticatorRequirement = CreateInitiatorTokenRequirement();

                // 4. Create authenticator (we dont support out of band resolvers on the client side
                SecurityTokenResolver outOfBandTokenResolver;
                this.initiatorTokenAuthenticator = this.Factory.SecurityTokenManager.CreateSecurityTokenAuthenticator(tokenAuthenticatorRequirement, out outOfBandTokenResolver);
                SecurityUtils.OpenTokenAuthenticatorIfRequired(this.initiatorTokenAuthenticator, timeoutHelper.RemainingTime());
            }
        }
 public LoadRetryAsyncResult(SqlWorkflowInstanceStore store, System.Runtime.DurableInstancing.InstancePersistenceContext context, System.Runtime.DurableInstancing.InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.InstanceStore = store;
     this.InstancePersistenceContext = context;
     this.InstancePersistenceCommand = command;
     this.commandTimeout = new TimeoutHelper(timeout);
     this.InstanceStore.BeginTryCommandInternal(this.InstancePersistenceContext, this.InstancePersistenceCommand, this.commandTimeout.RemainingTime(), onTryCommandCallback, this);
 }
 protected override SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout)
 {
     SecurityProtocolFactory protocolFactoryForOutgoingMessages = this.ProtocolFactoryForOutgoingMessages;
     SecurityProtocolFactory protocolFactoryForIncomingMessages = this.ProtocolFactoryForIncomingMessages;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     SecurityProtocol outgoingProtocol = (protocolFactoryForOutgoingMessages == null) ? null : protocolFactoryForOutgoingMessages.CreateSecurityProtocol(target, via, listenerSecurityState, false, helper.RemainingTime());
     return new DuplexSecurityProtocol(outgoingProtocol, (protocolFactoryForIncomingMessages == null) ? null : protocolFactoryForIncomingMessages.CreateSecurityProtocol(null, null, listenerSecurityState, false, helper.RemainingTime()));
 }
 public TimeoutStream(Stream stream, ref TimeoutHelper timeoutHelper) : base(stream)
 {
     if (!stream.CanTimeout)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("stream", System.ServiceModel.SR.GetString("StreamDoesNotSupportTimeout"));
     }
     this.timeoutHelper = timeoutHelper;
 }
 protected override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
     base.OnClose(timeoutHelper.RemainingTime());
     if (this.transportManagerContainer != null && !TransferTransportManagers())
     {
         this.transportManagerContainer.Close(timeoutHelper.RemainingTime());
     }
 }
 internal SendReceiveAsyncResult(SendReceiveReliableRequestor requestor, Message request, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.requestor = requestor;
     this.request = request;
     this.timeoutHelper = new TimeoutHelper(timeout);
     if (this.BeginSend())
     {
         base.Complete(true);
     }
 }
 protected override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     base.Connection.Write(SingletonEncoder.EndBytes, 0, SingletonEncoder.EndBytes.Length, true, helper.RemainingTime());
     this.connectionDemuxer.ReuseConnection(this.rawConnection, helper.RemainingTime());
     if (this.channelBindingToken != null)
     {
         this.channelBindingToken.Dispose();
     }
 }
 public SqlCommandAsyncResult(SqlCommand sqlCommand, string connectionString, DependentTransaction dependentTransaction, TimeSpan timeout, int retryCount, int maximumRetries, AsyncCallback callback, object state) : base(callback, state)
 {
     long num = Math.Min(timeout.Ticks, MaximumOpenTimeout.Ticks);
     this.sqlCommand = sqlCommand;
     this.connectionString = connectionString;
     this.dependentTransaction = dependentTransaction;
     this.timeoutHelper = new TimeoutHelper(TimeSpan.FromTicks(num));
     this.retryCount = retryCount;
     this.maximumRetries = maximumRetries;
 }
        public virtual void Abandon(Exception exception, TimeSpan timeout)
        {
            EnsureValidTimeout(timeout);
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.WaitForStateLock(timeoutHelper.RemainingTime());

            try
            {
                if (PreAbandon())
                {
                    return;
                }
            }
            finally
            {
                // Abandon can never be reverted, release the state lock.
                this.ReleaseStateLock();
            }

            bool success = false;
            try
            {
                if (exception == null)
                {
                    OnAbandon(timeoutHelper.RemainingTime());
                }
                else
                {
                    if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
                    {
                        TD.ReceiveContextAbandonWithException(this.eventTraceActivity, this.GetType().ToString(), exception.GetType().ToString());
                    }
                    OnAbandon(exception, timeoutHelper.RemainingTime());
                }
                lock (ThisLock)
                {
                    ThrowIfFaulted();
                    ThrowIfNotAbandoning();
                    this.State = ReceiveContextState.Abandoned;
                }
                success = true;
            }
            finally
            {
                if (!success)
                {
                    if (TD.ReceiveContextAbandonFailedIsEnabled())
                    {
                        TD.ReceiveContextAbandonFailed(this.eventTraceActivity, this.GetType().ToString());
                    }
                    Fault();
                }
            }

        }
 protected virtual IAsyncResult BeginSecureOutgoingMessageAtInitiatorCore(Message message, string actor, TimeSpan timeout, AsyncCallback callback, object state)
 {
     IList<SupportingTokenSpecification> list;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (base.TryGetSupportingTokens(base.SecurityProtocolFactory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         this.SetUpDelayedSecurityExecution(ref message, actor, list);
         return new CompletedAsyncResult<Message>(message, callback, state);
     }
     return new SecureOutgoingMessageAsyncResult(actor, message, this, timeout, callback, state);
 }
 public override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.forwardProtocolFactory != null)
     {
         this.forwardProtocolFactory.Close(false, helper.RemainingTime());
     }
     if (this.reverseProtocolFactory != null)
     {
         this.reverseProtocolFactory.Close(false, helper.RemainingTime());
     }
 }
 public CloseCommunicationAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, object mutex) : base(callback, state)
 {
     this.timeout = timeout;
     this.timeoutHelper = new TimeoutHelper(timeout);
     this.mutex = mutex;
     if (timeout < TimeSpan.Zero)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(System.ServiceModel.SR.GetString("SFxCloseTimedOut1", new object[] { timeout })));
     }
     this.timer = new IOThreadTimer(new Action<object>(CloseCommunicationAsyncResult.TimeoutCallback), this, true);
     this.timer.Set(timeout);
 }
 protected override Message OnRequest(Message request, TimeSpan timeout, bool last)
 {
     RequestContext context;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     base.Binder.Send(request, helper.RemainingTime(), MaskingMode.None);
     TimeSpan receiveTimeout = this.GetReceiveTimeout(helper.RemainingTime());
     base.Binder.TryReceive(receiveTimeout, out context, MaskingMode.None);
     if (context == null)
     {
         return null;
     }
     return context.RequestMessage;
 }
 private void CloseInitiate(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     foreach (InstanceContext context in this.ToArray())
     {
         try
         {
             if (context.State == CommunicationState.Opened)
             {
                 IAsyncResult result = context.BeginClose(helper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(InstanceContextManager.CloseInstanceContextCallback)), context);
                 if (result.CompletedSynchronously)
                 {
                     context.EndClose(result);
                 }
             }
             else
             {
                 context.Abort();
             }
         }
         catch (ObjectDisposedException exception)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
             }
         }
         catch (InvalidOperationException exception2)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information);
             }
         }
         catch (CommunicationException exception3)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information);
             }
         }
         catch (TimeoutException exception4)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Information);
             }
         }
     }
 }
 protected override void VerifyIncomingMessageCore(ref Message message, TimeSpan timeout)
 {
     string actor = string.Empty;
     ReceiveSecurityHeader securityHeader = this.Factory.StandardsManager.CreateReceiveSecurityHeader(message, actor, this.Factory.IncomingAlgorithmSuite, MessageDirection.Input);
     securityHeader.RequireMessageProtection = false;
     securityHeader.ReaderQuotas = this.Factory.SecurityBindingElement.ReaderQuotas;
     IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = base.GetSupportingTokenAuthenticatorsAndSetExpectationFlags(this.Factory, message, securityHeader);
     ReadOnlyCollection<SecurityTokenResolver> outOfBandResolvers = base.MergeOutOfBandResolvers(supportingAuthenticators, this.sessionTokenResolverList);
     if ((supportingAuthenticators != null) && (supportingAuthenticators.Count > 0))
     {
         supportingAuthenticators = new List<SupportingTokenAuthenticatorSpecification>(supportingAuthenticators);
         supportingAuthenticators.Insert(0, this.sessionTokenAuthenticatorSpecificationList[0]);
     }
     else
     {
         supportingAuthenticators = this.sessionTokenAuthenticatorSpecificationList;
     }
     securityHeader.ConfigureTransportBindingServerReceiveHeader(supportingAuthenticators);
     securityHeader.ConfigureOutOfBandTokenResolver(outOfBandResolvers);
     securityHeader.ExpectEndorsingTokens = true;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     securityHeader.SetTimeParameters(this.Factory.NonceCache, this.Factory.ReplayWindow, this.Factory.MaxClockSkew);
     securityHeader.EnforceDerivedKeyRequirement = message.Headers.Action != this.Factory.StandardsManager.SecureConversationDriver.CloseAction.Value;
     securityHeader.Process(helper.RemainingTime(), System.ServiceModel.Security.SecurityUtils.GetChannelBindingFromMessage(message), this.Factory.ExtendedProtectionPolicy);
     if (securityHeader.Timestamp == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString("RequiredTimestampMissingInSecurityHeader")));
     }
     bool flag = false;
     if (securityHeader.EndorsingSupportingTokens != null)
     {
         for (int i = 0; i < securityHeader.EndorsingSupportingTokens.Count; i++)
         {
             SecurityContextSecurityToken token = securityHeader.EndorsingSupportingTokens[i] as SecurityContextSecurityToken;
             if ((token != null) && (token.ContextId == this.sessionId))
             {
                 flag = true;
                 break;
             }
         }
     }
     if (!flag)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString("NoSessionTokenPresentInMessage")));
     }
     message = securityHeader.ProcessedMessage;
     base.AttachRecipientSecurityProperty(message, securityHeader.BasicSupportingTokens, securityHeader.EndorsingSupportingTokens, securityHeader.SignedEndorsingSupportingTokens, securityHeader.SignedSupportingTokens, securityHeader.SecurityTokenAuthorizationPoliciesMapping);
     base.OnIncomingMessageVerified(message);
 }
 protected override IAsyncResult BeginSecureOutgoingMessageAtInitiatorCore(Message message, string actor, TimeSpan timeout, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     this.GetTokensForOutgoingMessages(out token, out token2, out parameters);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (!base.TryGetSupportingTokens(base.SecurityProtocolFactory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         return new SecureOutgoingMessageAsyncResult(actor, message, this, token, token2, parameters, helper.RemainingTime(), callback, state);
     }
     this.SetupDelayedSecurityExecution(actor, ref message, token, token2, parameters, list);
     return new CompletedAsyncResult<Message>(message, callback, state);
 }
        public override async Task<WebSocket> CreateWebSocketAsync(Uri address, WebHeaderCollection headers, ICredentials credentials,
            WebSocketTransportSettings settings, TimeoutHelper timeoutHelper)
        {
            ClientWebSocket webSocket = new ClientWebSocket();
            webSocket.Options.Credentials = credentials;
            webSocket.Options.AddSubProtocol(settings.SubProtocol);
            webSocket.Options.KeepAliveInterval = settings.KeepAliveInterval;
            foreach (var headerObj in headers)
            {
                var header = headerObj as string;
                webSocket.Options.SetRequestHeader(header, headers[header]);
            }

            await webSocket.ConnectAsync(address, timeoutHelper.CancellationToken);
            return webSocket;
        }
 internal ProxyRpc(ServiceChannel channel, ProxyOperationRuntime operation, string action, object[] inputs, TimeSpan timeout)
 {
     this.Action = action;
     this.Activity = null;
     this.Channel = channel;
     this.Correlation = EmptyArray.Allocate(operation.Parent.CorrelationCount);
     this.InputParameters = inputs;
     this.Operation = operation;
     this.OutputParameters = null;
     this.Request = null;
     this.Reply = null;
     this.ActivityId = Guid.Empty;
     this.ReturnValue = null;
     this.MessageVersion = channel.MessageVersion;
     this.TimeoutHelper = new System.Runtime.TimeoutHelper(timeout);
 }
 internal ComposedAsyncResult(TimeSpan timeout, OperationWithTimeoutBeginCallback[] beginOperations, OperationEndCallback[] endOperations, AsyncCallback callback, object state) : base(callback, state)
 {
     this.completedSynchronously = true;
     this.timeoutHelper = new TimeoutHelper(timeout);
     this.beginOperations = beginOperations;
     this.endOperations = endOperations;
     this.SkipToNextOperation();
     if (this.currentOperation < this.beginOperations.Length)
     {
         this.beginOperations[this.currentOperation](this.RemainingTime(), onOperationCompleted, this);
     }
     else
     {
         base.Complete(this.completedSynchronously);
     }
 }
 public override void OnOpen(TimeSpan timeout)
 {
     if (this.serverTokenProvider == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("NoServerX509TokenProvider")));
     }
     TimeoutHelper helper = new TimeoutHelper(timeout);
     System.ServiceModel.Security.SecurityUtils.OpenTokenProviderIfRequired(this.serverTokenProvider, helper.RemainingTime());
     if (this.clientTokenAuthenticator != null)
     {
         System.ServiceModel.Security.SecurityUtils.OpenTokenAuthenticatorIfRequired(this.clientTokenAuthenticator, helper.RemainingTime());
     }
     SecurityToken token = this.serverTokenProvider.GetToken(helper.RemainingTime());
     this.serverToken = this.ValidateX509Token(token);
     base.OnOpen(helper.RemainingTime());
 }
 internal ProxyRpc(ServiceChannel channel, ProxyOperationRuntime operation, string action, object[] inputs, TimeSpan timeout)
 {
     this.Action           = action;
     this.Activity         = null;
     this.Channel          = channel;
     this.Correlation      = EmptyArray.Allocate(operation.Parent.CorrelationCount);
     this.InputParameters  = inputs;
     this.Operation        = operation;
     this.OutputParameters = null;
     this.Request          = null;
     this.Reply            = null;
     this.ActivityId       = Guid.Empty;
     this.ReturnValue      = null;
     this.MessageVersion   = channel.MessageVersion;
     this.TimeoutHelper    = new System.Runtime.TimeoutHelper(timeout);
 }
        // tx aborts can ---- with DeleteMessage but this ---- is harmless because 
        //  - internal state changes are protected via the internalStateLock
        //  - we do not have an ordering requirement between DeleteMessage and a tx abort
        //
        // tx commits cannot ---- with DeleteMessage as the ReceiveContext state machine does not allow
        // DeleteMessage calls if the tx holding this lock committed 
        public void DeleteMessage(MsmqReceiveContext receiveContext, TimeSpan timeout)
        {
            TimeoutHelper helper = new TimeoutHelper(timeout);
            long lookupId = receiveContext.LookupId;
            lock (this.internalStateLock)
            {
                // Expiry map is first checked before calling ReceiveContextExists as we need to throw
                // validity expired exception if the lookup id is not in the map.
                if (this.messageExpiryMap.ContainsKey(lookupId))
                {
                    Fx.Assert(ReceiveContextExists(receiveContext), "Mismatch between the receive context object stored in the map and the object passed to the method");
                    MsmqReceiveContext entry = this.messageExpiryMap[lookupId];
                    if (DateTime.UtcNow > entry.ExpiryTime)
                    {
                        entry.MarkContextExpired();
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MessageValidityExpired, lookupId)));
                    }
                    else
                    {
                        ((ILockingQueue)this.queue).DeleteMessage(lookupId, helper.RemainingTime());

                        if (Transaction.Current != null)
                        {
                            List<MsmqReceiveContext> transMsgs;
                            if (!this.transMessages.TryGetValue(Transaction.Current.TransactionInformation.DistributedIdentifier, out transMsgs))
                            {
                                transMsgs = new List<MsmqReceiveContext>();
                                this.transMessages.Add(Transaction.Current.TransactionInformation.DistributedIdentifier, transMsgs);
                                // only need to attach the tx complete handler once per transaction
                                Transaction.Current.TransactionCompleted += this.transactionCompletedHandler;
                            }
                            transMsgs.Add(entry);
                        }
                        else
                        {
                            this.messageExpiryMap.Remove(lookupId);
                        }
                    }
                }
                else
                {
                    // it was cleaned up by the expiry timer
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MessageValidityExpired, lookupId)));
                }
            }
        }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityToken token3;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     this.GetTokensForOutgoingMessages(out token, out token2, out token3, out parameters);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (base.TryGetSupportingTokens(this.Factory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         SecurityProtocolCorrelationState state2 = this.CreateCorrelationStateIfRequired();
         this.SetUpDelayedSecurityExecution(ref message, token, token2, token3, parameters, list, state2);
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     return new SecureOutgoingMessageAsyncResult(message, this, token, token2, token3, parameters, helper.RemainingTime(), callback, state);
 }
 public override void OnOpen(TimeSpan timeout)
 {
     if ((this.ForwardProtocolFactory != null) && object.ReferenceEquals(this.ForwardProtocolFactory, this.ReverseProtocolFactory))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ReverseProtocolFactory", System.ServiceModel.SR.GetString("SameProtocolFactoryCannotBeSetForBothDuplexDirections"));
     }
     if (this.forwardProtocolFactory != null)
     {
         this.forwardProtocolFactory.ListenUri = base.ListenUri;
     }
     if (this.reverseProtocolFactory != null)
     {
         this.reverseProtocolFactory.ListenUri = base.ListenUri;
     }
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.Open(this.ForwardProtocolFactory, base.ActAsInitiator, "ForwardProtocolFactory", helper.RemainingTime());
     this.Open(this.ReverseProtocolFactory, !base.ActAsInitiator, "ReverseProtocolFactory", helper.RemainingTime());
 }
        internal IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper,
            ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
        {
            connection.Write(Preamble, 0, Preamble.Length, true, timeoutHelper.RemainingTime());

            if (_upgrade != null)
            {
                IStreamUpgradeChannelBindingProvider channelBindingProvider = _upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();

                StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);

                if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder,
                    this, ref timeoutHelper))
                {
                    ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
                }

#if FEATURE_CORECLR // ExtendedProtection
                if (channelBindingProvider != null && channelBindingProvider.IsChannelBindingSupportEnabled)
                {
                    _channelBindingToken = channelBindingProvider.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
                }
#endif // FEATURE_CORECLR // ExtendedProtection

                remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);

                connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0,
                    ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
            }
            else
            {
                remoteSecurity = null;
            }

            // read ACK
            byte[] ackBuffer = new byte[1];
            int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
            if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, decoder, this.Via))
            {
                ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
            }

            return connection;
        }
 public void FlushPendingRecords(TimeSpan timeout)
 {
     try
     {
         if (this.HasPendingRecords)
         {
             TimeoutHelper helper = new TimeoutHelper(timeout);
             for (int i = 0; i < this.trackingParticipants.Count; i++)
             {
                 TrackingParticipant participant = this.trackingParticipants[i];
                 RuntimeTrackingProfile runtimeTrackingProfile = this.GetRuntimeTrackingProfile(participant);
                 if (this.pendingTrackingRecords != null)
                 {
                     for (int j = 0; j < this.pendingTrackingRecords.Count; j++)
                     {
                         TrackingRecord record = this.pendingTrackingRecords[j];
                         TrackingRecord record2 = null;
                         bool shouldClone = this.trackingParticipants.Count > 1;
                         if (runtimeTrackingProfile == null)
                         {
                             record2 = shouldClone ? record.Clone() : record;
                         }
                         else
                         {
                             record2 = runtimeTrackingProfile.Match(record, shouldClone);
                         }
                         if (record2 != null)
                         {
                             participant.Track(record2, helper.RemainingTime());
                             if (TD.TrackingRecordRaisedIsEnabled())
                             {
                                 TD.TrackingRecordRaised(record2.ToString(), participant.GetType().ToString());
                             }
                         }
                     }
                 }
             }
         }
     }
     finally
     {
         this.ClearPendingRecords();
     }
 }
 public override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.serverTokenProvider != null)
     {
         System.ServiceModel.Security.SecurityUtils.CloseTokenProviderIfRequired(this.serverTokenProvider, helper.RemainingTime());
         this.serverTokenProvider = null;
     }
     if (this.clientTokenAuthenticator != null)
     {
         System.ServiceModel.Security.SecurityUtils.CloseTokenAuthenticatorIfRequired(this.clientTokenAuthenticator, helper.RemainingTime());
         this.clientTokenAuthenticator = null;
     }
     if (this.serverToken != null)
     {
         this.serverToken = null;
     }
     base.OnClose(helper.RemainingTime());
 }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     SecurityToken token2;
     SecurityProtocolCorrelationState state2;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.TryGetTokenSynchronouslyForOutgoingSecurity(message, correlationState, false, helper.RemainingTime(), out token, out parameters, out token2, out list, out state2))
     {
         this.SetUpDelayedSecurityExecution(ref message, token2, token, parameters, list, base.GetSignatureConfirmationCorrelationState(correlationState, state2));
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     if (!this.Factory.ActAsInitiator)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ProtocolMustBeInitiator", new object[] { base.GetType().ToString() })));
     }
     return new SecureOutgoingMessageAsyncResult(message, this, this.GetTokenProvider(), this.Factory.ApplyConfidentiality, this.initiatorTokenAuthenticator, correlationState, helper.RemainingTime(), callback, state);
 }
 public IOThreadCancellationTokenSource(TimeSpan timeout)
 {
     TimeoutHelper.ThrowIfNegativeArgument(timeout);
     this.timeout = timeout;
 }
Esempio n. 33
0
 internal ReceiveTimeoutAsyncResult(TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.timeoutHelper = new System.Runtime.TimeoutHelper(timeout);
 }