public static byte[] SetArguments(this ClientRequestContext source, byte[] value)
        {
            var old = source.SendingBuffer[3].AsEnumerable().ToArray();

            source.SendingBuffer[3] = new ArraySegment <byte>(value);
            return(old);
        }
        public void TestClear_Initialized()
        {
            int    messageId  = Environment.TickCount;
            string methodName = Guid.NewGuid().ToString();
            Action <ClientResponseContext, Exception, Boolean> completionCallback = (_0, _1, _2) => { };

            var target = new ClientRequestContext();

            target.RenewSessionId();
            target.SetRequest(messageId, methodName, completionCallback);
            target.ArgumentsPacker.Pack(1);
            target.Clear();

            Assert.That(target.ArgumentsPacker, Is.Not.Null);
            Assert.That(target.ArgumentsPacker.Position, Is.EqualTo(0));
            Assert.That(target.BoundTransport, Is.Null);
            Assert.That(target.MessageId, Is.Null);
            Assert.That(target.MessageType, Is.EqualTo(MessageType.Response));
            Assert.That(target.MethodName, Is.Null);
            Assert.That(target.NotificationCompletionCallback, Is.Null);
            Assert.That(target.RequestCompletionCallback, Is.Null);
            Assert.That(target.SendingBuffer.All(segment => segment.Array == null));
            Assert.That(target.SessionId, Is.EqualTo(0));
            Assert.That(target.SessionStartedAt, Is.EqualTo(default(DateTimeOffset)));
        }
Esempio n. 3
0
 /// <summary>
 ///		Performs protocol specific asynchronous 'Send' operation.
 /// </summary>
 /// <param name="context">Context information.</param>
 protected sealed override void SendCore(ClientRequestContext context)
 {
     if (!this.BoundSocket.SendAsync(context.SocketContext))
     {
         context.SetCompletedSynchronously();
         this.OnSent(context);
     }
 }
Esempio n. 4
0
		public void TestSetTransport_NotNull_SetAsIs()
		{
			var target = new ClientRequestContext();
			using ( var manager = new NullClientTransportManager() )
			using ( var transport = new NullClientTransport( manager ) )
			{
				target.SetTransport( transport );
				Assert.That( target.BoundTransport, Is.SameAs( transport ) );
			}
		}
        public void TestSetTransport_NotNull_SetAsIs()
        {
            var target = new ClientRequestContext();

            using (var manager = new NullClientTransportManager())
                using (var transport = new NullClientTransport(manager))
                {
                    target.SetTransport(transport);
                    Assert.That(target.BoundTransport, Is.SameAs(transport));
                }
        }
        public void TestPrepare_SetAsNotification_SendingBufferAndSessionAreSet()
        {
            var target = new ClientRequestContext();

            target.SetNotification("A", (_0, _1) => { });
            var oldSessionId = target.SessionId;

            target.Prepare(true);
            Assert.That(target.SendingBuffer.All(segment => segment.Array != null), Is.Not.Null);
            Assert.That(target.BufferList, Is.SameAs(target.SendingBuffer));
        }
        /// <summary>
        ///		Returns the request context to the pool.
        /// </summary>
        /// <param name="context">The context to the pool.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="context"/> is  <c>null</c>.
        /// </exception>
        protected internal void ReturnRequestContext(ClientRequestContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Contract.EndContractBlock();

            context.Clear();
            context.UnboundTransport();
            this.RequestContextPool.Return(context);
        }
Esempio n. 8
0
		public void TestSetRequest_NonNull_PropertiesAreSet()
		{
			int messageId = Environment.TickCount;
			string methodName = Guid.NewGuid().ToString();
			Action<ClientResponseContext, Exception, Boolean> completionCallback = ( _0, _1, _2 ) => { };

			var target = new ClientRequestContext();
			target.SetRequest( messageId, methodName, completionCallback );

			Assert.That( target.MessageType, Is.EqualTo( MessageType.Request ) );
			Assert.That( target.MessageId, Is.EqualTo( messageId ) );
			Assert.That( target.MethodName, Is.EqualTo( methodName ) );
			Assert.That( target.RequestCompletionCallback, Is.EqualTo( completionCallback ) );
			Assert.That( target.NotificationCompletionCallback, Is.Null );
		}
Esempio n. 9
0
		public void TestConstructor_AllPropertiesAreInitialized()
		{
			var target = new ClientRequestContext();

			Assert.That( target.ArgumentsPacker, Is.Not.Null );
			Assert.That( target.BoundTransport, Is.Null );
			Assert.That( target.MessageId, Is.Null );
			Assert.That( target.MessageType, Is.EqualTo( MessageType.Response ) );
			Assert.That( target.MethodName, Is.Null );
			Assert.That( target.NotificationCompletionCallback, Is.Null );
			Assert.That( target.RequestCompletionCallback, Is.Null );
			Assert.That( target.SendingBuffer, Is.Not.Null );
			Assert.That( target.SessionId, Is.EqualTo( 0 ) );
			Assert.That( target.SessionStartedAt, Is.EqualTo( default( DateTimeOffset ) ) );
		}
        public void TestSetNotification_NonNull_PropertiesAreSet()
        {
            string methodName = Guid.NewGuid().ToString();
            Action <Exception, Boolean> completionCallback = (_0, _1) => { };

            var target = new ClientRequestContext();

            target.SetNotification(methodName, completionCallback);

            Assert.That(target.MessageType, Is.EqualTo(MessageType.Notification));
            Assert.That(target.MessageId, Is.Null);
            Assert.That(target.MethodName, Is.EqualTo(methodName));
            Assert.That(target.RequestCompletionCallback, Is.Null);
            Assert.That(target.NotificationCompletionCallback, Is.EqualTo(completionCallback));
        }
        public void TestConstructor_AllPropertiesAreInitialized()
        {
            var target = new ClientRequestContext();

            Assert.That(target.ArgumentsPacker, Is.Not.Null);
            Assert.That(target.BoundTransport, Is.Null);
            Assert.That(target.MessageId, Is.Null);
            Assert.That(target.MessageType, Is.EqualTo(MessageType.Response));
            Assert.That(target.MethodName, Is.Null);
            Assert.That(target.NotificationCompletionCallback, Is.Null);
            Assert.That(target.RequestCompletionCallback, Is.Null);
            Assert.That(target.SendingBuffer, Is.Not.Null);
            Assert.That(target.SessionId, Is.EqualTo(0));
            Assert.That(target.SessionStartedAt, Is.EqualTo(default(DateTimeOffset)));
        }
        /// <summary>
        ///		Returns the specified context to the <see cref="Manager"/>.
        /// </summary>
        /// <param name="context">The <see cref="ClientRequestContext"/> to be returned.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="context"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///		<paramref name="context"/> is not bound to this transport.
        /// </exception>
        public void ReturnContext(ClientRequestContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (!Object.ReferenceEquals(context.BoundTransport, this))
            {
                throw new ArgumentException("Context is not bound to this transport.", "context");
            }

            Contract.EndContractBlock();

            this.Manager.ReturnRequestContext(context);
        }
        public void TestSetRequest_NonNull_PropertiesAreSet()
        {
            int    messageId  = Environment.TickCount;
            string methodName = Guid.NewGuid().ToString();
            Action <ClientResponseContext, Exception, Boolean> completionCallback = (_0, _1, _2) => { };

            var target = new ClientRequestContext();

            target.SetRequest(messageId, methodName, completionCallback);

            Assert.That(target.MessageType, Is.EqualTo(MessageType.Request));
            Assert.That(target.MessageId, Is.EqualTo(messageId));
            Assert.That(target.MethodName, Is.EqualTo(methodName));
            Assert.That(target.RequestCompletionCallback, Is.EqualTo(completionCallback));
            Assert.That(target.NotificationCompletionCallback, Is.Null);
        }
Esempio n. 14
0
        protected sealed override void SendCore(ClientRequestContext context)
        {
            var destination = this._destination;

            if (destination == null)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            var data          = context.BufferList.SelectMany(segment => segment.Array.Skip(segment.Offset).Take(segment.Count)).ToArray();
            var dataEventArgs = new InProcDataSendingEventArgs()
            {
                Data = data
            };

            this.OnDataSending(dataEventArgs);

            if (Interlocked.CompareExchange(ref this._canSend, 0, 0) != 0)
            {
                destination.FeedData(dataEventArgs.Data);
                this.OnMessageSent(new InProcMessageSentEventArgs(context));
            }
            else
            {
                context.SocketError = SocketError.OperationAborted;
            }

            using (var dummySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                if (!this.HandleSocketError(dummySocket, context))
                {
                    return;
                }
            }

            this.OnSent(context);
        }
 protected override void SendCore(ClientRequestContext context)
 {
     throw new NotImplementedException();
 }
Esempio n. 16
0
		protected sealed override void SendCore( ClientRequestContext context )
		{
			var destination = this._destination;
			if ( destination == null )
			{
				throw new ObjectDisposedException( this.ToString() );
			}

			var data = context.BufferList.SelectMany( segment => segment.Array.Skip( segment.Offset ).Take( segment.Count ) ).ToArray();
			var dataEventArgs = new InProcDataSendingEventArgs() { Data = data };
			this.OnDataSending( dataEventArgs );

			if ( Interlocked.CompareExchange( ref this._canSend, 0, 0 ) != 0 )
			{
				destination.FeedData( dataEventArgs.Data );
				this.OnMessageSent( new InProcMessageSentEventArgs( context ) );
			}
			else
			{
				context.SocketError = SocketError.OperationAborted;
			}

			using ( var dummySocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ) )
			{
				if ( !this.HandleSocketError( dummySocket, context ) )
				{
					return;
				}
			}

			this.OnSent( context );
		}
Esempio n. 17
0
		/// <summary>
		///		Performs protocol specific asynchronous 'Send' operation.
		/// </summary>
		/// <param name="context">Context information.</param>
		protected sealed override void SendCore( ClientRequestContext context )
		{
			if ( !this.BoundSocket.SendToAsync( context.SocketContext ) )
			{
				context.SetCompletedSynchronously();
				this.OnSent( context );
			}
		}
Esempio n. 18
0
		/// <summary>
		///		Performs protocol specific asynchronous 'Send' operation.
		/// </summary>
		/// <param name="context">Context information.</param>
		protected override void SendCore( ClientRequestContext context )
		{
			this.OnSent( context );
		}
 /// <summary>
 ///		Performs protocol specific asynchronous 'Send' operation.
 /// </summary>
 /// <param name="context">Context information.</param>
 protected abstract void SendCore(ClientRequestContext context);
 public static byte[] GetMethodName(this ClientRequestContext source)
 {
     return(source.SendingBuffer[2].AsEnumerable().ToArray());
 }
Esempio n. 21
0
		public void TestClear_Initialized()
		{
			int messageId = Environment.TickCount;
			string methodName = Guid.NewGuid().ToString();
			Action<ClientResponseContext, Exception, Boolean> completionCallback = ( _0, _1, _2 ) => { };

			var target = new ClientRequestContext();
			target.RenewSessionId();
			target.SetRequest( messageId, methodName, completionCallback );
			target.ArgumentsPacker.Pack( 1 );
			target.Clear();

			Assert.That( target.ArgumentsPacker, Is.Not.Null );
			Assert.That( target.ArgumentsPacker.Position, Is.EqualTo( 0 ) );
			Assert.That( target.BoundTransport, Is.Null );
			Assert.That( target.MessageId, Is.Null );
			Assert.That( target.MessageType, Is.EqualTo( MessageType.Response ) );
			Assert.That( target.MethodName, Is.Null );
			Assert.That( target.NotificationCompletionCallback, Is.Null );
			Assert.That( target.RequestCompletionCallback, Is.Null );
			Assert.That( target.SendingBuffer.All( segment => segment.Array == null ) );
			Assert.That( target.SessionId, Is.EqualTo( 0 ) );
			Assert.That( target.SessionStartedAt, Is.EqualTo( default( DateTimeOffset ) ) );
		}
Esempio n. 22
0
		public void TestPrepare_SetAsNotification_SendingBufferAndSessionAreSet()
		{
			var target = new ClientRequestContext();
			target.SetNotification( "A", ( _0, _1 ) => { } );
			var oldSessionId = target.SessionId;

			target.Prepare( true );
			Assert.That( target.SendingBuffer.All( segment => segment.Array != null ), Is.Not.Null );
			Assert.That( target.BufferList, Is.SameAs( target.SendingBuffer ) );
		}
Esempio n. 23
0
		/// <summary>
		///		Returns the request context to the pool.
		/// </summary>
		/// <param name="context">The context to the pool.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="context"/> is  <c>null</c>.
		/// </exception>
		protected internal void ReturnRequestContext( ClientRequestContext context )
		{
			if ( context == null )
			{
				throw new ArgumentNullException( "context" );
			}

			Contract.EndContractBlock();

			context.Clear();
			context.UnboundTransport();
			this.RequestContextPool.Return( context );
		}
        /// <summary>
        ///		Called when asynchronous 'Send' operation is completed.
        /// </summary>
        /// <param name="context">Context information.</param>
        /// <returns>
        ///		<c>true</c>, if the subsequent request is already received;
        ///		<c>false</c>, otherwise.
        /// </returns>
        ///	<exception cref="InvalidOperationException">
        ///		This instance is not in 'Sending' state.
        ///	</exception>
        ///	<exception cref="ObjectDisposedException">
        ///		This instance is disposed.
        ///	</exception>
        protected virtual void OnSent(ClientRequestContext context)
        {
            if (MsgPackRpcClientProtocolsTrace.ShouldTrace(MsgPackRpcClientProtocolsTrace.SentOutboundData))
            {
                var socket = this.BoundSocket;
                MsgPackRpcClientProtocolsTrace.TraceEvent(
                    MsgPackRpcClientProtocolsTrace.SentOutboundData,
                    "Sent request/notification. {{ \"SessionID\" : {0}, \"Socket\" : 0x{1:X}, \"RemoteEndPoint\" : \"{2}\", \"LocalEndPoint\" : \"{3}\", \"Type\" : \"{4}\", \"MessageID\" : {5}, \"Method\" : \"{6}\", \"BytesTransferred\" : {7} }}",
                    context.SessionId,
                    GetHandle(socket),
                    GetRemoteEndPoint(socket, context),
                    GetLocalEndPoint(socket),
                    context.MessageType,
                    context.MessageId,
                    context.MethodName,
                    context.BytesTransferred
                    );
            }

            context.StopWatchTimeout();
            context.Timeout -= this.OnSendTimeout;

            context.ClearBuffers();

            if (context.MessageType == MessageType.Notification)
            {
                try
                {
                    Action <Exception, bool> handler = null;
                    try
                    {
                        this._pendingNotificationTable.TryRemove(context.SessionId, out handler);
                    }
                    finally
                    {
                        var rpcError = context.SocketError.ToClientRpcError();
                        if (handler != null)
                        {
                            handler(rpcError.IsSuccess ? null : rpcError.ToException(), context.CompletedSynchronously);
                        }
                    }
                }
                finally
                {
                    this.Manager.ReturnRequestContext(context);
                    this.OnProcessFinished();
                    this.Manager.ReturnTransport(this);
                }
            }
            else
            {
                if (this.Manager.Configuration.WaitTimeout != null &&
                    (this.Manager.Configuration.WaitTimeout.Value - context.ElapsedTime).TotalMilliseconds < 1.0)
                {
                    this.OnWaitTimeout(context);
                    this.Manager.ReturnRequestContext(context);
                    this.Manager.ReturnTransport(this);
                    return;
                }

                var responseContext = this.Manager.GetResponseContext(this, context.RemoteEndPoint);

                if (this.Manager.Configuration.WaitTimeout != null)
                {
                    responseContext.Timeout += this.OnReceiveTimeout;
                    responseContext.StartWatchTimeout(this.Manager.Configuration.WaitTimeout.Value - context.ElapsedTime);
                }

                this.Manager.ReturnRequestContext(context);
                this.Receive(responseContext);
            }
        }
 /// <summary>
 ///		Performs protocol specific asynchronous 'Send' operation.
 /// </summary>
 /// <param name="context">Context information.</param>
 protected override void SendCore(ClientRequestContext context)
 {
     this.OnSent(context);
 }
 public static byte[] GetArguments(this ClientRequestContext source)
 {
     return(source.SendingBuffer[3].AsEnumerable().ToArray());
 }
Esempio n. 27
0
		internal InProcMessageSentEventArgs( ClientRequestContext context )
		{
			this._context = context;
		}
Esempio n. 28
0
		public void TestSetNotification_NonNull_PropertiesAreSet()
		{
			string methodName = Guid.NewGuid().ToString();
			Action<Exception, Boolean> completionCallback = ( _0, _1 ) => { };

			var target = new ClientRequestContext();
			target.SetNotification( methodName, completionCallback );

			Assert.That( target.MessageType, Is.EqualTo( MessageType.Notification ) );
			Assert.That( target.MessageId, Is.Null );
			Assert.That( target.MethodName, Is.EqualTo( methodName ) );
			Assert.That( target.RequestCompletionCallback, Is.Null );
			Assert.That( target.NotificationCompletionCallback, Is.EqualTo( completionCallback ) );
		}
        /// <summary>
        ///		Sends a request or notification message with the specified context.
        /// </summary>
        /// <param name="context">The context information.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="context"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///		<paramref name="context"/> is not bound to this transport.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///		This instance has been disposed.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///		This instance is in shutdown.
        ///		Or the message ID or session ID is duplicated.
        /// </exception>
        /// <exception cref="RpcException">
        ///		Failed to send request or notification to the server.
        /// </exception>
        public void Send(ClientRequestContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (!Object.ReferenceEquals(context.BoundTransport, this))
            {
                throw new ArgumentException("Context is not bound to this object.", "context");
            }

            this.VerifyIsNotDisposed();

            if (this.IsClientShutdown)
            {
                throw new InvalidOperationException("This transport is in shutdown.");
            }

            Contract.EndContractBlock();

            if (this.IsServerShutdown)
            {
                throw new RpcErrorMessage(RpcError.TransportError, "Server did shutdown socket.", null).ToException();
            }

            context.Prepare(this.CanUseChunkedBuffer);

            if (context.MessageType == MessageType.Request)
            {
                if (!this._pendingRequestTable.TryAdd(context.MessageId.Value, context.RequestCompletionCallback))
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "Message ID '{0}' is already used.", context.MessageId));
                }
            }
            else
            {
                if (!this._pendingNotificationTable.TryAdd(context.SessionId, context.NotificationCompletionCallback))
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "Session ID '{0}' is already used.", context.MessageId));
                }
            }

            if (MsgPackRpcClientProtocolsTrace.ShouldTrace(MsgPackRpcClientProtocolsTrace.SendOutboundData))
            {
                var socket = this.BoundSocket;
                MsgPackRpcClientProtocolsTrace.TraceEvent(
                    MsgPackRpcClientProtocolsTrace.SendOutboundData,
                    "Send request/notification. {{ \"SessionID\" : {0}, \"Socket\" : 0x{1:X}, \"RemoteEndPoint\" : \"{2}\", \"LocalEndPoint\" : \"{3}\", \"Type\" : \"{4}\", \"MessageID\" : {5}, \"Method\" : \"{6}\", \"BytesTransferring\" : {7} }}",
                    context.SessionId,
                    GetHandle(socket),
                    GetRemoteEndPoint(socket, context),
                    GetLocalEndPoint(socket),
                    context.MessageType,
                    context.MessageId,
                    context.MethodName,
                    context.SendingBuffer.Sum(segment => ( long )segment.Count)
                    );
            }

            // Because exceptions here means client error, it should be handled like other client error.
            // Therefore, no catch clauses here.
            ApplyFilters(this._afterSerializationFilters, context);

            if (this.Manager.Configuration.WaitTimeout != null)
            {
                context.Timeout += this.OnSendTimeout;
                context.StartWatchTimeout(this.Manager.Configuration.WaitTimeout.Value);
            }

            this.SendCore(context);
        }
Esempio n. 30
0
 internal InProcMessageSentEventArgs(ClientRequestContext context)
 {
     this._context = context;
 }
 public static byte[] GetTypeHeader(this ClientRequestContext source)
 {
     return(source.SendingBuffer[0].AsEnumerable().ToArray());
 }