private static NetworkDetector.ConnectivityStatus CheckTcpConnectivity(Uri baseAddress, out Exception exception) { NetworkDetector.ConnectivityStatus connectivityStatu = NetworkDetector.ConnectivityStatus.Unavailable; exception = null; if (!RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTP", false) && !RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTPS", false)) { try { BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement(); TcpTransportBindingElement tcpTransportBindingElement = new TcpTransportBindingElement(); tcpTransportBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100; tcpTransportBindingElement.MaxReceivedMessageSize = (long)65536; CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(binaryMessageEncodingBindingElement); customBinding.Elements.Add(tcpTransportBindingElement); customBinding.OpenTimeout = TimeSpan.FromSeconds(10); customBinding.SendTimeout = TimeSpan.FromSeconds(10); customBinding.ReceiveTimeout = TimeSpan.MaxValue; int num = 9350; Uri uri = ServiceBusUriHelper.CreateServiceUri("net.tcp", string.Concat(baseAddress.DnsSafeHost, ":", num.ToString(CultureInfo.InvariantCulture)), "/"); IChannelFactory <IDuplexSessionChannel> channelFactory = null; IDuplexSessionChannel duplexSessionChannel = null; try { channelFactory = customBinding.BuildChannelFactory <IDuplexSessionChannel>(new object[0]); channelFactory.Open(); duplexSessionChannel = channelFactory.CreateChannel(new EndpointAddress(uri, new AddressHeader[0])); duplexSessionChannel.Open(); Message message = Message.CreateMessage(MessageVersion.Default, "http://schemas.microsoft.com/netservices/2009/05/servicebus/connect/OnewayPing", new OnewayPingMessage()); duplexSessionChannel.Send(message, customBinding.SendTimeout); duplexSessionChannel.Close(); duplexSessionChannel = null; channelFactory.Close(); channelFactory = null; } finally { if (duplexSessionChannel != null) { duplexSessionChannel.Abort(); } if (channelFactory != null) { channelFactory.Abort(); } } connectivityStatu = NetworkDetector.ConnectivityStatus.Available; } catch (CommunicationException communicationException) { exception = communicationException; } catch (TimeoutException timeoutException) { exception = timeoutException; } } NetworkDetector.LogResult(baseAddress, "Tcp", connectivityStatu); return(connectivityStatu); }
void RunTest() { listener.Open(); Thread thread = new Thread(ServerThread); thread.Start(this); CustomBinding binding = new CustomBinding(new WseTcpTransportBindingElement()); IChannelFactory <IDuplexSessionChannel> channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>(); channelFactory.Open(); IDuplexSessionChannel channel = channelFactory.CreateChannel(new EndpointAddress(this.uri)); Message requestMessage; channel.Open(); requestMessage = Message.CreateMessage(binding.MessageVersion, "http://SayHello", "to you."); channel.Send(requestMessage); Message hello = channel.Receive(); using (hello) { Console.WriteLine(hello.GetBody <string>()); } Console.WriteLine("Press enter."); Console.ReadLine(); requestMessage = Message.CreateMessage(binding.MessageVersion, "http://NotHello", "to me."); channel.Send(requestMessage); channel.Close(); thread.Join(); channelFactory.Close(); listener.Close(); Console.WriteLine("Press enter."); Console.ReadLine(); }
internal static void CloseDuplexSessionChannel(ReliableChannelBinder <IDuplexSessionChannel> binder, IDuplexSessionChannel channel, TimeSpan timeout) { Message message; TimeoutHelper helper = new TimeoutHelper(timeout); channel.Session.CloseOutputSession(helper.RemainingTime()); binder.WaitForPendingOperations(helper.RemainingTime()); TimeSpan span = helper.RemainingTime(); bool flag = span == TimeSpan.Zero; Label_003B: message = null; bool flag2 = true; try { bool flag3 = channel.TryReceive(span, out message); flag2 = false; if (flag3 && (message == null)) { channel.Close(helper.RemainingTime()); return; } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } if (!flag2) { throw; } if (!MaskHandled(binder.DefaultMaskingMode) || !binder.IsHandleable(exception)) { throw; } flag2 = false; } finally { if (message != null) { message.Close(); } if (flag2) { channel.Abort(); } } if (!flag && (channel.State == CommunicationState.Opened)) { span = helper.RemainingTime(); flag = span == TimeSpan.Zero; goto Label_003B; } channel.Abort(); }
public static void IDuplexSessionChannel_Tcp_NetTcpBinding() { StringBuilder errorBuilder = new StringBuilder(); try { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); // Create the channel factory IChannelFactory <IDuplexSessionChannel> factory = binding.BuildChannelFactory <IDuplexSessionChannel>( new BindingParameterCollection()); factory.Open(); // Create the channel. IDuplexSessionChannel channel = factory.CreateChannel( new EndpointAddress(Endpoints.Tcp_NoSecurity_Address)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); requestMessage.Headers.MessageId = new UniqueId(Guid.NewGuid()); // Send the Message and receive the Response. channel.Send(requestMessage); Message replyMessage = channel.Receive(TimeSpan.FromSeconds(5)); // If the incoming Message did not contain the same UniqueId used for the MessageId of the outgoing Message we would have received a Fault from the Service if (!String.Equals(replyMessage.Headers.RelatesTo.ToString(), requestMessage.Headers.MessageId.ToString())) { errorBuilder.AppendLine(String.Format("The MessageId of the incoming Message does not match the MessageId of the outgoing Message, expected: {0} but got: {1}", requestMessage.Headers.MessageId, replyMessage.Headers.RelatesTo)); } // Validate the Response var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: CustomBindingTest FAILED with the following errors: {0}", errorBuilder)); }
public static void IDuplexSessionChannel_Https_NetHttpsBinding() { IChannelFactory <IDuplexSessionChannel> factory = null; IDuplexSessionChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ NetHttpsBinding binding = new NetHttpsBinding(BasicHttpsSecurityMode.Transport); // Create the channel factory factory = binding.BuildChannelFactory <IDuplexSessionChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_NetHttpsWebSockets)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); requestMessage.Headers.MessageId = new UniqueId(Guid.NewGuid()); // *** EXECUTE *** \\ // Send the Message and receive the Response. channel.Send(requestMessage); replyMessage = channel.Receive(TimeSpan.FromSeconds(5)); // *** VALIDATE *** \\ // If the incoming Message did not contain the same UniqueId used for the MessageId of the outgoing Message we would have received a Fault from the Service string expectedMessageID = requestMessage.Headers.MessageId.ToString(); string actualMessageID = replyMessage.Headers.RelatesTo.ToString(); Assert.True(String.Equals(expectedMessageID, actualMessageID), String.Format("Expected Message ID was {0}. Actual was {1}", expectedMessageID, actualMessageID)); // Validate the Response var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Session.CloseOutputSession(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
public void Close() { if (controlChannel != null) { controlChannel.Close(); controlChannel = null; } if (channelFactory != null) { channelFactory.Close(); channelFactory = null; } }
protected override void OnClose(TimeSpan timeout) { //wait for receive to stop so we can have a clean shutdown TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (this.receiveStopped.WaitOne(TimeoutHelper.ToMilliseconds(timeoutHelper.RemainingTime()), false)) { innerChannel.Close(timeoutHelper.RemainingTime()); } else { throw new TimeoutException("Close timeout exceeded"); } //we don't call base.OnClose because it does nothing }
public static void Main() { CustomBinding binding = new CustomBinding(); binding.Elements.Add(new TextMessageEncodingBindingElement()); binding.Elements.Add(new TcpTransportBindingElement()); BindingParameterCollection bpcol = new BindingParameterCollection(); // using (IChannelListener<IDuplexSessionChannel> listener = // binding.BuildChannelListener<IDuplexSessionChannel> ( // new Uri ("net.tcp://localhost/Server"), bpcol)) // { IChannelListener <IDuplexSessionChannel> listener = binding.BuildChannelListener <IDuplexSessionChannel> ( new Uri("net.tcp://localhost/"), bpcol); listener.Open(); IDuplexSessionChannel channel = listener.AcceptChannel(); Console.WriteLine("Listening for messages..."); channel.Open(); Message message = channel.Receive(); Console.WriteLine("Message received."); Console.WriteLine("Message action: {0}", message.Headers.Action); Console.WriteLine("Message content: {0}", message.GetBody <string> ()); message = Message.CreateMessage( //channel.Manager.MessageVersion, MessageVersion.Default, "Action", "Hello, World, from service side"); channel.Send(message); message.Close(); channel.Close(); listener.Close(); // } }
public static void Main() { Console.WriteLine("Press ENTER when service is ready."); Console.ReadLine(); CustomBinding binding = new CustomBinding(); binding.Elements.Add(new TextMessageEncodingBindingElement()); binding.Elements.Add(new TcpTransportBindingElement()); BindingParameterCollection bpcol = new BindingParameterCollection(); // using (IChannelFactory<IDuplexSessionChannel> factory = // binding.BuildChannelFactory<IDuplexSessionChannel>(bpcol)) // { IChannelFactory <IDuplexSessionChannel> factory = binding.BuildChannelFactory <IDuplexSessionChannel> (bpcol); factory.Open(); IDuplexSessionChannel channel = factory.CreateChannel( new EndpointAddress("net.tcp://localhost/")); channel.Open(); Message message = Message.CreateMessage( //channel.Manager.MessageVersion, MessageVersion.Default, "Action", "Hello, World, from client side"); channel.Send(message); message = channel.Receive(); Console.WriteLine("Message received."); Console.WriteLine("Message action: {0}", message.Headers.Action); Console.WriteLine("Message content: {0}", message.GetBody <string> ()); message.Close(); channel.Close(); factory.Close(); // } }
private void OnReceive(IAsyncResult result) { IDuplexSessionChannel asyncState = (IDuplexSessionChannel)result.AsyncState; bool flag = false; try { Message message = asyncState.EndReceive(result); if (message == null) { asyncState.Close(this.channelPool.IdleTimeout); flag = true; } else { message.Close(); } } catch (CommunicationException exception) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } } catch (TimeoutException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } finally { if (!flag) { asyncState.Abort(); } } }
void OnReceive(IAsyncResult result) { IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState; bool success = false; try { Message message = channel.EndReceive(result); if (message == null) { channel.Close(this.channelPool.IdleTimeout); success = true; } else { message.Close(); } } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } finally { if (!success) { channel.Abort(); } } }
void RunServer() { IDuplexSessionChannel channel = listener.AcceptChannel(TimeSpan.MaxValue); channel.Open(); Message message; while ((message = channel.Receive(TimeSpan.MaxValue)) != null) { string action = message.Headers.Action; string body = message.GetBody <string>(); Console.WriteLine("Received Action: " + action); Console.WriteLine("Received Body: " + body); if (action == "http://SayHello") { Message helloMessage = Message.CreateMessage(message.Version, "http://Hello", "Hello " + body); channel.Send(helloMessage); } message.Close(); } channel.Close(); }
public static void IDuplexSessionChannel_Http_BasicHttpBinding() { #if FULLXUNIT_NOTSUPPORTED bool root_Certificate_Installed = Root_Certificate_Installed(); if (!root_Certificate_Installed) { Console.WriteLine("---- Test SKIPPED --------------"); Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE."); Console.WriteLine("Root_Certificate_Installed evaluated as {0}", root_Certificate_Installed); return; } #endif IChannelFactory <IDuplexSessionChannel> factory = null; IDuplexSessionChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(); // Create the channel factory factory = binding.BuildChannelFactory <IDuplexSessionChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_NetHttps)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); requestMessage.Headers.MessageId = new UniqueId(Guid.NewGuid()); // *** EXECUTE *** \\ // Send the Message and receive the Response. channel.Send(requestMessage); replyMessage = channel.Receive(TimeSpan.FromSeconds(5)); // *** VALIDATE *** \\ // If the incoming Message did not contain the same UniqueId used for the MessageId of the outgoing Message we would have received a Fault from the Service Assert.Equal(requestMessage.Headers.MessageId.ToString(), replyMessage.Headers.RelatesTo.ToString()); // Validate the Response var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
internal static void CloseDuplexSessionChannel(ReliableChannelBinder <IDuplexSessionChannel> binder, IDuplexSessionChannel channel, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); channel.Session.CloseOutputSession(timeoutHelper.RemainingTime()); binder.WaitForPendingOperations(timeoutHelper.RemainingTime()); TimeSpan timeout1 = timeoutHelper.RemainingTime(); bool flag1 = timeout1 == TimeSpan.Zero; while (true) { Message message = (Message)null; bool flag2 = true; try { bool flag3 = channel.TryReceive(timeout1, out message); flag2 = false; if (flag3) { if (message == null) { channel.Close(timeoutHelper.RemainingTime()); return; } } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } else if (flag2) { if (!ReliableChannelBinderHelper.MaskHandled(binder.DefaultMaskingMode) || !binder.IsHandleable(ex)) { throw; } else { flag2 = false; } } else { throw; } } finally { if (message != null) { message.Close(); } if (flag2) { channel.Abort(); } } if (!flag1 && channel.State == CommunicationState.Opened) { timeout1 = timeoutHelper.RemainingTime(); flag1 = timeout1 == TimeSpan.Zero; } else { break; } } channel.Abort(); }
/// <summary> /// AsyncCallback for ReceiveRequest /// </summary> /// <param name="ar">async result</param> private void ReceiveRequest(IAsyncResult ar) { ChannelClientState state = (ChannelClientState)ar.AsyncState; IDuplexSessionChannel channel = (IDuplexSessionChannel)state.Channel; BrokerClient client = state.Client; Message requestMessage; try { requestMessage = channel.EndReceive(ar); } catch (Exception ce) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception while receiving requests: {0}", ce); this.FrontendDisconnect(channel, client); lock (channel) { if (channel.State == CommunicationState.Faulted) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Abort faulted channel."); channel.Abort(); return; } } // Retry receiving requests if (!ar.CompletedSynchronously) { this.TryToBeginReceiveMessagesWithThrottling(state); } return; } #region Debug Failure Test SimulateFailure.FailOperation(1); #endregion // After channel timeout, the request will be null if you call channel.Receive() // Need to end the channel at this time if (requestMessage == null) { // Indicate that the channel should be closed // Close the channel lock (channel) { if (channel.State == CommunicationState.Opened) { this.FrontendDisconnect(channel, client); try { channel.Close(); BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Channel closed"); } catch (Exception ce) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception throwed while close the channel: {0}", ce); channel.Abort(); } } } return; } // Try to get the client id string callerSID; string userName = this.GetUserName(requestMessage, out callerSID); string clientId = GetClientId(requestMessage, callerSID); try { ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong); ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId); } catch (ArgumentException) { BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdInvalid(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage)); RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer); requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_InvalidClientIdOrTooLong, SR.InvalidClientIdOrTooLong), this.ReplySentCallback, requestContextToReject); return; } if (client == null) { if (!this.TryGetClientByChannel(channel, clientId, userName, requestMessage, out client)) { return; } state.Client = client; } // Receive new requests if (!ar.CompletedSynchronously) { this.TryToBeginReceiveMessagesWithThrottling(state); } // Reject if client id does not match if (String.Compare(clientId, client.ClientId, StringComparison.OrdinalIgnoreCase) != 0) { BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdNotMatch(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage)); RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer); requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_ClientIdNotMatch, SR.ClientIdNotMatch), this.ReplySentCallback, requestContextToReject); return; } // Try to get the user info header bool userDataFlag = GetUserInfoHeader(requestMessage); // Create request context RequestContextBase requestContext; if (userDataFlag) { // Message that needs not to reply requestContext = DummyRequestContext.GetInstance(requestMessage.Version); } else { requestContext = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer, client); } // Check auth if (!this.CheckAuth(requestContext, requestMessage)) { return; } // remove security header for websocket TryRemoveSecurityHeaderForHttps(requestMessage); // Send the request to the broker client Task.Run(() => client.RequestReceived(requestContext, requestMessage, null)); }