public AutoCloseDuplexSessionChannel(IDuplexSessionChannel innerChannel) { this.innerChannel = innerChannel; pendingMessages = new InputQueue <Message>(); messageDequeuedCallback = new Action(StartBackgroundReceive); // kick off a new receive when a message is picked up closeState = new CloseState(); }
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); }
/// <summary> /// Try to begin receive messages /// </summary> /// <param name="ccs">indicating the channel and the client</param> /// <returns>if the operation completed synchronously</returns> protected override bool TryToBeginReceive(ChannelClientState ccs) { IDuplexSessionChannel channel = (IDuplexSessionChannel)ccs.Channel; BrokerClient client = ccs.Client; IAsyncResult ar = null; try { ar = channel.BeginReceive(this.receiveRequest, ccs); } catch (Exception e) { BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Exception throwed while begin receive messages: {0}", e); // Channel must be in falted state lock (channel) { if (channel.State == CommunicationState.Faulted) { BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] About the channel."); this.FrontendDisconnect(channel, client); // About the falted channel channel.Abort(); } } return(false); } return(ar.CompletedSynchronously && channel.State == CommunicationState.Opened); }
protected override TChannel OnAcceptChannel(TimeSpan timeout) { this.Print("OnAcceptChannel()"); IDuplexSessionChannel innerChannel = (IDuplexSessionChannel)this.InnerChannelListener.AcceptChannel(timeout); return(new SimpleDuplexSessionChannel(this, innerChannel) as TChannel); }
public AutoCloseDuplexSessionChannel(IDuplexSessionChannel innerChannel) { this.innerChannel = innerChannel; this.pendingMessages = new InputQueue <Message>(); this.messageDequeuedCallback = new Action(this.StartBackgroundReceive); this.closeState = new CloseState(); }
protected override TChannel OnCreateChannel(EndpointAddress address, Uri via) { IDuplexSessionChannel innerChannel = this.InnerChannelFactory.CreateChannel(address, via) as IDuplexSessionChannel; return((TChannel)(object)new SimpleDuplexSessionChannel(this, innerChannel)); }
bool CompleteAccept(IAsyncResult result) { Socket dataSocket = listener.listenSocket.EndAccept(result); channel = new ServerTcpDuplexSessionChannel(this.listener.encoderFactory, this.listener.bufferManager, dataSocket, new EndpointAddress(this.listener.uri), this.listener); return(true); }
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(); }
IDuplexSessionChannel GetChannelFromPool(ref TimeoutHelper timeoutHelper, out ChannelPoolKey key, out bool isConnectionFromPool) { isConnectionFromPool = true; while (true) { IDuplexSessionChannel pooledChannel = this.channelPool.TakeConnection(this.RemoteAddress, this.Via, timeoutHelper.RemainingTime(), out key); if (pooledChannel == null) { isConnectionFromPool = false; return(this.innerFactory.CreateChannel(RemoteAddress, Via)); } // only return good connections if (pooledChannel.State == CommunicationState.Opened) { return(pooledChannel); } // Abort stale connections from the pool this.channelPool.ReturnConnection(key, pooledChannel, false, timeoutHelper.RemainingTime()); } }
public SendAsyncResult(DuplexSessionOneWayChannelFactory.DuplexSessionOutputChannel parent, Message message, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.parent = parent; this.message = message; this.timeoutHelper = new TimeoutHelper(timeout); this.innerChannel = parent.GetChannelFromPool(ref this.timeoutHelper, out this.key, out this.isConnectionFromPool); bool flag = false; bool flag2 = true; try { if (!this.isConnectionFromPool) { flag2 = this.OpenNewChannel(); } if (flag2) { flag2 = this.SendMessage(); } flag = true; } finally { if (!flag) { this.Cleanup(false); } } if (flag2) { this.Cleanup(true); base.Complete(true); } }
protected override IRequestSessionChannel OnCreateChannel(EndpointAddress address, Uri via) { IDuplexSessionChannel duplexSessionChannel = this.innerFactory.CreateChannel(address, via); MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelCreated(duplexSessionChannel.GetType().Name, duplexSessionChannel.LocalAddress.Uri.AbsoluteUri, duplexSessionChannel.RemoteAddress.Uri.AbsoluteUri, duplexSessionChannel.Via.AbsoluteUri, duplexSessionChannel.Session.Id)); return(new DuplexRequestBindingElement.DuplexRequestSessionChannel(this, duplexSessionChannel)); }
protected override void OnSend(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ChannelPoolKey key = null; bool isConnectionFromPool = true; IDuplexSessionChannel innerChannel = GetChannelFromPool(ref timeoutHelper, out key, out isConnectionFromPool); bool success = false; try { if (!isConnectionFromPool) { StampInitialMessage(message); innerChannel.Open(timeoutHelper.RemainingTime()); StartBackgroundReceive(innerChannel); } innerChannel.Send(message, timeoutHelper.RemainingTime()); success = true; } finally { if (!success) { CleanupChannel(innerChannel, false, key, isConnectionFromPool, ref timeoutHelper); } } CleanupChannel(innerChannel, true, key, isConnectionFromPool, ref timeoutHelper); }
protected override TChannel OnAcceptChannel(TimeSpan timeout) { PrintHelper.Print(this, "OnAcceptChannel"); IDuplexSessionChannel innerChannel = this._channelListener.AcceptChannel(timeout) as IDuplexSessionChannel; return(new SimpleDuplexSessionChannel(this, innerChannel) as TChannel); }
protected override void SendReply(Message reply, IDuplexSessionChannel channel, Message item) { if (FaultHelper.AddressReply(item, reply)) { channel.Send(reply); } }
internal ChunkingDuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel, ICollection <string> operationParams, int maxBufferedChunks) : base(channelManager) { this.Initialize(channelManager, innerChannel, operationParams, maxBufferedChunks); }
protected override void OnSend(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ChannelPoolKey key = null; bool isConnectionFromPool = true; IDuplexSessionChannel channel = this.GetChannelFromPool(ref timeoutHelper, out key, out isConnectionFromPool); bool flag2 = false; try { if (!isConnectionFromPool) { this.StampInitialMessage(message); channel.Open(timeoutHelper.RemainingTime()); this.StartBackgroundReceive(channel); } channel.Send(message, timeoutHelper.RemainingTime()); flag2 = true; } finally { if (!flag2) { this.CleanupChannel(channel, false, key, isConnectionFromPool, ref timeoutHelper); } } this.CleanupChannel(channel, true, key, isConnectionFromPool, ref timeoutHelper); }
public ChannelReceiver(DuplexSessionOneWayChannelListener parent, IDuplexSessionChannel channel) { this.channel = channel; this.acceptor = parent.inputChannelAcceptor; this.idleTimeout = parent.idleTimeout; this.validateHeader = parent.packetRoutable; this.onMessageDequeued = new Action(this.OnMessageDequeued); }
private void OnOpenInnerChannel(IAsyncResult result) { if (!result.CompletedSynchronously) { IDuplexSessionChannel asyncState = (IDuplexSessionChannel)result.AsyncState; this.CompleteOpen(asyncState, result); } }
private void StartBackgroundReceive(IDuplexSessionChannel channel) { if (this.onReceive == null) { this.onReceive = Fx.ThunkCallback(new AsyncCallback(this.OnReceive)); } channel.BeginReceive(TimeSpan.MaxValue, this.onReceive, channel); }
public async Task OpenAsync() { await OpenAsync(this.factory); this.channel = this.factory.CreateChannel(new EndpointAddress("net.pipe://localhost/" + this.name)); await OpenAsync(this.channel); }
void Initialize(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel, ICollection <string> operationParams, int maxBufferedChunks) { this.innerChannel = innerChannel; this.operationParams = operationParams; this.maxBufferedChunks = maxBufferedChunks; }
public IDuplexChannel GetNextChannel() { lock (ThisLock) { IDuplexSessionChannel channel = channel = _channels.Dequeue(); _channels.Enqueue(channel); return(channel); } }
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 async Task CloseAsync() { if (this.channel != null) { await CloseAsync(this.channel); this.channel = null; } await CloseAsync(this.factory); }
public UnreliableNetworkSimulateChannel(IDuplexSessionChannel innerChannel, int dropRate) { if (null == innerChannel) { throw new ArgumentNullException("innerChannel"); } this.InnerChannel = innerChannel; this.MessageInspector = new MessageInspector(dropRate); }
private bool ChannelSupportsOneCreateSequenceAttempt() { IDuplexSessionChannel channel = this.binder.Channel as IDuplexSessionChannel; if (channel == null) { return(false); } return((channel.Session is ISecuritySession) && !(channel.Session is ISecureConversationSession)); }
public IChannelBinder Accept(TimeSpan timeout) { IDuplexSessionChannel channel = this.listener.AcceptChannel(timeout); if (channel == null) { return(null); } return(new DuplexChannelBinder(channel, this.correlator, this.listener.Uri)); }
public IChannelBinder EndAccept(IAsyncResult result) { IDuplexSessionChannel channel = this.listener.EndAcceptChannel(result); if (channel == null) { return(null); } return(new DuplexChannelBinder(channel, this.correlator, this.listener.Uri)); }
public void Complete(IDuplexSessionChannel channel) { logger.Info("Complete()"); // set the channel before complete this.channel = channel; // the websocket server accpet only support async operation this.Complete(false); }
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 static void IDuplexSessionChannel_Async_Tcp_NetTcpBinding() { IChannelFactory <IDuplexSessionChannel> factory = null; IDuplexSessionChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); // Create the channel factory factory = binding.BuildChannelFactory <IDuplexSessionChannel>(new BindingParameterCollection()); Task.Factory.FromAsync(factory.BeginOpen, factory.EndOpen, TaskCreationOptions.None).GetAwaiter().GetResult(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.Tcp_NoSecurity_Address)); Task.Factory.FromAsync(channel.BeginOpen, channel.EndOpen, TaskCreationOptions.None).GetAwaiter().GetResult(); // 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. Task.Factory.FromAsync((asyncCallback, o) => channel.BeginSend(requestMessage, asyncCallback, o), channel.EndSend, TaskCreationOptions.None).GetAwaiter().GetResult(); replyMessage = Task.Factory.FromAsync(channel.BeginReceive, channel.EndReceive, TaskCreationOptions.None).GetAwaiter().GetResult(); // *** 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(); Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, TaskCreationOptions.None).GetAwaiter().GetResult(); Task.Factory.FromAsync(factory.BeginClose, factory.EndClose, TaskCreationOptions.None).GetAwaiter().GetResult(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
public void Close() { if (controlChannel != null) { controlChannel.Close(); controlChannel = null; } if (channelFactory != null) { channelFactory.Close(); channelFactory = null; } }
public DuplexSessionDemuxFailureAsyncResult(IChannelDemuxFailureHandler demuxFailureHandler, IDuplexSessionChannel channel, Message message, AsyncCallback callback, object state) : base(callback, state) { if (demuxFailureHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("demuxFailureHandler"); } if (channel == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel"); } this.demuxFailureHandler = demuxFailureHandler; this.channel = channel; this.message = message; }
public DurableInstanceContextDuplexSessionChannel( ChannelManagerBase channelManager, ContextType contextType, IDuplexSessionChannel innerChannel, string contextStoreLocation) : base(channelManager, innerChannel) { this.innerDuplexSessionChannel = innerChannel; this.contextType = contextType; this.contextStoreLocation = contextStoreLocation; this.endpointAddress = innerDuplexSessionChannel.RemoteAddress; this.isFirstOutgoingMessage = true; this.isFirstIncomingMessage = true; this.outputStateLock = new object(); this.inputStateLock = new object(); }
public void Open() { // FUTURE: For security purpose, we need to set the right ACL to the Named-Pipe. Unfortunately // this is not supported in current WCF API. NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); binding.MaxReceivedMessageSize = MaxControlReceivedMessageSize; binding.ReaderQuotas.MaxArrayLength = MaxControlReceivedMessageSize; channelFactory = new DuplexChannelFactory<IUdpControlRegistration>( new InstanceContext(null, this), binding, new EndpointAddress(HostedUdpConstants.ControlServiceAddress)); IUdpControlRegistration controlRegistration = channelFactory.CreateChannel(); controlChannel = controlRegistration as IDuplexSessionChannel; ControlRegistrationData data = new ControlRegistrationData(); data.Uri = uri; data.InstanceId = instanceId; controlRegistration.Register(data); }
public SimpleDuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel) : base(channelManager, (ChannelBase)innerChannel) { this.Print("SimpleDuplexSessionChannel()"); }
public RelayConnection(IDuplexSessionChannel channel) { this.channel = channel; this.WriteTimeout = this.ReadTimeout = 60*1000; // 60s default }