public ServerProcessing ProcessMessage(
			IServerChannelSinkStack sinkStack_in,
			IMessage requestMsg_in,
			ITransportHeaders requestHeaders_in,
			Stream requestStream_in,

			out IMessage responseMsg_out,
			out ITransportHeaders responseHeaders_out,
			out Stream responseStream_out
		) {
			if (nextchannelsink_ != null) {
				CallContext.SetData(
					"ClientIPAddress", 
					((IPAddress)requestHeaders_in[CommonTransportKeys.IPAddress]).ToString()
				);
				ServerProcessing _serverprocessing = NextChannelSink.ProcessMessage(
					sinkStack_in,
					requestMsg_in,
					requestHeaders_in,
					requestStream_in,

					out responseMsg_out,
					out responseHeaders_out,
					out responseStream_out
				);
				return _serverprocessing;
			} else {
				responseMsg_out = null;
				responseHeaders_out = null;
				responseStream_out = null;
				return new ServerProcessing();
			}
		}
示例#2
0
        void ProcessMessage(IPEndPoint remote, ITransportHeaders requestHeaders, Stream requestStream)
        {
            // parse request uri
            var url = requestHeaders[CommonTransportKeys.RequestUri].ToString();
            string objectUri;
            UdpChannelHelper.Parse(url, out objectUri);
            objectUri = objectUri ?? url;
            requestHeaders[CommonTransportKeys.RequestUri] = objectUri;

            IMessage responseMsg;
            ITransportHeaders responseHeaders;
            Stream responseStream;

            // process message
            var stack = new ServerChannelSinkStack();
            stack.Push(this, null);
            var operation = NextChannelSink.ProcessMessage(stack, null, requestHeaders, requestStream,
                out responseMsg, out responseHeaders, out responseStream);

            switch (operation)
            {
                case ServerProcessing.Complete:
                    stack.Pop(this);
                    var transport = new UdpTransport(new UdpClient());
                    transport.Write(responseHeaders, responseStream, remote);
                    break;

                case ServerProcessing.Async:
                    stack.StoreAndDispatch(NextChannelSink, null);
                    break;

                case ServerProcessing.OneWay:
                    break;
            }
        }
		public Stream GetRequestStream(IMessage requestMsg, ITransportHeaders requestHeaders)
		{
			// parameters validation
			if (requestHeaders == null)
				throw new ArgumentNullException("requestHeaders");

			IMethodCallMessage methodCall = requestMsg as IMethodCallMessage;
			if (methodCall == null)
				throw new NotSupportedException();

			if (_connection != null)
			{
				// close connection as it is probably not valid
				_connection.Close();
			}

			// get connection from the cache
			_connection = _connectionCache.GetConnection(_channelUri);

			try
			{
				// return stream for writing request
				return _connection.GetRequestStream(methodCall, requestHeaders);
			}
			catch
			{
				// close connection as it is probably not valid
				_connection.Close();
				_connection = null;
				throw;
			}
		}
 private Header[] GetChannelHeaders(ITransportHeaders requestHeaders, out string soapActionToVerify)
 {
     string str3;
     string str4;
     soapActionToVerify = null;
     string uRI = (string) requestHeaders["__RequestUri"];
     string uri = (string) requestHeaders["SOAPAction"];
     if (uri == null)
     {
         throw new RemotingException(CoreChannel.GetResourceString("Remoting_SoapActionMissing"));
     }
     uri = HttpEncodingHelper.DecodeUri(uri);
     soapActionToVerify = uri;
     if (!SoapServices.GetTypeAndMethodNameFromSoapAction(uri, out str3, out str4))
     {
         Type serverTypeForUri = RemotingServices.GetServerTypeForUri(uRI);
         if (serverTypeForUri == null)
         {
             throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_TypeNotFoundFromUri"), new object[] { uRI }));
         }
         str3 = "clr:" + serverTypeForUri.FullName + ", " + serverTypeForUri.Assembly.GetName().Name;
     }
     else
     {
         str3 = "clr:" + str3;
     }
     int num = 2;
     Header[] headerArray = new Header[num];
     headerArray[0] = new Header("__Uri", uRI);
     headerArray[1] = new Header("__TypeName", str3);
     return headerArray;
 }
示例#5
0
		public Stream GetResponseStream (IServerResponseChannelSinkStack sinkStack,
						 object state,
						 IMessage msg,
						 ITransportHeaders headers)
		{
			return null;
		}
		public IMethodCallMessage DeserializeRequest(ITransportHeaders requestHeaders, Stream requestStream)
		{
			string uri = (string)requestHeaders["__RequestUri"];
			UriHeaderHandler uriHH = new UriHeaderHandler(uri);

			return (IMethodCallMessage)_deserializer.Deserialize(requestStream, new HeaderHandler(uriHH.HeaderHandler));
		}
示例#7
0
 public Stream GetResponseStream (IServerResponseChannelSinkStack sinkStack,
                                  object state,
                                  IMessage msg,
                                  ITransportHeaders headers)
 {
   throw new NotImplementedException();
 }
		public void AsyncProcessRequest (IClientChannelSinkStack sinkStack, IMessage msg,
			ITransportHeaders headers, Stream requestStream)
		{
			TcpConnection connection = null;
			bool isOneWay = RemotingServices.IsOneWay (((IMethodMessage)msg).MethodBase);

			try
			{
				if (headers == null) headers = new TransportHeaders();
				headers [CommonTransportKeys.RequestUri] = ((IMethodMessage)msg).Uri;
				
				// Sends the stream using a connection from the pool
				// and creates a WorkItem that will wait for the
				// response of the server

				connection = TcpConnectionPool.GetConnection (_host, _port);
				TcpMessageIO.SendMessageStream (connection.Stream, requestStream, headers, connection.Buffer);
				connection.Stream.Flush ();

				if (!isOneWay) 
				{
					sinkStack.Push (this, connection);
					ThreadPool.QueueUserWorkItem (new WaitCallback(ReadAsyncTcpMessage), sinkStack);
				}
				else
					connection.Release();
			}
			catch
			{
				if (connection != null) connection.Release();
				if (!isOneWay) throw;
			}
		}
 public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders headers, Stream requestStream)
 {
     ITransportHeaders headers2;
     Stream stream;
     AsyncCallback callback = new AsyncCallback(this.AsyncFinishedCallback);
     new AsyncMessageDelegate(this.AsyncProcessMessage).BeginInvoke(msg, headers, requestStream, out headers2, out stream, sinkStack, callback, null);
 }
示例#10
0
		private static bool isHeaderEncrypted(ITransportHeaders headers_in) {
			return (
				(headers_in[EncryptionHelper.X_ENCRYPT] != null)
				&&
				((string)headers_in[EncryptionHelper.X_ENCRYPT] == "1")
			);
		} 
示例#11
0
		public void AsyncProcessRequest(
			IClientChannelSinkStack sinkStack_in,
			IMessage msg_in,
			ITransportHeaders headers_in,
			Stream stream_in
		) {
			#region encrypt...
			headers_in[EncryptionHelper.X_ENCRYPT] = "1";
			headers_in[EncryptionHelper.X_CLIENTID] = this.clientid_;
			stream_in
				= EncryptionHelper.Encrypt(
					stream_in,
					false,
					this.keyspath_,
					this.clientid_
				); 
			#endregion

			sinkStack_in.Push(this, null);
			this.nextchannelsink_.AsyncProcessRequest(
				sinkStack_in,
				msg_in,
				headers_in,
				stream_in
			);
		} 
示例#12
0
		public void AsyncProcessResponse(
			IServerResponseChannelSinkStack sinkStack_in, 
			object state_in,
			IMessage message_in, 
			ITransportHeaders headers_in, 
			Stream stream_in
		) {
#if DEBUG
			Console.WriteLine("compression sink: AsyncProcessResponse...");
#endif
			bool _hasBeenCompressed = (bool)state_in;

			if (_hasBeenCompressed) {
				#region compress...
				headers_in[CompressionHelper.X_COMPRESS] = "1";

				stream_in = CompressionHelper.GetCompressedStreamCopy(
					stream_in
				); 
				#endregion
			} else {
				if (this.mustdo_) {
					throw new Exception("\n\n\t\tyour activity is being logged!\n\n\t\tun-compressed communications not allowed!\n\n");
				}
			}

			sinkStack_in.AsyncProcessResponse(
				message_in,
				headers_in, 
				stream_in
			);
		} 
		public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state, ITransportHeaders responseHeaders, Stream responseStream)
		{
			// parameters validation
			if (sinkStack == null)
				throw new ArgumentNullException("sinkStack");
			if (responseHeaders == null)
				throw new ArgumentNullException("responseHeaders");
			if (responseStream == null)
				throw new ArgumentNullException("responseStream");

			IMethodCallMessage methodCall = state as IMethodCallMessage;
			if (methodCall == null)
				throw new NotSupportedException();

			IMethodReturnMessage methodReturn;
			try
			{
				// deserialize response
				methodReturn = _formatter.DeserializeResponse(methodCall, responseHeaders, responseStream);
				responseStream.Close();
			}
			catch (Exception ex)
			{
				methodReturn = new ReturnMessage(ex, methodCall);
			}

			// dispatch response
			sinkStack.DispatchReplyMessage(methodReturn);
		}
 public ServerProcessing ProcessMessage(
         IServerChannelSinkStack sinkStack,
         IMessage requestMsg,
         ITransportHeaders requestHeaders,
         Stream requestStream,
         out IMessage responseMsg,
         out ITransportHeaders responseHeaders,
         out Stream responseStream)
 {
     if (_nextSink != null)
         {
             IPAddress ip =
                 requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;
             CallContext.SetData("ClientIPAddress", ip);
             ServerProcessing spres = _nextSink.ProcessMessage(
                 sinkStack,
                 requestMsg,
                 requestHeaders,
                 requestStream,
                 out responseMsg,
                 out responseHeaders,
                 out responseStream);
             return spres;
         }
         else
         {
             responseMsg = null;
             responseHeaders = null;
             responseStream = null;
             return new ServerProcessing();
         }
 }
示例#15
0
		private static bool isHeaderCompressed_(ITransportHeaders headers_in) {
			return (
				(headers_in[CompressionHelper.X_COMPRESS] != null)
				&&
				((string)headers_in[CompressionHelper.X_COMPRESS] == "1")
			);
		}
示例#16
0
 public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
     ITransportHeaders headers, Stream stream)
 {
     // never gets called, this sink is always first
     sinkStack.Push(this, null);
     _nextSink.AsyncProcessRequest(sinkStack, msg, headers, stream);
 }
示例#17
0
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg,
							ITransportHeaders requestHeaders,
							Stream requestStream,
							out IMessage responseMsg,
							out ITransportHeaders responseHeaders,
							out Stream responseStream)
		{
			IMessage call;
			
			string uri = (string)requestHeaders [CommonTransportKeys.RequestUri];

			if (requestMsg == null) {
				call = (IMessage)format.DeserializeRequest (requestStream, uri);
			} else { 
				call = requestMsg;
			}

			next_sink.ProcessMessage (sinkStack, call, requestHeaders, null,
						  out responseMsg, out responseHeaders, out responseStream);
						
			responseStream = new MemoryStream ();

			format.SerializeResponse (responseStream, responseMsg);
			
			return ServerProcessing.Complete;
		}
示例#18
0
		/// <summary></summary>
		public ServerProcessing ProcessMessage(
			IServerChannelSinkStack sinkStack,
			IMessage requestMsg,
			ITransportHeaders requestHeaders,
			Stream requestStream,
			out IMessage responseMsg,
			out ITransportHeaders responseHeaders,
			out Stream responseStream)
		{
			if (NextChannelSink != null)
			{
				SetClientIpAddressDataHelper(requestHeaders);
				ServerProcessing spres = NextChannelSink.ProcessMessage(
					sinkStack,
					requestMsg,
					requestHeaders,
					requestStream,
					out responseMsg,
					out responseHeaders,
					out responseStream);
				return spres;
			}

			responseMsg = null;
			responseHeaders = null;
			responseStream = null;
			return new ServerProcessing();
		}
示例#19
0
        public RemotingHttpRequest(ITransportHeaders headers, Stream stream)
        {
            Method = (String)headers["__RequestVerb"];
            Host = (String)headers["Host"];
            UserAgent = (String)headers["User-Agent"];

            String requestUri = (String)headers["__RequestUri"];
            Url = "http://" + Host + requestUri;

            Int32 offset = requestUri.IndexOf('?');
            if (offset >= 0)
            {
                RequestUri = requestUri.Substring(0, offset);
                QueryString = requestUri.Substring(offset + 1);
            }
            else
            {
                RequestUri = requestUri;
                QueryString = null;
            }

            foreach (DictionaryEntry item in headers)
            {
                if (item.Value is String)
                    _headers.Add((String)item.Key, (String)item.Value);
            }

            InputStream = stream;
        }
        public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state, ITransportHeaders headers, Stream stream)
        {
            RequestState rs = state as RequestState;
            if (rs != null && rs.didCompress) {
                bool compressOK = object.Equals(headers[CompressionHelper.CompressKey], CompressionHelper.CompressedFlag);
                if (!compressOK) {
                    serverCanCompress = false;
                    checkedCompress = true;

                    // synchronously send the message now
                    rs.origStream.Position = rs.origPos;
                    ProcessMessage(rs.msg, rs.headers, rs.origStream, out headers, out stream);
                }
                else {
                    // decompress stuff
                    stream = CompressionHelper.DecompressStream(stream);

                    serverCanCompress = true;
                    checkedCompress = true;
                }
                rs.origStream.Close();
            }

            // process through the rest of the stacks
            sinkStack.AsyncProcessResponse(headers, stream);
        }
 internal void SendRequest(IMessage msg, ITransportHeaders headers, Stream contentStream)
 {
     IMethodCallMessage message = (IMethodCallMessage) msg;
     int length = (int) contentStream.Length;
     string uri = message.Uri;
     this._bOneWayRequest = RemotingServices.IsOneWay(message.MethodBase);
     ChunkedMemoryStream outputStream = new ChunkedMemoryStream(CoreChannel.BufferPool);
     base.WritePreambleAndVersion(outputStream);
     if (!this._bOneWayRequest)
     {
         base.WriteUInt16(0, outputStream);
     }
     else
     {
         base.WriteUInt16(1, outputStream);
     }
     base.WriteUInt16(0, outputStream);
     base.WriteInt32(length, outputStream);
     base.WriteUInt16(4, outputStream);
     base.WriteByte(1, outputStream);
     base.WriteCountedString(uri, outputStream);
     base.WriteHeaders(headers, outputStream);
     outputStream.WriteTo(base.NetStream);
     outputStream.Close();
     StreamHelper.CopyStream(contentStream, base.NetStream);
     contentStream.Close();
 }
示例#22
0
        public void Write(ITransportHeaders headers, Stream stream, IPEndPoint endpoint)
        {
            using (var ms = new MemoryStream())
            using (var bw = new BinaryWriter(ms))
            {
                foreach (DictionaryEntry entry in headers)
                {
                    bw.Write(HeaderMarker);
                    bw.Write(entry.Key.ToString());
                    bw.Write(entry.Value.ToString());
                }

                var length = (int)stream.Length;
                var br = new BinaryReader(stream);

                bw.Write(DataMarker);
                bw.Write(length);
                bw.Write(br.ReadBytes(length));
                bw.Flush();

                // FIXME: 1) reliability 2) check buffer size
                var buffer = ms.ToArray();
                UdpClient.Send(buffer, buffer.Length, endpoint);
            }
        }
示例#23
0
		// =============== IClientChannelSink implementation ========================

		/// <summary>
		/// Request synchronous processing of a method call on the current sink.
		/// </summary>
		/// <param name="msg"><see cref="IMessage"/> to process.</param>
		/// <param name="requestHeaders">Request <see cref="ITransportHeaders"/>.</param>
		/// <param name="requestStream">Request <see cref="Stream"/>.</param>
		/// <param name="responseHeaders">Response <see cref="ITransportHeaders"/>.</param>
		/// <param name="responseStream">Response <see cref="Stream"/>.</param>
		public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			IMessage replyMsg;

			// process serialized message
			InternalProcessMessage(msg, requestHeaders, requestStream, out replyMsg, out responseHeaders, out responseStream);
		}
示例#24
0
        protected override void ProcessRequest(IMessage message, ITransportHeaders headers, ref Stream stream, ref object state)
        {
            if (headers["CustomEncryption"] != null && headers["Credentials"] != null)
            {

                var args = new EncryptCredentials(headers["Credentials"].ToString());
                User user = new User();
                user.Username = string.Format("{0}", args["Username"]);
                user.Password = string.Format("{0}", args["Password"]);
                user.AddressTable.Add(user.Username, string.Format("{0}", args["Uri"]));
                UserDataManager userManager = new UserDataManager();
                if (user != null && userManager.UserLogOn(user.Username, user.Password) != null)
                {
                    // okay
                    Console.WriteLine(
                        "AuthServerSink: retrieved valid credential information: username: {0}, password {1}.",
                        user.Username, user.Password);
                    LoginInfo.Authenticated = true;
                    LoginInfo.LoginName = user.Username;
                    LoginInfo.LoginPassword = user.Password;

                    Console.WriteLine("EncryptServerSink: decrypting request");
                    stream = this.Decrypt(stream);
                    state = true;

                    return;
                }
            }
            // not good!
            Console.WriteLine(
                "DemoCredentialsServerSink: retrieved bad credentials or credentials are missing. Throwing an exception.");
            throw new RemotingException("Invalid credentials.");
        }
示例#25
0
        public IPEndPoint Read(out ITransportHeaders headers, out Stream stream, out IPEndPoint remote)
        {
            // FIXME: 1) reliability 2) exceptions
            remote = new IPEndPoint(IPAddress.Loopback, 0);
            var buffer = UdpClient.Receive(ref remote);

            using (var ms = new MemoryStream(buffer))
            using (var br = new BinaryReader(ms))
            {
                var marker = br.ReadInt16();
                if (marker != HeaderMarker && marker != DataMarker)
                {
                    throw new InvalidDataException("Unexpected datagram format");
                }

                // read transport headers
                headers = new TransportHeaders();
                while (marker != DataMarker)
                {
                    var name = br.ReadString();
                    var value = br.ReadString();
                    headers[name] = value;
                    marker = br.ReadInt16();
                }

                // get response stream
                var length = br.ReadInt32();
                stream = new MemoryStream(buffer, (int)ms.Position, length);
            }

            return remote;
        }
 private IMessage DeserializeMessage(IMethodCallMessage mcm, ITransportHeaders headers, Stream stream)
 {
     IMessage message;
     string str2;
     string str3;
     Header[] h = new Header[] { new Header("__TypeName", mcm.TypeName), new Header("__MethodName", mcm.MethodName), new Header("__MethodSignature", mcm.MethodSignature) };
     string contentType = headers["Content-Type"] as string;
     HttpChannelHelper.ParseContentType(contentType, out str2, out str3);
     if (string.Compare(str2, "text/xml", StringComparison.Ordinal) == 0)
     {
         message = CoreChannel.DeserializeSoapResponseMessage(stream, mcm, h, this._strictBinding);
     }
     else
     {
         int count = 0x400;
         byte[] buffer = new byte[count];
         StringBuilder builder = new StringBuilder();
         for (int i = stream.Read(buffer, 0, count); i > 0; i = stream.Read(buffer, 0, count))
         {
             builder.Append(Encoding.ASCII.GetString(buffer, 0, i));
         }
         message = new ReturnMessage(new RemotingException(builder.ToString()), mcm);
     }
     stream.Close();
     return message;
 }
示例#27
0
        public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders requestHeaders, Stream requestStream)
        {
            // add message Uri to headers
            var mcm = (IMethodCallMessage)msg;
            requestHeaders[CommonTransportKeys.RequestUri] = mcm.Uri;

            // send data (FIXME: 1) add reliability, 2) handle exceptions)
            var transport = new UdpTransport(UdpClient);
            transport.Write(requestHeaders, requestStream, ServerEndpoint);

            // if the call is not one-way, schedule an async call
            if (!RemotingServices.IsOneWay(mcm.MethodBase))
            {
                ThreadPool.QueueUserWorkItem((s) =>
                {
                    try
                    {
                        ITransportHeaders responseHeaders;
                        Stream responseStream;
                        IPEndPoint remote;
                        transport.Read(out responseHeaders, out responseStream, out remote);
                        sinkStack.AsyncProcessResponse(responseHeaders, responseStream);
                    }
                    catch (Exception ex)
                    {
                        sinkStack.DispatchException(ex);
                    }
                });
            }
        }
示例#28
0
        /// <summary>
        /// Processes an asynchronous request.
        /// </summary>
        /// <param name="sinkStack">Channel sink stack</param>
        /// <param name="msg">Message to processed</param>
        /// <param name="headers">Transport headers</param>
        /// <param name="stream">Request stream</param>
        public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders headers, Stream stream)
        {
            stream = CreateEnvelope(stream, headers);

            sinkStack.Push(this, null);
            _nextSink.AsyncProcessRequest(sinkStack, msg, headers, stream);
        }
		public void ReceiveRequest(out ITransportHeaders requestHeaders, out Stream requestStream)
		{
			// transport signature
			if (!MatchPreamble())
				BinaryWireProtocol.ThrowException(BinaryWireProtocol.StatusCode.InvalidMessageFormat);
			// operation opcode
			byte operation = _reader.ReadByte();
			if (operation != BinaryWireProtocol.OperationType.Request && operation != BinaryWireProtocol.OperationType.OneWayRequest)
				BinaryWireProtocol.ThrowException(BinaryWireProtocol.StatusCode.InvalidMessageFormat);
			// content length
			int contentLength = _reader.ReadInt32();
			// request uri
			string requestUri = _reader.ReadString();
			if (!CheckRequestUri(requestUri))
				BinaryWireProtocol.ThrowException(BinaryWireProtocol.StatusCode.InvalidRequestUri);
			// request headers
			requestHeaders = ReadHeaders();
			// set special headers
			requestHeaders[BinaryWireProtocol.WellKnownHeaders.ConnectionId] = _connectionId;
			requestHeaders[BinaryWireProtocol.WellKnownHeaders.RequestUri] = requestUri;

			// create stream for request reading
			if (contentLength == -1)
			{
				requestStream = new ChunkedReadStream(_bufferedStream);
			}
			else
			{
				requestStream = new FixedReadStream(_bufferedStream, contentLength);
			}

			// set client principal
			RemotingService.ClientPrincipal = _transport.ClientPrincipal;
		}
		public ServerProcessing ProcessMessage(
			IServerChannelSinkStack sinkStack, 
			IMessage requestMsg, 
			ITransportHeaders requestHeaders, 
			Stream requestStream, 
			out IMessage responseMsg, 
			out ITransportHeaders responseHeaders, 
			out Stream responseStream)
		{
			var ip = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;
			CallContext.SetData("ClientIPAddress", ip);

			var connectionId = (Int64)requestHeaders[CommonTransportKeys.ConnectionId];
			CallContext.SetData("ClientConnectionId", connectionId); 
			
			if (_next != null) 
			{
				var spres =  _next.ProcessMessage (sinkStack,requestMsg, requestHeaders,requestStream,out responseMsg,out responseHeaders,out responseStream);
				return spres;
			} 
			else 
			{
				responseMsg=null;
				responseHeaders=null;
				responseStream=null;
				return new ServerProcessing();
			}
		}
        } // ProcessMessage

        public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, Object state,
                                         IMessage msg, ITransportHeaders headers, Stream stream)
        {
            // We never push ourselves to the sink stack, so this won't be called.
            throw new NotSupportedException();
        } // AsyncProcessResponse
示例#32
0
 void IServerChannelSink.AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, ITransportHeaders headers, System.IO.Stream stream)
 {
     nextSink.AsyncProcessResponse(sinkStack, state, msg, headers, stream);
 }
示例#33
0
 System.IO.Stream IServerChannelSink.GetResponseStream(IServerResponseChannelSinkStack sinkStack, object state, System.Runtime.Remoting.Messaging.IMessage msg, ITransportHeaders headers)
 {
     return(nextSink.GetResponseStream(sinkStack, state, msg, headers));
 }
 public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack,
                                  object state, IMessage msg, ITransportHeaders headers, Stream stream)
 {
     headers["X-Cache"] = "60";
     sinkStack.AsyncProcessResponse(msg, headers, stream);
 }
        } // AsyncProcessResponse

        public Stream GetResponseStream(IServerResponseChannelSinkStack sinkStack, Object state,
                                        IMessage msg, ITransportHeaders headers)
        {
            // We never push ourselves to the sink stack, so this won't be called.
            throw new NotSupportedException();
        } // GetResponseStream
        /// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="msg">The message to process.</param>
        /// <param name="requestHeaders">The headers to add to the outgoing message heading to the server.</param>
        /// <param name="requestStream">The stream headed to the transport sink.</param>
        /// <param name="responseHeaders">When this method returns, contains an ITransportHeaders interface that holds the headers that the server returned. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a Stream coming back from the transport sink. This parameter is passed uninitialized.</param>
        public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream,
                                   out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            BinaryLogWriter   binaryLogWriter   = this.ITransportContext.BinaryLogWriter;
            ITransportContext iTransportContext = this.ITransportContext;

            if (!GenuineUtility.CheckUrlOnConnectivity(this._recipientUri))
            {
                // get the transport context from the Uri Storage
                iTransportContext = UriStorage.GetTransportContext(this._recipientUri);
                if (iTransportContext == null)
                {
                    iTransportContext = this.ITransportContext;
                }
            }

            Message message = Message.CreateOutcomingMessage(iTransportContext, msg, requestHeaders, requestStream, true);

            try
            {
                message.Recipient = iTransportContext.KnownHosts[this._recipientUri];

                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteMessageCreatedEvent("GenuineTcpClientTransportSink.ProcessMessage",
                                                             LogMessageType.MessageCreated, null, message, true, message.Recipient,
                                                             this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? message.Stream : null,
                                                             msg.Properties["__Uri"] as string, BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string),
                                                             GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
                                                             "Synchronous .NET Remoting invocaiton is being initiated.");

                    message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = msg.Properties["__Uri"] as string;
                    message.ITransportHeaders[Message.TransportHeadersMethodName]       = BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string);

                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageRequestInvoking, null, message, message.Recipient,
                                               null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1, GenuineUtility.TickCount, 0, 0, null, null, null, null,
                                               "The .NET Remoting synchronous invocation has been made.");
                }

                SyncSinkStackResponseProcessor syncSinkStackResponseProcessor = new SyncSinkStackResponseProcessor(iTransportContext, message);
                iTransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, syncSinkStackResponseProcessor);
                message.CancelSending = syncSinkStackResponseProcessor.IsReceivedEvent;

                try
                {
                    // send the message or initiate the sending
                    iTransportContext.ConnectionManager.Send(message);
                }
                catch (Exception ex)
                {
                    // if it's a response processor's problem, force its exception to be fired
                    if (syncSinkStackResponseProcessor.DispatchedException != null)
                    {
                        throw OperationException.WrapException(syncSinkStackResponseProcessor.DispatchedException);
                    }

                    syncSinkStackResponseProcessor.DispatchException(ex);
                    throw;
                }

                if (!GenuineUtility.WaitOne(syncSinkStackResponseProcessor.IsReceivedEvent, GenuineUtility.GetMillisecondsLeft(message.FinishTime)))
                {
                    throw GenuineExceptions.Get_Send_ServerDidNotReply();
                }
                if (syncSinkStackResponseProcessor.DispatchedException != null)
                {
                    throw OperationException.WrapException(syncSinkStackResponseProcessor.DispatchedException);
                }

                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageDispatched, null, syncSinkStackResponseProcessor.Response, syncSinkStackResponseProcessor.Response.Sender,
                                               null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1,
                                               GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                               "The .NET Remoting synchronous invocation has been completed.");
                }

                responseHeaders = syncSinkStackResponseProcessor.Response.ITransportHeaders;
                responseStream  = syncSinkStackResponseProcessor.Response.Stream;
            }
            catch (Exception ex)
            {
                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageDispatched, ex, message, message.Recipient, null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1,
                                               GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                               "The exception is dispatched to the caller context.");
                }

                throw;
            }
        }
 public Stream GetResponseStream(IServerResponseChannelSinkStack sinkStack,
                                 object state, IMessage msg, ITransportHeaders headers)
 {
     return(null);
 }
 /// <summary>
 /// Requests asynchronous processing of a response to a method call on the current sink.
 /// </summary>
 /// <param name="sinkStack">A stack of sinks that called this sink.</param>
 /// <param name="state">Information generated on the request side that is associated with this sink.</param>
 /// <param name="headers">The headers retrieved from the server response stream.</param>
 /// <param name="stream">The stream coming back from the transport sink.</param>
 public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state,
                                  ITransportHeaders headers, Stream stream)
 {
     throw new NotSupportedException();
 }
示例#39
0
 public void AsyncProcessResponse(ITransportHeaders headers, Stream stream)
 {
 }
 public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state, ITransportHeaders headers, Stream stream)
 {
     throw new RemotingException("Wrong sequence in config file - clientProviders");
 }
 /// <summary>
 /// Returns the Stream onto which the provided message is to be serialized.
 /// </summary>
 /// <param name="msg">The IMethodCallMessage containing details about the method call.</param>
 /// <param name="headers">The headers to add to the outgoing message heading to the server.</param>
 /// <returns>The Stream onto which the provided message is to be serialized.</returns>
 public Stream GetRequestStream(IMessage msg, ITransportHeaders headers)
 {
     return(null);
 }
示例#42
0
 public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, Object state,
                                  ITransportHeaders headers, Stream stream1)
 {
     sinkStack.AsyncProcessResponse(headers, stream1);
 }
        /// <summary>
        /// Requests asynchronous processing of a method call on the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called this sink.</param>
        /// <param name="msg">The message to process.</param>
        /// <param name="headers">The headers to add to the outgoing message heading to the server.</param>
        /// <param name="stream">The stream headed to the transport sink.</param>
        public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
                                        ITransportHeaders headers, Stream stream)
        {
            ITransportContext iTransportContext = this.ITransportContext;

            if (!GenuineUtility.CheckUrlOnConnectivity(this._recipientUri))
            {
                // get the transport context from the Uri Storage
                iTransportContext = UriStorage.GetTransportContext(this._recipientUri);
                if (iTransportContext == null)
                {
                    iTransportContext = this.ITransportContext;
                }
            }

            Message message = Message.CreateOutcomingMessage(iTransportContext, msg, headers, stream, false);

            message.Recipient = iTransportContext.KnownHosts[this._recipientUri];
            IMethodMessage iMethodMessage = (IMethodMessage)msg;

            message.IsOneWay = RemotingServices.IsOneWay(iMethodMessage.MethodBase);

            // LOG: put down the log record
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;

            if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
            {
                binaryLogWriter.WriteMessageCreatedEvent("GenuineTcpClientTransportSink.AsyncProcessRequest",
                                                         LogMessageType.MessageCreated, null, message, true, message.Recipient,
                                                         this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? message.Stream : null,
                                                         msg.Properties["__Uri"] as string, BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string),
                                                         GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
                                                         "Asynchronous .NET Remoting invocaiton is being initiated.");

                message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = msg.Properties["__Uri"] as string;
                message.ITransportHeaders[Message.TransportHeadersMethodName]       = BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string);

                binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.AsyncProcessRequest",
                                           LogMessageType.MessageRequestInvoking, null, message, message.Recipient,
                                           null,
                                           GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                           null, null, -1,
                                           GenuineUtility.TickCount, 0, 0, null, null, null, null,
                                           "The .NET Remoting asynchronous invocation is being initiated.");
            }

            // register the response handler
            AsyncSinkStackResponseProcessor asyncSinkStackResponseProcessor = null;

            if (!message.IsOneWay)
            {
                asyncSinkStackResponseProcessor = new AsyncSinkStackResponseProcessor(iTransportContext, message, sinkStack);
                iTransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, asyncSinkStackResponseProcessor);
            }

            try
            {
                // and try to send the message
                iTransportContext.ConnectionManager.Send(message);
            }
            catch (Exception ex)
            {
                asyncSinkStackResponseProcessor.DispatchException(ex);
                throw;
            }
        }
示例#44
0
 public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, Object state,
                                  IMessage msg, ITransportHeaders headers, Stream stream1)
 {
     sinkStack.AsyncProcessResponse(msg, headers, stream1);
 }
        public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msgReq, ITransportHeaders headers, Stream stream)
        {
            // scope state
            string  strQueuePath         = null;
            string  strObjectUri         = null;
            Message outMsg               = null;
            MessageQueueTransaction mqtx = new MessageQueueTransaction();

            try
            {
                #region pre-processor (mapping url address)
                // split into the queuepath and endpoint
                strObjectUri = ParseLogicalUrl(m_LogicalUri, out strQueuePath);

                // update Uri property
                msgReq.Properties[MSMQChannelProperties.ObjectUri] = strObjectUri;

                // pass TransportHeaders to the receiver
                if (m_Sender.AllowHeaders == true)
                {
                    headers["__RequestUri"] = strObjectUri;
                    msgReq.Properties["__RequestHeaders"] = headers;
                }
                #endregion

                #region send a remoting message
                // set the destination queue
                m_OutQueue.Path = strQueuePath;

                // create a message
                outMsg = new Message(msgReq, new BinaryMessageFormatter());

                // option: timeout to pick-up a message (receive message)
                int intTimeToBeReceived = m_Sender.TimeToBeReceived;
                if (intTimeToBeReceived > 0)
                {
                    outMsg.TimeToBeReceived = TimeSpan.FromSeconds(intTimeToBeReceived);
                }

                // option: timeout to reach destination queue (send message)
                int intTimeToReachQueue = m_Sender.TimeToReachQueue;
                if (intTimeToReachQueue > 0)
                {
                    outMsg.TimeToReachQueue = TimeSpan.FromSeconds(intTimeToReachQueue);
                }

                // option: notify a negative receive on the client/server side
                if (m_Sender.AdminQueuePath != MSMQChannelDefaults.EmptyStr)
                {
                    // acknowledge type (mandatory)
                    outMsg.AcknowledgeType = AcknowledgeTypes.NegativeReceive | AcknowledgeTypes.NotAcknowledgeReachQueue;

                    // admin queue for a time-expired messages
                    outMsg.AdministrationQueue = m_Sender.AdminQueue;
                }

                // message label
                string label = string.Format("{0}/{1}, url={2}", Convert.ToString(msgReq.Properties["__TypeName"]).Split(',')[0],
                                             Convert.ToString(msgReq.Properties["__MethodName"]), strObjectUri);

                //// Send message based on the transaction context
                //if(ContextUtil.IsInTransaction == true)
                //{
                //    // we are already in the transaction - automatic (DTC) transactional message
                //    m_OutQueue.Send(outMsg, label, MessageQueueTransactionType.Automatic);
                //}
                //else
                //{
                // this is a single transactional message
                mqtx.Begin();
                m_OutQueue.Send(outMsg, label, mqtx);
                mqtx.Commit();
                //}
                #endregion
            }
            catch (Exception ex)
            {
                string strError = string.Format("[{0}]MSMQClientTransportSink.AsyncProcessRequest error = {1}, queuepath={2},",
                                                m_Sender.ChannelName, ex.Message, strQueuePath);

                m_Sender.WriteLogMsg(strError, EventLogEntryType.Error);
                throw new Exception(strError);
            }
            finally
            {
                #region clean-up
                if (mqtx.Status == MessageQueueTransactionStatus.Pending)
                {
                    mqtx.Abort();
                    Trace.WriteLine(string.Format("[{0}]MSMQClientTransportSink.AsyncProcessRequest Aborted, msgId = {1}", m_Sender.ChannelName, outMsg.Id));
                }

                if (outMsg != null)
                {
                    outMsg.Dispose();
                }
                #endregion
            }
        }
 public void AsyncProcessResponse(
     IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers, Stream stream)
 {
     throw new RemotingException("AsyncProcessRequest is not enabled yet");
 }
示例#47
0
 public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
                                 ITransportHeaders headers, Stream stream1)
 {
     sinkStack.Push(this, null);
     nextSink1.AsyncProcessRequest(sinkStack, msg, headers, stream1);
 }
 public Stream GetRequestStream(IMessage msg,
                                ITransportHeaders headers)
 {
     return(_nextSink.GetRequestStream(msg, headers));
 }
 public Stream GetResponseStream(
     IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers)
 {
     //not implemented, since only formatter sink need to call this method
     return(null);
 }