public async Task<ReceivingAmqpLink> CreateReceivingLinkAsync(string path, IotHubConnectionString connectionString, TimeSpan timeout, uint prefetchCount)
        {
            this.OnCreateReceivingLink(connectionString);

            var timeoutHelper = new TimeoutHelper(timeout);

            AmqpSession session;
            if (!this.FaultTolerantSession.TryGetOpenedObject(out session))
            {
                session = await this.FaultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime());
            }

            var linkAddress = this.BuildLinkAddress(connectionString, path);

            var linkSettings = new AmqpLinkSettings()
            {
                Role = true,
                TotalLinkCredit = prefetchCount,
                AutoSendFlow = prefetchCount > 0,
                Source = new Source() { Address = linkAddress.AbsoluteUri },
                SndSettleMode = null, // SenderSettleMode.Unsettled (null as it is the default and to avoid bytes on the wire)
                RcvSettleMode = (byte)ReceiverSettleMode.Second, 
                LinkName = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debuggin
            };

            SetLinkSettingsCommonProperties(linkSettings, timeoutHelper.RemainingTime());

            var link = new ReceivingAmqpLink(linkSettings);
            link.AttachTo(session);

            var audience = this.BuildAudience(connectionString, path);
            await this.OpenLinkAsync(link, connectionString, audience, timeoutHelper.RemainingTime());

            return link;
        }
Example #2
0
        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 async Task<SendingAmqpLink> CreateSendingLinkAsync(string path, TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            AmqpSession session;
            if (!this.faultTolerantSession.TryGetOpenedObject(out session))
            {
                session = await this.faultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime());
            }

            var linkAddress = this.connectionString.BuildLinkAddress(path);

            var linkSettings = new AmqpLinkSettings()
            {
                Role = false,
                InitialDeliveryCount = 0,
                Target = new Target() { Address = linkAddress.AbsoluteUri },
                SndSettleMode = null, // SenderSettleMode.Unsettled (null as it is the default and to avoid bytes on the wire)
                RcvSettleMode = null, // (byte)ReceiverSettleMode.First (null as it is the default and to avoid bytes on the wire)
                LinkName = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debugging
            };

            SetLinkSettingsCommonProperties(linkSettings, timeoutHelper.RemainingTime());

            var link = new SendingAmqpLink(linkSettings);
            link.AttachTo(session);

            await OpenLinkAsync(link, timeoutHelper.RemainingTime());

            return link;
        }
 public OpenCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection) : base(otherCallback, state)
 {
     this.timeoutHelper = new TimeoutHelper(timeout);
     this.completedSynchronously = true;
     this.count = collection.Count;
     if (this.count == 0)
     {
         base.Complete(true);
     }
     else
     {
         for (int i = 0; i < collection.Count; i++)
         {
             if (this.exception != null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.exception);
             }
             CallbackState state2 = new CallbackState(this, collection[i]);
             IAsyncResult result = collection[i].BeginOpen(this.timeoutHelper.RemainingTime(), nestedCallback, state2);
             if (result.CompletedSynchronously)
             {
                 collection[i].EndOpen(result);
                 this.Decrement(true);
             }
         }
     }
 }
        public OpenCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection)
            : base(otherCallback, state)
        {
            _timeoutHelper = new TimeoutHelper(timeout);
            _completedSynchronously = true;

            _count = collection.Count;
            if (_count == 0)
            {
                Complete(true);
                return;
            }

            for (int index = 0; index < collection.Count; index++)
            {
                // Throw exception if there was a failure calling EndOpen in the callback (skips remaining items)
                if (_exception != null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_exception);
                CallbackState callbackState = new CallbackState(this, collection[index]);
                IAsyncResult result = collection[index].BeginOpen(_timeoutHelper.RemainingTime(), s_nestedCallback, callbackState);
                if (result.CompletedSynchronously)
                {
                    collection[index].EndOpen(result);
                    Decrement(true);
                }
            }
        }
 public static void DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection, Uri via, string contentType, ref TimeoutHelper timeoutHelper)
 {
     ValidateReadingFaultString(decoder);
     int offset = 0;
     byte[] buffer = DiagnosticUtility.Utility.AllocateByteArray(0x100);
     int size = connection.Read(buffer, offset, buffer.Length, timeoutHelper.RemainingTime());
     while (size > 0)
     {
         int num3 = decoder.Decode(buffer, offset, size);
         offset += num3;
         size -= num3;
         if (decoder.CurrentState == ClientFramingDecoderState.Fault)
         {
             ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime());
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType));
         }
         if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString)
         {
             throw Fx.AssertAndThrow("invalid framing client state machine");
         }
         if (size == 0)
         {
             offset = 0;
             size = connection.Read(buffer, offset, buffer.Length, timeoutHelper.RemainingTime());
         }
     }
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
 }
        protected override async Task<AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            if (this.iotHubTokenRefresher != null)
            {
                this.iotHubTokenRefresher.Cancel();
            }

            AmqpSession amqpSession = await base.CreateSessionAsync(timeoutHelper.RemainingTime());

#if !WINDOWS_UWP
            if (this.AmqpTransportSettings.ClientCertificate == null)
            {
#endif
                this.iotHubTokenRefresher = new IotHubTokenRefresher(
                   amqpSession,
                   this.ConnectionString,
                   this.ConnectionString.AmqpEndpoint.AbsoluteUri
                   );

                // Send Cbs token for new connection first
                await this.iotHubTokenRefresher.SendCbsTokenAsync(timeoutHelper.RemainingTime());
#if !WINDOWS_UWP
            }
#endif

            return amqpSession;
        }
 public FloodAsyncResult(PeerNeighborManager owner, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.pending = new List<IAsyncResult>();
     this.results = new Dictionary<IAsyncResult, IPeerNeighbor>();
     this.thisLock = new object();
     this.pnm = owner;
     this.timeoutHelper = new TimeoutHelper(timeout);
 }
 public AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state)
 {
     if ((this.pendingMessage == null) && (this.pendingException == null))
     {
         this.readTimeoutHelper = new TimeoutHelper(timeout);
         while (!this.isAtEOF)
         {
             AsyncReadResult result;
             if (this.size > 0)
             {
                 this.pendingMessage = this.DecodeMessage(this.readTimeoutHelper.RemainingTime());
                 if (this.pendingMessage != null)
                 {
                     this.PrepareMessage(this.pendingMessage);
                     return AsyncReceiveResult.Completed;
                 }
                 if (this.isAtEOF)
                 {
                     return AsyncReceiveResult.Completed;
                 }
             }
             if (this.size != 0)
             {
                 throw Fx.AssertAndThrow("BeginReceive: DecodeMessage() should consume the outstanding buffer or return a message.");
             }
             if (!this.usingAsyncReadBuffer)
             {
                 this.buffer = this.connection.AsyncReadBuffer;
                 this.usingAsyncReadBuffer = true;
             }
             this.pendingCallback = callback;
             this.pendingCallbackState = state;
             bool flag = true;
             try
             {
                 result = this.connection.BeginRead(0, this.buffer.Length, this.readTimeoutHelper.RemainingTime(), this.onAsyncReadComplete, null);
                 flag = false;
             }
             finally
             {
                 if (flag)
                 {
                     this.pendingCallback = null;
                     this.pendingCallbackState = null;
                 }
             }
             if (result == AsyncReadResult.Queued)
             {
                 return AsyncReceiveResult.Pending;
             }
             this.pendingCallback = null;
             this.pendingCallbackState = null;
             int bytesRead = this.connection.EndRead();
             this.HandleReadComplete(bytesRead, false);
         }
     }
     return AsyncReceiveResult.Completed;
 }
Example #10
0
 internal ChunkingWriter(Message originalMessage,TimeoutHelper chunkingTimeout, IOutputChannel outputChannel) : base()
 {
     this.version = originalMessage.Version;
     this.originalMessage = originalMessage;
     this.chunkingTimeout = chunkingTimeout;
     this.outputChannel = outputChannel;
     this.startState = new StartChunkState();
     chunkNum = 1;
 }
 public IConnection Connect(Uri uri, TimeSpan timeout)
 {
     if (DiagnosticUtility.ShouldTraceInformation)
     {
         TraceUtility.TraceEvent(TraceEventType.Information, 0x4002b, System.ServiceModel.SR.GetString("TraceCodeInitiatingTcpConnection"), new StringTraceRecord("Uri", uri.ToString()), this, null);
     }
     int port = uri.Port;
     IPAddress[] iPAddresses = GetIPAddresses(uri);
     Socket socket = null;
     SocketException innerException = null;
     if (port == -1)
     {
         port = 0x328;
     }
     int invalidAddressCount = 0;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     for (int i = 0; i < iPAddresses.Length; i++)
     {
         if (helper.RemainingTime() == TimeSpan.Zero)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateTimeoutException(uri, helper.OriginalTimeout, iPAddresses, invalidAddressCount, innerException));
         }
         AddressFamily addressFamily = iPAddresses[i].AddressFamily;
         if ((addressFamily == AddressFamily.InterNetworkV6) && !Socket.OSSupportsIPv6)
         {
             iPAddresses[i] = null;
         }
         else
         {
             DateTime utcNow = DateTime.UtcNow;
             try
             {
                 socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
                 socket.Connect(new IPEndPoint(iPAddresses[i], port));
                 innerException = null;
                 break;
             }
             catch (SocketException exception2)
             {
                 invalidAddressCount++;
                 TraceConnectFailure(socket, exception2, uri, (TimeSpan) (DateTime.UtcNow - utcNow));
                 innerException = exception2;
                 socket.Close();
             }
         }
     }
     if (socket == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(System.ServiceModel.SR.GetString("NoIPEndpointsFoundForHost", new object[] { uri.Host })));
     }
     if (innerException != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertConnectException(innerException, uri, helper.ElapsedTime(), innerException));
     }
     return this.CreateConnection(socket);
 }
Example #12
0
 internal ChunkingReader(Message startMessage, int maxBufferedChunks, TimeoutHelper receiveTimeout)
 {
     //set innerReader
     this.innerReader = startMessage.GetReaderAtBodyContents();
     this.lockobject = new object();
     this.messageId = ChunkingUtils.GetMessageHeader<Guid>(startMessage,
         ChunkingUtils.MessageIdHeader, ChunkingUtils.ChunkNs);
     this.bufferedChunks = new SynchronizedQueue<Message>(maxBufferedChunks);
     this.receiveTimeout = receiveTimeout;
     this.nextChunkNum = 1;
 }
        public TimeoutStream(Stream stream, TimeSpan timeout)
            : base(stream)
        {
            if (!stream.CanTimeout)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("stream", SR.StreamDoesNotSupportTimeout);
            }

            _timeoutHelper = new TimeoutHelper(timeout);
            ReadTimeout = TimeoutHelper.ToMilliseconds(timeout);
            WriteTimeout = ReadTimeout;
        }
Example #14
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _timeoutHelper = default(TimeoutHelper);
                }

                _disposed = true;
            }
            base.Dispose(disposing);
        }
 public virtual void Abandon(Exception exception, TimeSpan timeout)
 {
     this.EnsureValidTimeout(timeout);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.WaitForStateLock(helper.RemainingTime());
     try
     {
         if (this.PreAbandon())
         {
             return;
         }
     }
     finally
     {
         this.ReleaseStateLock();
     }
     bool flag = false;
     try
     {
         if (exception == null)
         {
             this.OnAbandon(helper.RemainingTime());
         }
         else
         {
             if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
             {
                 TD.ReceiveContextAbandonWithException(base.GetType().ToString(), exception.GetType().ToString());
             }
             this.OnAbandon(exception, helper.RemainingTime());
         }
         lock (this.ThisLock)
         {
             this.ThrowIfFaulted();
             this.ThrowIfNotAbandoning();
             this.State = ReceiveContextState.Abandoned;
         }
         flag = true;
     }
     finally
     {
         if (!flag)
         {
             if (TD.ReceiveContextAbandonFailedIsEnabled())
             {
                 TD.ReceiveContextAbandonFailed(base.GetType().ToString());
             }
             this.Fault();
         }
     }
 }
        public void Open(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            if (this.securityProtocolFactory != null)
            {
                this.securityProtocolFactory.Open(false, timeoutHelper.RemainingTime());
            }
            if (this.sessionMode && this.sessionSettings != null)
            {
                this.sessionSettings.Open(timeoutHelper.RemainingTime());
            } 

            this.innerListener.Open(timeoutHelper.RemainingTime());

            this.SetBufferManager();        
        }
 public void Start(TimeSpan timeout)
 {
     if (this.cancelled)
     {
         return;
     }
     this.timeoutHelper = new TimeoutHelper(timeout);
     this.timeoutHelper.RemainingTime();
     if (this.maxDelay == TimeSpan.Zero)
     {
         StartZeroDelay();
     }
     else
     {
         StartSchedule();
     }
 }
 public static bool InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, ref IConnection connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, ref TimeoutHelper timeoutHelper)
 {
     for (string str = upgradeInitiator.GetNextUpgrade(); str != null; str = upgradeInitiator.GetNextUpgrade())
     {
         EncodedUpgrade upgrade = new EncodedUpgrade(str);
         connection.Write(upgrade.EncodedBytes, 0, upgrade.EncodedBytes.Length, true, timeoutHelper.RemainingTime());
         byte[] buffer = new byte[1];
         int count = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
         if (!ValidateUpgradeResponse(buffer, count, decoder))
         {
             return false;
         }
         ConnectionStream stream = new ConnectionStream(connection, defaultTimeouts);
         Stream stream2 = upgradeInitiator.InitiateUpgrade(stream);
         connection = new StreamConnection(stream2, stream);
     }
     return true;
 }
 void CloseInitiate(TimeSpan timeout)
 {
     TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
     InstanceContext[] instances = this.ToArray();
     for (int index = 0; index < instances.Length; index++)
     {
         InstanceContext instance = instances[index];
         try
         {
             if (instance.State == CommunicationState.Opened)
             {
                 IAsyncResult result = instance.BeginClose(timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(CloseInstanceContextCallback)), instance);
                 if (!result.CompletedSynchronously)
                     continue;
                 instance.EndClose(result);
             }
             else
             {
                 instance.Abort();
             }
         }
         catch (ObjectDisposedException e)
         {
             DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
         }
         catch (InvalidOperationException e)
         {
             DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
         }
         catch (CommunicationException e)
         {
             DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
         }
         catch (TimeoutException e)
         {
             if (TD.CloseTimeoutIsEnabled())
             {
                 TD.CloseTimeout(e.Message);
             }
             DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
         }
     }
 }
Example #20
0
        public override bool ConnectAsync(TimeSpan timeout, TransportAsyncCallbackArgs callbackArgs)
        {
            this.callbackArgs = callbackArgs;
            this.timeoutHelper = new TimeoutHelper(timeout);
            TransportInitiator innerInitiator = this.transportSettings.InnerTransportSettings.CreateInitiator();

            TransportAsyncCallbackArgs innerArgs = new TransportAsyncCallbackArgs();
            innerArgs.CompletedCallback = OnInnerTransportConnected;
            innerArgs.UserToken = this;
            if (innerInitiator.ConnectAsync(timeout, innerArgs))
            {
                // pending
                return true;
            }
            else
            {
                this.HandleInnerTransportConnected(innerArgs);
                return !this.callbackArgs.CompletedSynchronously;
            }
        }
        public override ReceiveResult TryReceive(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode)
        {
            // ignore the transactionMode
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            MsmqQueueHandle handle = GetHandle();

            while (true)
            {
                int error = PeekLockCore(handle, (MsmqInputMessage)message, timeoutHelper.RemainingTime());

                if (error == 0)
                {
                    return ReceiveResult.MessageReceived;
                }

                if (IsReceiveErrorDueToInsufficientBuffer(error))
                {
                    message.GrowBuffers();
                    continue;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_IO_TIMEOUT)
                {
                    return ReceiveResult.Timeout;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_OPERATION_CANCELLED)
                {
                    return ReceiveResult.OperationCancelled;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_INVALID_HANDLE)
                {
                    // should happen only if racing with Close
                    return ReceiveResult.OperationCancelled;
                }
                else if (IsErrorDueToStaleHandle(error))
                {
                    HandleIsStale(handle);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error));
            }
        }
		public static int Read(PipeStream stream, byte[] buffer, int offset, int count, bool isAsync, TimeoutHelper timeoutHelper)
		{
			// 异步时,使用异步方式读取数据
			if (isAsync)
			{
				IAsyncResult asyncResult = stream.BeginRead(buffer, offset, count, null, null);

				// 等待 timeoutHelper 计算后的剩余时间,如果在这段时间内没有读到数据,那么将直接返回,这时,由于没有读到数据,返回的数据长度为 0
				asyncResult.AsyncWaitHandle.WaitOne(timeoutHelper == null ? 60000 : (int)timeoutHelper.RemainingTime().TotalMilliseconds);

				if (asyncResult.GetType() == pipeStreamAsyncResultType)
				{
				    pipeStreamAsyncResult_waitHandle.SetValue(asyncResult, null);
				}

				return stream.EndRead(asyncResult);
			}

			// 使用系统内置的方式进行同步阻塞式读取,该方法直到读取到数据才返回
			return stream.Read(buffer, offset, count);
		}
        protected override async Task<AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            if (this.iotHubTokenRefresher != null)
            {
                this.iotHubTokenRefresher.Cancel();
            }

            AmqpSession amqpSession = await base.CreateSessionAsync(timeoutHelper.RemainingTime());
            this.iotHubTokenRefresher = new IotHubTokenRefresher(
                amqpSession, 
                this.ConnectionString, 
                this.ConnectionString.AmqpEndpoint.AbsoluteUri
                );

            // Send Cbs token for new connection first
            await this.iotHubTokenRefresher.SendCbsTokenAsync(timeoutHelper.RemainingTime());

            return amqpSession;
        }
        public CloseCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection)
            : base(otherCallback, state)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            _completedSynchronously = true;

            _count = collection.Count;
            if (_count == 0)
            {
                Complete(true);
                return;
            }

            for (int index = 0; index < collection.Count; index++)
            {
                CallbackState callbackState = new CallbackState(this, collection[index]);
                IAsyncResult result;
                try
                {
                    result = collection[index].BeginClose(timeoutHelper.RemainingTime(), s_nestedCallback, callbackState);
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    Decrement(true, e);
                    collection[index].Abort();
                    continue;
                }

                if (result.CompletedSynchronously)
                {
                    CompleteClose(collection[index], result);
                }
            }
        }
        public async Task<bool> WaitForMessageAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as 
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!await _sourceLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout)))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new TimeoutException(SR.Format(SR.WaitForMessageTimedOut, timeout),
                    TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }
            try
            {
                return await _source.WaitForMessageAsync(timeoutHelper.RemainingTime());
            }
            finally
            {
                _sourceLock.Release();
            }
        }
Example #26
0
        protected internal override Task OnOpenAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            return(TaskHelpers.CompletedTask());
        }
        async Task <ReceivingAmqpLink> CreateLinkAsync(TimeSpan timeout)
        {
            var amqpEventHubClient = ((AmqpEventHubClient)this.EventHubClient);

            var            timeoutHelper = new TimeoutHelper(timeout);
            AmqpConnection connection    = await amqpEventHubClient.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            // Authenticate over CBS
            var cbsLink = connection.Extensions.Find <AmqpCbsLink>();

            ICbsTokenProvider cbsTokenProvider = amqpEventHubClient.CbsTokenProvider;
            Uri    address   = new Uri(amqpEventHubClient.ConnectionStringBuilder.Endpoint, this.Path);
            string audience  = address.AbsoluteUri;
            string resource  = address.AbsoluteUri;
            var    expiresAt = await cbsLink.SendTokenAsync(cbsTokenProvider, address, audience, resource, new[] { ClaimConstants.Listen }, timeoutHelper.RemainingTime()).ConfigureAwait(false);

            AmqpSession session = null;

            try
            {
                // Create our Session
                var sessionSettings = new AmqpSessionSettings {
                    Properties = new Fields()
                };
                session = connection.CreateSession(sessionSettings);
                await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                FilterSet filterMap = null;
                var       filters   = this.CreateFilters();
                if (filters != null && filters.Count > 0)
                {
                    filterMap = new FilterSet();
                    foreach (var filter in filters)
                    {
                        filterMap.Add(filter.DescriptorName, filter);
                    }
                }

                // Create our Link
                var linkSettings = new AmqpLinkSettings
                {
                    Role            = true,
                    TotalLinkCredit = (uint)this.PrefetchCount,
                    AutoSendFlow    = this.PrefetchCount > 0
                };
                linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)MessagingEntityType.ConsumerGroup);
                linkSettings.Source = new Source {
                    Address = address.AbsolutePath, FilterSet = filterMap
                };
                linkSettings.Target = new Target {
                    Address = this.ClientId
                };
                linkSettings.SettleType = SettleMode.SettleOnSend;

                // Receiver metrics enabled?
                if (this.ReceiverRuntimeMetricEnabled)
                {
                    linkSettings.DesiredCapabilities = new Multiple <AmqpSymbol>(new List <AmqpSymbol>
                    {
                        AmqpClientConstants.EnableReceiverRuntimeMetricName
                    });
                }

                if (this.Epoch.HasValue)
                {
                    linkSettings.AddProperty(AmqpClientConstants.AttachEpoch, this.Epoch.Value);
                }

                if (!string.IsNullOrWhiteSpace(this.Identifier))
                {
                    linkSettings.AddProperty(AmqpClientConstants.ReceiverIdentifierName, this.Identifier);
                }

                var link = new ReceivingAmqpLink(linkSettings);
                linkSettings.LinkName = $"{amqpEventHubClient.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}";
                link.AttachTo(session);

                await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                var activeClientLink = new ActiveClientLink(
                    link,
                    audience,                                                         // audience
                    this.EventHubClient.ConnectionStringBuilder.Endpoint.AbsoluteUri, // endpointUri
                    new[] { ClaimConstants.Listen },
                    true,
                    expiresAt);

                this.clientLinkManager.SetActiveLink(activeClientLink);

                return(link);
            }
            catch
            {
                // Cleanup any session (and thus link) in case of exception.
                session?.Abort();
                throw;
            }
        }
        protected override SecurityProtocolCorrelationState VerifyIncomingMessageCore(ref Message message, string actor, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
        {
            IList <SupportingTokenAuthenticatorSpecification> list;
            AsymmetricSecurityProtocolFactory factory = this.Factory;
            TimeoutHelper         helper               = new TimeoutHelper(timeout);
            ReceiveSecurityHeader securityHeader       = base.ConfigureReceiveSecurityHeader(message, string.Empty, correlationStates, out list);
            SecurityToken         requiredSigningToken = null;

            if (factory.ActAsInitiator)
            {
                SecurityTokenAuthenticator initiatorAsymmetricTokenAuthenticator;
                SecurityToken token        = null;
                SecurityToken primaryToken = null;
                if (factory.RequireIntegrity)
                {
                    primaryToken         = SecurityProtocol.GetToken(this.initiatorAsymmetricTokenProvider, null, helper.RemainingTime());
                    requiredSigningToken = primaryToken;
                }
                if (factory.RequireConfidentiality)
                {
                    token = base.GetCorrelationToken(correlationStates);
                    if (!System.ServiceModel.Security.SecurityUtils.HasSymmetricSecurityKey(token))
                    {
                        securityHeader.WrappedKeySecurityTokenAuthenticator = this.Factory.WrappedKeySecurityTokenAuthenticator;
                    }
                }
                if (factory.AllowSerializedSigningTokenOnReply)
                {
                    initiatorAsymmetricTokenAuthenticator = this.initiatorAsymmetricTokenAuthenticator;
                    requiredSigningToken = null;
                }
                else
                {
                    initiatorAsymmetricTokenAuthenticator = null;
                }
                securityHeader.ConfigureAsymmetricBindingClientReceiveHeader(primaryToken, factory.AsymmetricTokenParameters, token, factory.CryptoTokenParameters, initiatorAsymmetricTokenAuthenticator);
            }
            else
            {
                SecurityToken token4;
                if ((this.Factory.RecipientAsymmetricTokenProvider != null) && this.Factory.RequireConfidentiality)
                {
                    token4 = SecurityProtocol.GetToken(factory.RecipientAsymmetricTokenProvider, null, helper.RemainingTime());
                }
                else
                {
                    token4 = null;
                }
                securityHeader.ConfigureAsymmetricBindingServerReceiveHeader(this.Factory.RecipientCryptoTokenAuthenticator, this.Factory.CryptoTokenParameters, token4, this.Factory.AsymmetricTokenParameters, list);
                securityHeader.WrappedKeySecurityTokenAuthenticator = this.Factory.WrappedKeySecurityTokenAuthenticator;
                securityHeader.ConfigureOutOfBandTokenResolver(base.MergeOutOfBandResolvers(list, this.Factory.RecipientOutOfBandTokenResolverList));
            }
            base.ProcessSecurityHeader(securityHeader, ref message, requiredSigningToken, helper.RemainingTime(), correlationStates);
            SecurityToken signatureToken  = securityHeader.SignatureToken;
            SecurityToken encryptionToken = securityHeader.EncryptionToken;

            if (factory.RequireIntegrity)
            {
                if (factory.ActAsInitiator)
                {
                    ReadOnlyCollection <IAuthorizationPolicy> recipientTokenPolicies = this.initiatorAsymmetricTokenAuthenticator.ValidateToken(signatureToken);
                    MessageSecurityProtocol.EnsureNonWrappedToken(signatureToken, message);
                    this.DoIdentityCheckAndAttachInitiatorSecurityProperty(message, encryptionToken, signatureToken, recipientTokenPolicies);
                }
                else
                {
                    MessageSecurityProtocol.EnsureNonWrappedToken(signatureToken, message);
                    this.AttachRecipientSecurityProperty(message, signatureToken, encryptionToken, securityHeader.BasicSupportingTokens, securityHeader.EndorsingSupportingTokens, securityHeader.SignedEndorsingSupportingTokens, securityHeader.SignedSupportingTokens, securityHeader.SecurityTokenAuthorizationPoliciesMapping);
                }
            }
            return(base.GetCorrelationState(signatureToken, securityHeader));
        }
        public async Task OnConnectedAsync(FramingConnection connection)
        {
            TimeSpan receiveTimeout = connection.ServiceDispatcher.Binding.ReceiveTimeout;
            var      timeoutHelper  = new TimeoutHelper(receiveTimeout);
            bool     success        = false;

            try
            {
                var decoder = connection.FramingDecoder as ServerSingletonDecoder;
                Fx.Assert(decoder != null, "FramingDecoder must be non-null and an instance of ServerSessionDecoder");

                // first validate our content type
                //ValidateContentType(connection, decoder);
                UpgradeState upgradeState = UpgradeState.None;
                // next read any potential upgrades and finish consuming the preamble
                ReadOnlySequence <byte> buffer = ReadOnlySequence <byte> .Empty;
                while (true)
                {
                    if (buffer.Length == 0 && CanReadAndDecode(upgradeState))
                    {
                        System.IO.Pipelines.ReadResult readResult = await connection.Input.ReadAsync();

                        buffer = readResult.Buffer;
                        if (readResult.IsCompleted)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
                        }
                    }

                    while (true)
                    {
                        if (CanReadAndDecode(upgradeState))
                        {
                            Fx.Assert(buffer.Length > 0, "There must be something in the buffer to decode");
                            int bytesDecoded = decoder.Decode(buffer);
                            if (bytesDecoded > 0)
                            {
                                buffer = buffer.Slice(bytesDecoded);
                                if (buffer.Length == 0)
                                {
                                    connection.Input.AdvanceTo(buffer.Start);
                                }
                            }
                        }

                        switch (decoder.CurrentState)
                        {
                        case ServerSingletonDecoder.State.UpgradeRequest:
                            switch (upgradeState)
                            {
                            case UpgradeState.None:
                                //change the state so that we don't read/decode until it is safe
                                ChangeUpgradeState(ref upgradeState, UpgradeState.VerifyingUpgradeRequest);
                                break;

                            case UpgradeState.VerifyingUpgradeRequest:
                                if (connection.StreamUpgradeAcceptor == null)
                                {
                                    await connection.SendFaultAsync(FramingEncodingString.UpgradeInvalidFault, timeoutHelper.RemainingTime(), TransportDefaults.MaxDrainSize);

                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                              new ProtocolException(SR.Format(SR.UpgradeRequestToNonupgradableService, decoder.Upgrade)));
                                }

                                if (!connection.StreamUpgradeAcceptor.CanUpgrade(decoder.Upgrade))
                                {
                                    await connection.SendFaultAsync(FramingEncodingString.UpgradeInvalidFault, timeoutHelper.RemainingTime(), TransportDefaults.MaxDrainSize);

                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.UpgradeProtocolNotSupported, decoder.Upgrade)));
                                }

                                ChangeUpgradeState(ref upgradeState, UpgradeState.WritingUpgradeAck);
                                // accept upgrade
                                await connection.Output.WriteAsync(ServerSingletonEncoder.UpgradeResponseBytes, timeoutHelper.GetCancellationToken());

                                await connection.Output.FlushAsync(timeoutHelper.GetCancellationToken());

                                ChangeUpgradeState(ref upgradeState, UpgradeState.UpgradeAckSent);
                                break;

                            case UpgradeState.UpgradeAckSent:
                                // This state was used to capture any extra read bytes into PreReadConnection but we don't need to do that when using pipes.
                                // This extra state transition has been left here to maintain the same state transitions as on .NET Framework to make comparison easier.
                                ChangeUpgradeState(ref upgradeState, UpgradeState.BeginUpgrade);
                                break;

                            case UpgradeState.BeginUpgrade:
                                // Set input pipe so that the next read will return all the unconsumed bytes.
                                // If all bytes have already been consumed so the buffer has 0 length, AdvanceTo would throw
                                // as it's already been called.
                                if (buffer.Length > 0)
                                {
                                    connection.Input.AdvanceTo(buffer.Start);
                                }

                                buffer = ReadOnlySequence <byte> .Empty;
                                try
                                {
                                    await UpgradeConnectionAsync(connection, decoder.Upgrade);

                                    ChangeUpgradeState(ref upgradeState, UpgradeState.EndUpgrade);
                                }
                                catch (Exception exception)
                                {
                                    if (Fx.IsFatal(exception))
                                    {
                                        throw;
                                    }

                                    throw;
                                }
                                break;

                            case UpgradeState.EndUpgrade:
                                //Must be a different state here than UpgradeComplete so that we don't try to read from the connection
                                ChangeUpgradeState(ref upgradeState, UpgradeState.UpgradeComplete);
                                break;

                            case UpgradeState.UpgradeComplete:
                                //Client is doing more than one upgrade, reset the state
                                ChangeUpgradeState(ref upgradeState, UpgradeState.VerifyingUpgradeRequest);
                                break;
                            }
                            break;

                        case ServerSingletonDecoder.State.Start:
                            SetupSecurityIfNecessary(connection);
                            if (upgradeState == UpgradeState.UpgradeComplete ||  //We have done at least one upgrade, but we are now done.
                                upgradeState == UpgradeState.None)       //no upgrade, just send the preample end bytes
                            {
                                ChangeUpgradeState(ref upgradeState, UpgradeState.WritingPreambleEnd);
                                // we've finished the preamble. Ack and return.
                                await connection.Output.WriteAsync(ServerSessionEncoder.AckResponseBytes);

                                await connection.Output.FlushAsync();

                                //terminal state
                                ChangeUpgradeState(ref upgradeState, UpgradeState.PreambleEndSent);
                            }
                            // If all bytes have already been consumed so the buffer has 0 length, AdvanceTo would throw
                            // as it's already been called.
                            if (buffer.Length > 0)
                            {
                                connection.Input.AdvanceTo(buffer.Start);
                            }

                            success = true;
                            await _next(connection);

                            return;
                        }

                        if (buffer.Length == 0)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                if (!success)
                {
                    connection.Abort();
                }
            }
        }
        WorkflowOperationContext(object[] inputs, OperationContext operationContext, string operationName,
                                 bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction,
                                 WorkflowServiceInstance workflowInstance, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, ServiceEndpoint endpoint,
                                 TimeSpan timeout, AsyncCallback callback, object state)
            : base(callback, state)
        {
            this.inputs                     = inputs;
            this.operationName              = operationName;
            this.OperationContext           = operationContext;
            this.ServiceEndpoint            = endpoint;
            this.CurrentTransaction         = currentTransaction;
            this.performanceCountersEnabled = performanceCountersEnabled;
            this.propagateActivity          = propagateActivity;
            this.timeoutHelper              = new TimeoutHelper(timeout);
            this.workflowInstance           = workflowInstance;
            this.thisLock                   = new object();
            this.notification               = notification;
            this.OnCompleting               = onCompleting;

            // Resolve bookmark
            Fx.Assert(behavior != null, "behavior must not be null!");
            this.bookmark = behavior.OnResolveBookmark(this, out this.bookmarkScope, out this.bookmarkValue);
            Fx.Assert(this.bookmark != null, "bookmark must not be null!");

            bool completeSelf = false;

            try
            {
                // set activity ID on the executing thread (Bug 113386)
                if (TraceUtility.MessageFlowTracingOnly)
                {
                    this.e2eActivityId             = TraceUtility.GetReceivedActivityId(this.OperationContext);
                    DiagnosticTraceBase.ActivityId = this.e2eActivityId;
                }

                if (Fx.Trace.IsEtwProviderEnabled)
                {
                    this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(this.OperationContext.IncomingMessage);
                }

                // Take ownership of the ReceiveContext when buffering is enabled by removing the property
                if (this.workflowInstance.BufferedReceiveManager != null)
                {
                    if (!ReceiveContext.TryGet(this.OperationContext.IncomingMessageProperties, out this.receiveContext))
                    {
                        Fx.Assert("ReceiveContext expected when BufferedReceives are enabled");
                    }

                    this.OperationContext.IncomingMessageProperties.Remove(ReceiveContext.Name);
                }

                completeSelf = ProcessRequest();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                // Failing synchronously is one case where AsyncResult won't handle calling OnCompleting
                OnCompleting(this, e);
                throw;
            }

            if (completeSelf)
            {
                base.Complete(true);
            }
        }
Example #31
0
 protected override IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper)
 {
     this.decoder = new ClientSingletonDecoder(0);
     return(channel.SendPreamble(connection, ref timeoutHelper, this.decoder, out this.remoteSecurity));
 }
Example #32
0
        private bool HandleErrorContinuation(Exception e, RequestContext request, ServiceChannel channel, ref ErrorHandlerFaultInfo faultInfo, bool replied)
        {
            if (replied)
            {
                try
                {
                    request.Close();
                }
                catch (Exception e1)
                {
                    if (Fx.IsFatal(e1))
                    {
                        throw;
                    }
                    this.HandleError(e1);
                }
            }
            else
            {
                request.Abort();
            }
            if (!this.HandleError(e, ref faultInfo) && _hasSession)
            {
                if (channel != null)
                {
                    if (replied)
                    {
                        TimeoutHelper timeoutHelper = new TimeoutHelper(CloseAfterFaultTimeout);
                        try
                        {
                            channel.Close(timeoutHelper.RemainingTime());
                        }
                        catch (Exception e2)
                        {
                            if (Fx.IsFatal(e2))
                            {
                                throw;
                            }
                            this.HandleError(e2);
                        }
                        try
                        {
                            _binder.CloseAfterFault(timeoutHelper.RemainingTime());
                        }
                        catch (Exception e3)
                        {
                            if (Fx.IsFatal(e3))
                            {
                                throw;
                            }
                            this.HandleError(e3);
                        }
                    }
                    else
                    {
                        channel.Abort();
                        _binder.Abort();
                    }
                }
                else
                {
                    if (replied)
                    {
                        try
                        {
                            _binder.CloseAfterFault(CloseAfterFaultTimeout);
                        }
                        catch (Exception e4)
                        {
                            if (Fx.IsFatal(e4))
                            {
                                throw;
                            }
                            this.HandleError(e4);
                        }
                    }
                    else
                    {
                        _binder.Abort();
                    }
                }
            }

            return(true);
        }
Example #33
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     _connection.Write(buffer, offset, count, this.Immediate, TimeoutHelper.FromMilliseconds(this.WriteTimeout));
 }
        private async Task OpenInternalAsync(bool withRetry, TimeoutHelper timeoutHelper)
        {
            using var cts = new CancellationTokenSource(timeoutHelper.GetRemainingTime());

            if (withRetry)
            {
                await _internalRetryPolicy
                .RunWithRetryAsync(
                    async() =>
                {
                    try
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Enter(this, timeoutHelper, nameof(OpenAsync));
                        }

                        // Will throw on error.
                        await base.OpenAsync(timeoutHelper).ConfigureAwait(false);
                        _onConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        HandleConnectionStatusExceptions(ex);
                        throw;
                    }
                    finally
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Exit(this, timeoutHelper, nameof(OpenAsync));
                        }
                    }
                },
                    cts.Token)
                .ConfigureAwait(false);
            }
            else
            {
                try
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Enter(this, timeoutHelper, nameof(OpenAsync));
                    }

                    // Will throw on error.
                    await base.OpenAsync(timeoutHelper).ConfigureAwait(false);

                    _onConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    HandleConnectionStatusExceptions(ex);
                    throw;
                }
                finally
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Exit(this, timeoutHelper, nameof(OpenAsync));
                    }
                }
            }
        }
Example #35
0
        public System.Threading.Tasks.Task OpenAsync()
        {
            var token = new TimeoutHelper(DefaultOpenTimeout).GetCancellationToken();

            return(OpenAsync(token));
        }
        internal static void SendFault(Microsoft.ServiceBus.Channels.IConnection connection, string faultString, byte[] drainBuffer, TimeSpan sendTimeout, int maxRead)
        {
            Microsoft.ServiceBus.Channels.EncodedFault encodedFault = new Microsoft.ServiceBus.Channels.EncodedFault(faultString);
            TimeoutHelper timeoutHelper = new TimeoutHelper(sendTimeout);

            try
            {
                connection.Write(encodedFault.EncodedBytes, 0, (int)encodedFault.EncodedBytes.Length, true, timeoutHelper.RemainingTime());
                connection.Shutdown(timeoutHelper.RemainingTime());
            }
            catch (CommunicationException communicationException1)
            {
                CommunicationException communicationException = communicationException1;
                if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceInformation)
                {
                    Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(communicationException, TraceEventType.Information);
                }
                connection.Abort();
                return;
            }
            catch (TimeoutException timeoutException1)
            {
                TimeoutException timeoutException = timeoutException1;
                if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceInformation)
                {
                    Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(timeoutException, TraceEventType.Information);
                }
                connection.Abort();
                return;
            }
            int num  = 0;
            int num1 = 0;

            do
            {
                try
                {
                    num = connection.Read(drainBuffer, 0, (int)drainBuffer.Length, timeoutHelper.RemainingTime());
                }
                catch (CommunicationException communicationException3)
                {
                    CommunicationException communicationException2 = communicationException3;
                    if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceInformation)
                    {
                        Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(communicationException2, TraceEventType.Information);
                    }
                    connection.Abort();
                    return;
                }
                catch (TimeoutException timeoutException3)
                {
                    TimeoutException timeoutException2 = timeoutException3;
                    if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceInformation)
                    {
                        Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(timeoutException2, TraceEventType.Information);
                    }
                    connection.Abort();
                    return;
                }
                if (num == 0)
                {
                    Microsoft.ServiceBus.Channels.ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime());
                    return;
                }
                num1 = num1 + num;
            }while (num1 <= maxRead && !(timeoutHelper.RemainingTime() <= TimeSpan.Zero));
            connection.Abort();
        }
Example #37
0
        internal MessageRpc(RequestContext requestContext, Message request, DispatchOperationRuntime operation,
                            ServiceChannel channel, ChannelHandler channelHandler, bool cleanThread,
                            OperationContext operationContext, InstanceContext instanceContext, EventTraceActivity eventTraceActivity)
        {
            Fx.Assert((operationContext != null), "System.ServiceModel.Dispatcher.MessageRpc.MessageRpc(), operationContext == null");
            Fx.Assert(channelHandler != null, "System.ServiceModel.Dispatcher.MessageRpc.MessageRpc(), channelHandler == null");

            Activity            = null;
            EventTraceActivity  = eventTraceActivity;
            AsyncResult         = null;
            CanSendReply        = true;
            Channel             = channel;
            this.channelHandler = channelHandler;
            Correlation         = EmptyArray <object> .Allocate(operation.Parent.CorrelationCount);

            DidDeserializeRequestBody = false;
            Error              = null;
            ErrorProcessor     = null;
            FaultInfo          = new ErrorHandlerFaultInfo(request.Version.Addressing.DefaultFaultAction);
            HasSecurityContext = false;
            Instance           = null;
            MessageRpcOwnsInstanceContextThrottle = false;
            NextProcessor        = null;
            NotUnderstoodHeaders = null;
            Operation            = operation;
            OperationContext     = operationContext;
            IsPaused             = false;
            ParametersDisposed   = false;
            Request                    = request;
            RequestContext             = requestContext;
            RequestContextThrewOnReply = false;
            SuccessfullySendReply      = false;
            RequestVersion             = request.Version;
            Reply = null;
            ReplyTimeoutHelper              = new TimeoutHelper();
            SecurityContext                 = null;
            InstanceContext                 = instanceContext;
            SuccessfullyBoundInstance       = false;
            SuccessfullyIncrementedActivity = false;
            SuccessfullyLockedInstance      = false;
            SwitchedThreads                 = !cleanThread;
            InputParameters                 = null;
            OutputParameters                = null;
            ReturnParameter                 = null;
            _isInstanceContextSingleton     = false;
            _invokeContinueGate             = null;

            if (!operation.IsOneWay && !operation.Parent.ManualAddressing)
            {
                RequestID   = request.Headers.MessageId;
                ReplyToInfo = new RequestReplyCorrelator.ReplyToInfo(request);
            }
            else
            {
                RequestID   = null;
                ReplyToInfo = new RequestReplyCorrelator.ReplyToInfo();
            }

            if (DiagnosticUtility.ShouldUseActivity)
            {
                Activity = TraceUtility.ExtractActivity(Request);
            }

            if (DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivity)
            {
                ResponseActivityId = ActivityIdHeader.ExtractActivityId(Request);
            }
            else
            {
                ResponseActivityId = Guid.Empty;
            }

            InvokeNotification = new MessageRpcInvokeNotification(Activity, this.channelHandler);

            if (EventTraceActivity == null && FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
            {
                if (Request != null)
                {
                    EventTraceActivity = EventTraceActivityHelper.TryExtractActivity(Request, true);
                }
            }
        }
Example #38
0
 public IAsyncResult BeginResumeBookmark(Bookmark bookmark, object value, TimeSpan timeout, AsyncCallback callback, object state)
 {
     TimeoutHelper.ThrowIfNegativeArgument(timeout);
     return(this.instance.OnBeginResumeBookmark(bookmark, value, timeout, callback, state));
 }
Example #39
0
 protected override void OnOpen(TimeSpan timeout)
 {
     TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 }
        public async Task <int> ReceiveAsync(byte[] buffer, int offset, int size, TimeSpan timeout)
        {
            byte[] header = new byte[2];

            Fx.AssertAndThrow(this.State == WebSocketState.Open, ClientWebSocketNotInOpenStateDuringReceive);
            this.TcpClient.ReceiveTimeout = TimeoutHelper.ToMilliseconds(timeout);

            bool succeeded = false;

            try
            {
                byte payloadLength;
                bool pongFrame;

                // TODO: rewrite this section to handle all control frames (including ping)
                int totalBytesRead;
                int bytesRead;
                do
                {
                    // Ignore pong frame and start over
                    totalBytesRead = 0;
                    do
                    {
                        bytesRead = await WebSocketStream.ReadAsync(header, totalBytesRead, header.Length - totalBytesRead).ConfigureAwait(false);

                        if (bytesRead == 0)
                        {
                            throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                        }

                        totalBytesRead += bytesRead;
                    }while (totalBytesRead < header.Length);

                    if (!ParseWebSocketFrameHeader(header, out payloadLength, out pongFrame))
                    {
                        // Encountered a close frame or error in parsing frame from server. Close connection
                        var closeHeader = PrepareWebSocketHeader(0, WebSocketMessageType.Close);

                        await WebSocketStream.WriteAsync(closeHeader, 0, closeHeader.Length).ConfigureAwait(false);

                        this.State = WebSocketState.Closed;
#if !NETSTANDARD1_3
                        this.WebSocketStream?.Close();
                        this.TcpClient?.Close();
#else
                        this.WebSocketStream?.Dispose();
                        this.TcpClient?.Dispose();
#endif
                        return(0);  // TODO: throw exception?
                    }

                    if (pongFrame && payloadLength > 0)
                    {
                        totalBytesRead = 0;
                        var tempBuffer = new byte[payloadLength];
                        while (totalBytesRead < payloadLength)
                        {
                            bytesRead = await WebSocketStream.ReadAsync(tempBuffer, totalBytesRead, payloadLength - totalBytesRead).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                            }

                            totalBytesRead += bytesRead;
                        }
                    }
                }while (pongFrame);

                totalBytesRead = 0;

                if (buffer.Length < payloadLength)
                {
                    throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace));
                }

                if (payloadLength < MediumSizeFrame)
                {
                    while (totalBytesRead < payloadLength)
                    {
                        bytesRead = await WebSocketStream.ReadAsync(buffer, offset + totalBytesRead, payloadLength - totalBytesRead).ConfigureAwait(false);

                        if (bytesRead == 0)
                        {
                            throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                        }

                        totalBytesRead += bytesRead;
                    }
                }
                else
                {
                    switch (payloadLength)
                    {
                    case MediumSizeFrame:
                        // read payload length (< 64K)
                        do
                        {
                            bytesRead = await WebSocketStream.ReadAsync(header, totalBytesRead, header.Length - totalBytesRead).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                            }

                            totalBytesRead += bytesRead;
                        }while (totalBytesRead < header.Length);

                        totalBytesRead = 0;
                        ushort extendedPayloadLength = (ushort)((header[0] << 8) | header[1]);

                        // read payload
                        if (buffer.Length >= extendedPayloadLength)
                        {
                            while (totalBytesRead < extendedPayloadLength)
                            {
                                bytesRead = await WebSocketStream.ReadAsync(buffer, offset + totalBytesRead, extendedPayloadLength - totalBytesRead).ConfigureAwait(false);

                                if (bytesRead == 0)
                                {
                                    throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                                }

                                totalBytesRead += bytesRead;
                            }
                        }
                        else
                        {
                            throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace));
                        }

                        break;

                    case LargeSizeFrame:
                        // read payload length (>= 64K)
                        var payloadLengthBuffer = new byte[8];
                        do
                        {
                            bytesRead = await WebSocketStream.ReadAsync(payloadLengthBuffer, totalBytesRead, payloadLengthBuffer.Length - totalBytesRead).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                            }

                            totalBytesRead += bytesRead;
                        }while (totalBytesRead < payloadLengthBuffer.Length);

                        totalBytesRead = 0;

                        // ignore bytes 0-3 - length cannot be larger than a 32-bit number
                        uint superExtendedPayloadLength = (uint)((payloadLengthBuffer[4] << 24) | (payloadLengthBuffer[5] << 16) | (payloadLengthBuffer[6] << 8) | payloadLengthBuffer[7]);

                        // read payload
                        if (buffer.Length >= superExtendedPayloadLength)
                        {
                            while (totalBytesRead < superExtendedPayloadLength)
                            {
                                bytesRead = await WebSocketStream.ReadAsync(buffer, offset + totalBytesRead, (int)(superExtendedPayloadLength - totalBytesRead)).ConfigureAwait(false);

                                if (bytesRead == 0)
                                {
                                    throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes"));
                                }

                                totalBytesRead += bytesRead;
                            }
                        }
                        else
                        {
                            throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace));
                        }

                        break;
                    }
                }

                succeeded = true;
                return(totalBytesRead);
            }
            finally
            {
                if (!succeeded)
                {
                    this.Fault();
                }
            }
        }
Example #41
0
 public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
 {
     TimeoutHelper.ThrowIfNegativeArgument(timeout);
     return((new ReconnectBindingElement.ReconnectChannelFactory <TChannel> .RequestSessionChannel.RequestAsyncResult(this, message, timeout, callback, state)).Start());
 }
Example #42
0
        public virtual async Task OnOpenAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (SecurityProtocolFactory.ActAsInitiator)
            {
                ChannelSupportingTokenProviderSpecification = new Collection <SupportingTokenProviderSpecification>();
                ScopedSupportingTokenProviderSpecification  = new Dictionary <string, ICollection <SupportingTokenProviderSpecification> >();

                AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.EndpointSupportingTokenParameters, false, (IList <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalEndpointSupportingTokenParameters, true, (IList <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters.Keys)
                {
                    Collection <SupportingTokenProviderSpecification> providerSpecList = new Collection <SupportingTokenProviderSpecification>();
                    AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters[action], false, providerSpecList);
                    ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
                }

                foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters.Keys)
                {
                    Collection <SupportingTokenProviderSpecification> providerSpecList;
                    if (ScopedSupportingTokenProviderSpecification.TryGetValue(action, out ICollection <SupportingTokenProviderSpecification> existingList))
                    {
                        providerSpecList = ((Collection <SupportingTokenProviderSpecification>)existingList);
                    }
                    else
                    {
                        providerSpecList = new Collection <SupportingTokenProviderSpecification>();
                        ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
                    }

                    AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters[action], true, providerSpecList);
                }

                if (!ChannelSupportingTokenProviderSpecification.IsReadOnly)
                {
                    if (ChannelSupportingTokenProviderSpecification.Count == 0)
                    {
                        ChannelSupportingTokenProviderSpecification = EmptyTokenProviders;
                    }
                    else
                    {
                        SecurityProtocolFactory.ExpectSupportingTokens = true;
                        CancellationToken cancellationToken = timeoutHelper.GetCancellationToken();
                        foreach (SupportingTokenProviderSpecification tokenProviderSpec in ChannelSupportingTokenProviderSpecification)
                        {
                            await SecurityUtils.OpenTokenProviderIfRequiredAsync(tokenProviderSpec.TokenProvider, cancellationToken);

                            if (tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
                            {
                                if (tokenProviderSpec.TokenParameters.RequireDerivedKeys && !tokenProviderSpec.TokenParameters.HasAsymmetricKey)
                                {
                                    SecurityProtocolFactory.ExpectKeyDerivation = true;
                                }
                            }
                        }
                        ChannelSupportingTokenProviderSpecification =
                            new ReadOnlyCollection <SupportingTokenProviderSpecification>((Collection <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                    }
                }
                // create a merged map of the per operation supporting tokens
                await MergeSupportingTokenProvidersAsync(timeoutHelper.RemainingTime());
            }
        }
Example #43
0
 protected override IAsyncResult BeginAcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
 {
     this.decoder = new ClientSingletonDecoder(0);
     return(new SendPreambleAsyncResult(channel, connection, ref timeoutHelper, decoder, callback, state));
 }
Example #44
0
        async Task DisposeMessagesAsync(IEnumerable <Guid> lockTokens, Outcome outcome)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(this.OperationTimeout, true);
            IList <ArraySegment <byte> > deliveryTags = this.ConvertLockTokensToDeliveryTags(lockTokens);

            ReceivingAmqpLink receiveLink = null;

            try
            {
                receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                Task <Outcome>[] disposeMessageTasks = new Task <Outcome> [deliveryTags.Count];
                int i = 0;
                foreach (ArraySegment <byte> deliveryTag in deliveryTags)
                {
                    disposeMessageTasks[i++] = Task.Factory.FromAsync(
                        (c, s) => receiveLink.BeginDisposeMessage(deliveryTag, outcome, true, timeoutHelper.RemainingTime(), c, s),
                        a => receiveLink.EndDisposeMessage(a),
                        this);
                }

                Outcome[] outcomes = await Task.WhenAll(disposeMessageTasks).ConfigureAwait(false);

                Error error = null;
                foreach (Outcome item in outcomes)
                {
                    var disposedOutcome = item.DescriptorCode == Rejected.Code && ((error = ((Rejected)item).Error) != null) ? item : null;
                    if (disposedOutcome != null)
                    {
                        if (error.Condition.Equals(AmqpErrorCode.NotFound))
                        {
                            if (this.isSessionReceiver)
                            {
                                throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession);
                            }
                            else
                            {
                                throw new MessageLockLostException(Resources.MessageLockLost);
                            }
                        }

                        throw AmqpExceptionHelper.ToMessagingContractException(error);
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception is OperationCanceledException &&
                    receiveLink != null && receiveLink.State != AmqpObjectState.Opened)
                {
                    if (this.isSessionReceiver)
                    {
                        throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession);
                    }
                    else
                    {
                        throw new MessageLockLostException(Resources.MessageLockLost);
                    }
                }

                throw AmqpExceptionHelper.GetClientException(exception);
            }
        }
Example #45
0
 protected override void SetPipelineIncomingTimeout()
 {
     this.cancellationTokenSource.CancelAfter(TimeoutHelper.ToMilliseconds((httpRequestContext.Listener as IDefaultCommunicationTimeouts).OpenTimeout));
 }
        protected override async Task <IList <EventData> > OnReceiveAsync(int maxMessageCount, TimeSpan waitTime)
        {
            bool shouldRetry;
            int  retryCount = 0;

            var timeoutHelper = new TimeoutHelper(waitTime, true);

            do
            {
                shouldRetry = false;

                try
                {
                    try
                    {
                        // Always use default timeout for AMQP sesssion.
                        ReceivingAmqpLink receiveLink =
                            await this.ReceiveLinkManager.GetOrCreateAsync(
                                TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false);

                        IEnumerable <AmqpMessage> amqpMessages = null;
                        bool hasMessages = await Task.Factory.FromAsync(
                            (c, s) => receiveLink.BeginReceiveMessages(maxMessageCount, timeoutHelper.RemainingTime(), c, s),
                            a => receiveLink.EndReceiveMessages(a, out amqpMessages),
                            this).ConfigureAwait(false);

                        if (receiveLink.TerminalException != null)
                        {
                            throw receiveLink.TerminalException;
                        }

                        if (hasMessages && amqpMessages != null)
                        {
                            IList <EventData> eventDatas = null;
                            foreach (var amqpMessage in amqpMessages)
                            {
                                if (eventDatas == null)
                                {
                                    eventDatas = new List <EventData>();
                                }

                                receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
                                eventDatas.Add(AmqpMessageConverter.AmqpMessageToEventData(amqpMessage));
                            }

                            return(eventDatas);
                        }
                    }
                    catch (AmqpException amqpException)
                    {
                        throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error);
                    }
                }
                catch (Exception ex)
                {
                    // Evaluate retry condition?
                    TimeSpan?retryInterval = this.RetryPolicy.GetNextRetryInterval(ex, timeoutHelper.RemainingTime(), ++retryCount);
                    if (retryInterval != null && !this.EventHubClient.CloseCalled)
                    {
                        await Task.Delay(retryInterval.Value).ConfigureAwait(false);

                        shouldRetry = true;
                    }
                    else
                    {
                        // Handle EventHubsTimeoutException explicitly.
                        // We don't really want to to throw EventHubsTimeoutException on this call.
                        if (ex is EventHubsTimeoutException)
                        {
                            break;
                        }

                        throw;
                    }
                }
            } while (shouldRetry);

            // No messages to deliver.
            return(null);
        }
 public override Task OpenAsync(TimeoutHelper timeoutHelper)
 {
     return(TaskHelpers.CompletedTask);
 }
        protected virtual void VerifyIncomingMessageCore(ref Message message, TimeSpan timeout)
        {
            TransportSecurityProtocolFactory factory = (TransportSecurityProtocolFactory)this.SecurityProtocolFactory;
            string actor = string.Empty; // message.Version.Envelope.UltimateDestinationActor;

            ReceiveSecurityHeader securityHeader = factory.StandardsManager.TryCreateReceiveSecurityHeader(message, actor,
                                                                                                           factory.IncomingAlgorithmSuite, (factory.ActAsInitiator) ? MessageDirection.Output : MessageDirection.Input);
            bool expectBasicTokens;
            bool expectEndorsingTokens;
            bool expectSignedTokens;
            IList <SupportingTokenAuthenticatorSpecification> supportingAuthenticators = factory.GetSupportingTokenAuthenticators(message.Headers.Action,
                                                                                                                                  out expectSignedTokens, out expectBasicTokens, out expectEndorsingTokens);

            if (securityHeader == null)
            {
                bool expectSupportingTokens = expectEndorsingTokens || expectSignedTokens || expectBasicTokens;
                if ((factory.ActAsInitiator && (!factory.AddTimestamp || factory.SecurityBindingElement.EnableUnsecuredResponse)) ||
                    (!factory.ActAsInitiator && !factory.AddTimestamp && !expectSupportingTokens))
                {
                    return;
                }
                else
                {
                    if (String.IsNullOrEmpty(actor))
                    {
                        throw Diagnostics.TraceUtility.ThrowHelperError(new MessageSecurityException(
                                                                            SR.Format(SR.UnableToFindSecurityHeaderInMessageNoActor)), message);
                    }
                    else
                    {
                        throw Diagnostics.TraceUtility.ThrowHelperError(new MessageSecurityException(
                                                                            SR.Format(SR.UnableToFindSecurityHeaderInMessage, actor)), message);
                    }
                }
            }

            securityHeader.RequireMessageProtection = false;
            securityHeader.ExpectBasicTokens        = expectBasicTokens;
            securityHeader.ExpectSignedTokens       = expectSignedTokens;
            securityHeader.ExpectEndorsingTokens    = expectEndorsingTokens;
            securityHeader.MaxReceivedMessageSize   = factory.SecurityBindingElement.MaxReceivedMessageSize;
            securityHeader.ReaderQuotas             = factory.SecurityBindingElement.ReaderQuotas;

            // Due to compatibility, only honor this setting if this app setting is enabled
            if (ServiceModelAppSettings.UseConfiguredTransportSecurityHeaderLayout)
            {
                securityHeader.Layout = factory.SecurityHeaderLayout;
            }

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (!factory.ActAsInitiator)
            {
                securityHeader.ConfigureTransportBindingServerReceiveHeader(supportingAuthenticators);
                securityHeader.ConfigureOutOfBandTokenResolver(MergeOutOfBandResolvers(supportingAuthenticators, EmptyReadOnlyCollection <SecurityTokenResolver> .Instance));
                if (factory.ExpectKeyDerivation)
                {
                    securityHeader.DerivedTokenAuthenticator = factory.DerivedKeyTokenAuthenticator;
                }
            }
            securityHeader.ReplayDetectionEnabled = factory.DetectReplays;
            securityHeader.SetTimeParameters(factory.NonceCache, factory.ReplayWindow, factory.MaxClockSkew);
            securityHeader.Process(timeoutHelper.RemainingTime(), SecurityUtils.GetChannelBindingFromMessage(message), factory.ExtendedProtectionPolicy);
            message = securityHeader.ProcessedMessage;
            if (!factory.ActAsInitiator)
            {
                AttachRecipientSecurityProperty(message, securityHeader.BasicSupportingTokens, securityHeader.EndorsingSupportingTokens, securityHeader.SignedEndorsingSupportingTokens,
                                                securityHeader.SignedSupportingTokens, securityHeader.SecurityTokenAuthorizationPoliciesMapping);
            }

            base.OnIncomingMessageVerified(message);
        }
Example #49
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     return(this.Read(buffer, offset, count, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
 }
 private IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper, ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
 {
     connection.Write(this.Preamble, 0, this.Preamble.Length, true, timeoutHelper.RemainingTime());
     if (this.upgrade != null)
     {
         IStreamUpgradeChannelBindingProvider property = this.upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
         StreamUpgradeInitiator upgradeInitiator = this.upgrade.CreateUpgradeInitiator(base.RemoteAddress, base.Via);
         if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder, this, ref timeoutHelper))
         {
             ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, base.Via, this.messageEncoder.ContentType, ref timeoutHelper);
         }
         if ((property != null) && property.IsChannelBindingSupportEnabled)
         {
             this.channelBindingToken = property.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
         }
         remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);
         connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
     }
     else
     {
         remoteSecurity = null;
     }
     byte[] buffer = new byte[1];
     int count = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
     if (!ConnectionUpgradeHelper.ValidatePreambleResponse(buffer, count, decoder, base.Via))
     {
         ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, base.Via, this.messageEncoder.ContentType, ref timeoutHelper);
     }
     return connection;
 }
        bool InternalAddMessage(Message message, TimeSpan timeout, object state, bool isLast)
        {
            MessageAttemptInfo attemptInfo;
            TimeoutHelper helper = new TimeoutHelper(timeout);

            try
            {
                if (isLast)
                {
                    if (state != null)
                    {
                        throw Fx.AssertAndThrow("The isLast overload does not take a state.");
                    }

                    attemptInfo = this.strategy.AddLast(message, helper.RemainingTime(), null);
                }
                else if (!this.strategy.Add(message, helper.RemainingTime(), state, out attemptInfo))
                {
                    return false;
                }
            }
            catch (TimeoutException)
            {
                if (isLast)
                    this.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.id, SR.GetString(SR.SequenceTerminatedAddLastToWindowTimedOut), null));
                // else - RM does not fault the channel based on a timeout exception trying to add a sequenced message to the window.

                throw;
            }
            catch (Exception e)
            {
                if (!Fx.IsFatal(e))
                    this.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.id, SR.GetString(SR.SequenceTerminatedUnknownAddToWindowError), null));

                throw;
            }

            if (sendGuard.Enter())
            {
                try
                {
                    this.sendHandler(attemptInfo, helper.RemainingTime(), false);
                }
                catch (QuotaExceededException)
                {
                    this.RaiseFault(null, SequenceTerminatedFault.CreateQuotaExceededFault(this.id));
                    throw;
                }
                finally
                {
                    this.sendGuard.Exit();
                }
            }

            return true;
        }
 protected ReceiveMessageAndVerifySecurityAsyncResultBase(IInputChannel innerChannel, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.timeoutHelper = new TimeoutHelper(timeout);
     this.innerChannel  = innerChannel;
 }
Example #53
0
            public Task <Message> ReceiveAsync()
            {
                var helper = new TimeoutHelper(DefaultReceiveTimeout);

                return(ReceiveAsync(helper.GetCancellationToken()));
            }
Example #54
0
            public Task CloseAsync()
            {
                var helper = new TimeoutHelper(DefaultCloseTimeout);

                return(CloseAsync(helper.GetCancellationToken()));
            }
 public void SendRequest(Message message, TimeSpan timeout)
 {
     TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
     try
     {
         this.connection = this.connectionPoolHelper.EstablishConnection(timeoutHelper.RemainingTime());
         ChannelBindingUtility.TryAddToMessage(this.channel.channelBindingToken, message, false);
         bool flag = false;
         try
         {
             StreamingConnectionHelper.WriteMessage(message, this.connection, true, this.channel.settings, ref timeoutHelper);
             flag = true;
         }
         finally
         {
             if (!flag)
             {
                 this.connectionPoolHelper.Abort();
             }
         }
     }
     catch (TimeoutException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(System.ServiceModel.SR.GetString("TimeoutOnRequest", new object[] { timeout }), exception));
     }
 }
Example #56
0
        private IAsyncResult OnBeginCloseContinue(TimeSpan timeout, AsyncCallback callback, object state)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            return(base.OnBeginClose(timeoutHelper.RemainingTime(), callback, state));
        }
        public void Close(TimeSpan timeout)
        {
            bool completeTransfer = false;

            lock (this.ThisLock)
            {
                completeTransfer = !this.closed;
                this.closed = true;
            }

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (completeTransfer)
            {
                this.CompleteTransfer(timeoutHelper.RemainingTime());
            }

            this.shutdownHandle.Wait(timeoutHelper.RemainingTime());
            this.sendGuard.Close(timeoutHelper.RemainingTime());
            this.strategy.Close();
        }
Example #58
0
        public void CloseAfterFault(TimeSpan timeout)
        {
            var helper = new TimeoutHelper(timeout);

            _channel.CloseAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
        }
            public AddAsyncResult(Message message, bool isLast, TimeSpan timeout, object state,
                ReliableOutputConnection connection, AsyncCallback callback, object asyncState)
                : base(callback, asyncState)
            {
                this.connection = connection;
                this.timeoutHelper = new TimeoutHelper(timeout);
                this.isLast = isLast;

                bool complete = false;
                IAsyncResult result;

                try
                {
                    if (isLast)
                    {
                        if (state != null)
                        {
                            throw Fx.AssertAndThrow("The isLast overload does not take a state.");
                        }

                        result = this.connection.strategy.BeginAddLast(message, this.timeoutHelper.RemainingTime(), state, addCompleteStatic, this);
                    }
                    else
                    {
                        result = this.connection.strategy.BeginAdd(message, this.timeoutHelper.RemainingTime(), state, addCompleteStatic, this);
                    }
                }
                catch (TimeoutException)
                {
                    if (isLast)
                        this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedAddLastToWindowTimedOut), null));
                    // else - RM does not fault the channel based on a timeout exception trying to add a sequenced message to the window.

                    throw;
                }
                catch (Exception e)
                {
                    if (!Fx.IsFatal(e))
                        this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedUnknownAddToWindowError), null));

                    throw;
                }

                if (result.CompletedSynchronously)
                    complete = this.CompleteAdd(result);

                if (complete)
                    this.Complete(true);
            }
Example #60
0
        protected override async Task OnSendAsync(Message message, TimeSpan timeout)
        {
            this.ThrowIfDisposedOrNotOpen();

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!await _sendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout)))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
                                                                              string.Format(SRServiceModel.SendToViaTimedOut, Via, timeout),
                                                                              TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }

            byte[] buffer = null;

            try
            {
                // check again in case the previous send faulted while we were waiting for the lock
                this.ThrowIfDisposedOrNotOpen();
                this.ThrowIfOutputSessionClosed();

                bool success = false;
                try
                {
                    this.ApplyChannelBinding(message);

                    var tcs = new TaskCompletionSource <bool>(this);

                    AsyncCompletionResult completionResult;
                    if (this.IsStreamedOutput)
                    {
                        completionResult = this.StartWritingStreamedMessage(message, timeoutHelper.RemainingTime(), s_onWriteComplete, this);
                    }
                    else
                    {
                        bool allowOutputBatching;
                        ArraySegment <byte> messageData;
                        allowOutputBatching = message.Properties.AllowOutputBatching;
                        messageData         = this.EncodeMessage(message);

                        buffer           = messageData.Array;
                        completionResult = this.StartWritingBufferedMessage(
                            message,
                            messageData,
                            allowOutputBatching,
                            timeoutHelper.RemainingTime(),
                            s_onWriteComplete,
                            tcs);
                    }

                    if (completionResult == AsyncCompletionResult.Completed)
                    {
                        tcs.TrySetResult(true);
                    }

                    await tcs.Task;

                    this.FinishWritingMessage();

                    success = true;
                    if (WcfEventSource.Instance.MessageSentByTransportIsEnabled())
                    {
                        EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
                        WcfEventSource.Instance.MessageSentByTransport(eventTraceActivity, this.RemoteAddress.Uri.AbsoluteUri);
                    }
                }
                finally
                {
                    if (!success)
                    {
                        this.Fault();
                    }
                }
            }
            finally
            {
                _sendLock.Release();
            }
            if (buffer != null)
            {
                _bufferManager.ReturnBuffer(buffer);
            }
        }