internal static bool IsConcurrent(ChannelDispatcher runtime, bool hasSession)
        {
            bool isConcurrencyModeSingle = true;

            if (ConcurrencyBehavior.SupportsTransactedBatch(runtime))
            {
                return false;
            }

            foreach (EndpointDispatcher endpointDispatcher in runtime.Endpoints)
            {
                if (endpointDispatcher.DispatchRuntime.EnsureOrderedDispatch)
                {
                    return false;
                }

                if (endpointDispatcher.DispatchRuntime.ConcurrencyMode != ConcurrencyMode.Single)
                {
                    isConcurrencyModeSingle = false;
                }
            }

            if (!isConcurrencyModeSingle)
            {
                return true;
            }

            if (!hasSession)
            {
                return true;
            }

            return false;
        }
        private static void CreateHttpGetChannelDispatcher(ServiceHostBase host, Uri listenUri, MetadataSet metadata)
        {
            //创建Binding
            TextMessageEncodingBindingElement messageEncodingElement = new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.None };
            HttpTransportBindingElement transportElement = new HttpTransportBindingElement();
            Utility.SetPropertyValue(transportElement, "Method", "GET");
            Binding binding = new CustomBinding(messageEncodingElement, transportElement);

            //创建ChannelListener
            IChannelListener listener = binding.BuildChannelListener<IReplyChannel>(listenUri, string.Empty, ListenUriMode.Explicit, new BindingParameterCollection());
            ChannelDispatcher dispatcher = new ChannelDispatcher(listener, "ServiceMetadataBehaviorHttpGetBinding", binding) { MessageVersion = binding.MessageVersion };

            //创建EndpointDispatcher
            EndpointDispatcher endpoint = new EndpointDispatcher(new EndpointAddress(listenUri), "IHttpGetMetadata", "http://www.artech.com/");

            //创建DispatchOperation,并设置DispatchMessageFormatter和OperationInvoker
            DispatchOperation operation = new DispatchOperation(endpoint.DispatchRuntime, "Get", "*", "*");
            operation.Formatter = Utility.CreateInstance<IDispatchMessageFormatter>(MessageOperationFormatterType, Type.EmptyTypes, new object[0]);
            MethodInfo method = typeof(IHttpGetMetadata).GetMethod("Get");
            operation.Invoker = Utility.CreateInstance<IOperationInvoker>(SyncMethodInvokerType, new Type[] { typeof(MethodInfo) }, new object[] { method });
            endpoint.DispatchRuntime.Operations.Add(operation);

            //设置SingletonInstanceContext和InstanceContextProvider
            MetadataProvisionService serviceInstance = new MetadataProvisionService(metadata);
            endpoint.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, serviceInstance);
            endpoint.DispatchRuntime.InstanceContextProvider = Utility.CreateInstance<IInstanceContextProvider>(SingletonInstanceContextProviderType, new Type[] { typeof(DispatchRuntime) }, new object[] { endpoint.DispatchRuntime });
            dispatcher.Endpoints.Add(endpoint);

            //设置ContractFilter和AddressFilter
            endpoint.ContractFilter = new MatchAllMessageFilter();
            endpoint.AddressFilter = new MatchAllMessageFilter();

            host.ChannelDispatchers.Add(dispatcher);
        }
        internal ListenerHandler(IListenerBinder listenerBinder, ChannelDispatcher channelDispatcher, ServiceHostBase host, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts)
        {
            this.listenerBinder = listenerBinder;
            if (!((this.listenerBinder != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.listenerBinder != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listenerBinder");
            }

            this.channelDispatcher = channelDispatcher;
            if (!((this.channelDispatcher != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.channelDispatcher != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            this.host = host;
            if (!((this.host != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.host != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("host");
            }

            this.throttle = throttle;
            if (!((this.throttle != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.throttle != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("throttle");
            }

            this.timeouts = timeouts;

            this.endpoints = channelDispatcher.EndpointDispatcherTable;
            this.acceptor = new ErrorHandlingAcceptor(listenerBinder, channelDispatcher);
        }
		protected void UnregisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
		{
			var entry = Entries.First (e => e.ChannelDispatcher == channel);
			Entries.Remove (entry);

			entry.WaitHandle.Set (); // make sure to finish pending requests.
		}
		public HttpChannelListenerEntry (ChannelDispatcher channel, EventWaitHandle waitHandle)
		{
			ChannelDispatcher = channel;
			WaitHandle = waitHandle;
			ContextQueue = new Queue<HttpContextInfo> ();
			RetrieverLock = new object ();
		}
        public bool Handle(Exception exception, ChannelDispatcher dispatcher, WCFServiceController wcfServiceController)
        {
            if (this.pendingRestart)
            {
                return false;
            }

            if (!(exception is CommunicationException))
            {
                AcceptedErrorLimitation.Add(exception);
                if (AcceptedErrorLimitation.ExceedLimit())
                {
                    AutoRestartLimitation.Add(exception);
                    if (AutoRestartLimitation.ExceedLimit())
                    {
                        _logger.LogWarning("Unable solve exception with configured max-times of WCF Service restart." +
                                           string.Format(
                                               "WCF Servuce {0}, Times of Auto-Restart has exceed the max value within configued time range, waiting window service restart",
                                               wcfServiceController.ServiceName));
                        this.pendingRestart = true;
                        return false;
                    }
                    else
                    {
                        AcceptedErrorLimitation.ResetCount();
                        return Handle(wcfServiceController);
                    }
                }
            }

            return true;
        }
 internal ErrorBehavior(ChannelDispatcher channelDispatcher)
 {
     this.handlers = EmptyArray<IErrorHandler>.ToArray(channelDispatcher.ErrorHandlers);
     this.debug = channelDispatcher.IncludeExceptionDetailInFaults;
     this.isOnServer = channelDispatcher.IsOnServer;
     this.messageVersion = channelDispatcher.MessageVersion;
 }
 private void SetIsolationLevel(ChannelDispatcher channelDispatcher)
 {
     if (channelDispatcher == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
     }
     channelDispatcher.TransactionIsolationLevel = this.transactionIsolationLevel;
 }
		protected void RegisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
		{
			lock (entries_lock) {
				Entries.Add (new HttpChannelListenerEntry (channel, new AutoResetEvent (false)));

				Entries.Sort (HttpChannelListenerEntry.CompareEntries);
			}
		}
Exemple #10
0
 internal DispatchRuntime(ClientRuntime proxyRuntime, SharedRuntimeState shared)
     : this(shared)
 {
     ClientRuntime            = proxyRuntime ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(proxyRuntime));
     _instanceProvider        = new CallbackInstanceProvider();
     _channelDispatcher       = new ChannelDispatcher(shared);
     _instanceContextProvider = InstanceContextProviderBase.GetProviderForMode(InstanceContextMode.PerSession, this);
     Fx.Assert(!shared.IsOnServer, "Client constructor called on server?");
 }
Exemple #11
0
            public Task <object> InvokeAsync(object instance, object[] inputs, out object[] outputs)
            {
                outputs = EmptyArray <object> .Allocate(0);

                Message message = inputs[0] as Message;

                if (message == null)
                {
                    return(null);
                }

                string action = message.Headers.Action;

                FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
                                                                 message.Version.Addressing.Namespace);
                string      reasonText = SR.Format(SR.SFxNoEndpointMatchingContract, action);
                FaultReason reason     = new FaultReason(reasonText);

                FaultException exception = new FaultException(reason, code);

                ErrorBehavior.ThrowAndCatch(exception);

                ServiceChannel serviceChannel = OperationContext.Current.InternalServiceChannel;

                OperationContext.Current.OperationCompleted +=
                    delegate(object sender, EventArgs e)
                {
                    ChannelDispatcher channelDispatcher = _dispatchRuntime.ChannelDispatcher;
                    if (!channelDispatcher.HandleError(exception) && serviceChannel.HasSession)
                    {
                        try
                        {
                            serviceChannel.Close(ChannelHandler.CloseAfterFaultTimeout);
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            channelDispatcher.HandleError(ex);
                        }
                    }
                };

                if (_dispatchRuntime._shared.EnableFaults)
                {
                    MessageFault fault = MessageFault.CreateFault(code, reason, action);
                    return(Task.FromResult((object)Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultFaultAction)));
                }
                else
                {
                    OperationContext.Current.RequestContext.Close();
                    OperationContext.Current.RequestContext = null;
                    return(Task.FromResult((object)null));
                }
            }
        public ListenerLoopManager(ChannelDispatcher owner)
        {
            this.owner = owner;
            var sba = owner.Host != null?owner.Host.Description.Behaviors.Find <ServiceBehaviorAttribute> () : null;

            if (sba != null)
            {
                address_filter_mode = sba.AddressFilterMode;
            }
        }
 public void ApplyDispatchBehaviorAddsTheProvider()
 {
     // TODO: Figure out how to mock up the service host with endpoint dispatchers
     var listenerMock = new Mock<IChannelListener>();
     var channelDispatcher = new ChannelDispatcher(listenerMock.Object);
     var hostMock = new Mock<ServiceHostBase>();
     hostMock.Object.ChannelDispatchers.Add(channelDispatcher);
     var provider = new WcfChannelInstanceProvider(null);
     provider.ApplyDispatchBehavior(null, hostMock.Object);
 }
        private static void ApplyDispatchBehavior(ChannelDispatcher dispatcher)
        {
            // Don't add an error handler if it already exists
            foreach (IErrorHandler errorHandler in dispatcher.ErrorHandlers)
            {
                if (errorHandler is ExceptionConverterErrorHandler) return;
            }

            dispatcher.ErrorHandlers.Add(new ExceptionConverterErrorHandler());
        }
        internal void Attach(ChannelDispatcher channelDispatcher)
        {
            if (ChannelDispatcher != null)
            {
                Exception error = new InvalidOperationException(SR.SFxEndpointDispatcherMultipleChannelDispatcher0);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
            }

            ChannelDispatcher = channelDispatcher ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(channelDispatcher));
            _listenUri        = channelDispatcher.Listener.Uri;
        }
 // This is a workaround to the fact that the id of the dispatcher and endpoint must match
 // for the endpoint to be exposed in the service metadata. For simply using the service,
 // this step is not necessary.
 private void AssociateEndpointToDispatcher(ServiceEndpoint endpoint, ChannelDispatcher dispatcher)
 {
     BindingFlags instanceBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
     PropertyInfo endpointIdProperty = typeof(ServiceEndpoint).GetProperty("Id", instanceBindingFlags);
     PropertyInfo endpointDispatcherIdProperty = typeof(EndpointDispatcher).GetProperty("Id", instanceBindingFlags);
     string endpointId = endpointIdProperty.GetValue(endpoint, null) as string;
     foreach (EndpointDispatcher ed in dispatcher.Endpoints)
     {
         endpointDispatcherIdProperty.SetValue(ed, endpointId, null);
     }
 }
Exemple #17
0
        internal DispatchRuntime(ClientRuntime proxyRuntime, SharedRuntimeState shared)
            : this(shared)
        {
            if (proxyRuntime == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("proxyRuntime");
            }

            _proxyRuntime      = proxyRuntime;
            _channelDispatcher = new ChannelDispatcher(shared);
            Fx.Assert(!shared.IsOnServer, "Client constructor called on server?");
        }
        private static void ApplyDispatchBehavior(System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher)
        {
            // Don't add an error handler if it already exists
            foreach (IErrorHandler errorHandler in dispatcher.ErrorHandlers)
            {
                if (errorHandler is CustomInspectorBehavior)
                {
                    return;
                }
            }

            dispatcher.ErrorHandlers.Add(new CustomInspectorBehavior());
        }
Exemple #19
0
        internal ErrorHandlingAcceptor(IListenerBinder binder, ChannelDispatcher dispatcher)
        {
            if (binder == null)
            {
                Fx.Assert("binder is null");
            }
            if (dispatcher == null)
            {
                Fx.Assert("dispatcher is null");
            }

            this.binder     = binder;
            this.dispatcher = dispatcher;
        }
 internal SharedTransactedBatchContext(ChannelHandler handler, ChannelDispatcher dispatcher, int maxConcurrentBatches)
 {
     this.handler = handler;
     this.maxBatchSize = dispatcher.MaxTransactedBatchSize;
     this.maxConcurrentBatches = maxConcurrentBatches;
     this.currentBatchSize = dispatcher.MaxTransactedBatchSize;
     this.currentConcurrentBatches = 0;
     this.currentConcurrentDispatches = 0;
     this.successfullCommits = 0;
     this.isBatching = true;
     this.isolationLevel = dispatcher.TransactionIsolationLevel;
     this.txTimeout = TransactionBehavior.NormalizeTimeout(dispatcher.TransactionTimeout);
     this.BatchingStateChanged(this.isBatching);
 }
 internal SharedTransactedBatchContext(ChannelHandler handler, ChannelDispatcher dispatcher, int maxConcurrentBatches)
 {
     this.handler                     = handler;
     this.maxBatchSize                = dispatcher.MaxTransactedBatchSize;
     this.maxConcurrentBatches        = maxConcurrentBatches;
     this.currentBatchSize            = dispatcher.MaxTransactedBatchSize;
     this.currentConcurrentBatches    = 0;
     this.currentConcurrentDispatches = 0;
     this.successfullCommits          = 0;
     this.isBatching                  = true;
     this.isolationLevel              = dispatcher.TransactionIsolationLevel;
     this.txTimeout                   = TransactionBehavior.NormalizeTimeout(dispatcher.TransactionTimeout);
     BatchingStateChanged(this.isBatching);
 }
Exemple #22
0
            public object Invoke(object instance, object[] inputs, out object[] outputs)
            {
                FaultException exception;
                ServiceChannel serviceChannel;

                outputs = EmptyArray <object> .Allocate(0);

                Message message = inputs[0] as Message;

                if (message != null)
                {
                    string action = message.Headers.Action;
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Information, 0x80037, System.ServiceModel.SR.GetString("TraceCodeUnhandledAction"), new StringTraceRecord("Action", action), this, null, message);
                    }
                    FaultCode   code   = FaultCode.CreateSenderFaultCode("ActionNotSupported", message.Version.Addressing.Namespace);
                    FaultReason reason = new FaultReason(System.ServiceModel.SR.GetString("SFxNoEndpointMatchingContract", new object[] { action }));
                    exception = new FaultException(reason, code);
                    System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(exception);
                    serviceChannel = OperationContext.Current.InternalServiceChannel;
                    OperationContext.Current.OperationCompleted += delegate(object sender, EventArgs e) {
                        ChannelDispatcher channelDispatcher = this.dispatchRuntime.ChannelDispatcher;
                        if (!channelDispatcher.HandleError(exception) && serviceChannel.HasSession)
                        {
                            try
                            {
                                serviceChannel.Close(ChannelHandler.CloseAfterFaultTimeout);
                            }
                            catch (Exception exception1)
                            {
                                if (Fx.IsFatal(exception1))
                                {
                                    throw;
                                }
                                channelDispatcher.HandleError(exception1);
                            }
                        }
                    };
                    if (this.dispatchRuntime.shared.EnableFaults)
                    {
                        MessageFault fault = MessageFault.CreateFault(code, reason, action);
                        return(Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultFaultAction));
                    }
                    OperationContext.Current.RequestContext.Close();
                    OperationContext.Current.RequestContext = null;
                }
                return(null);
            }
Exemple #23
0
        internal void Detach(ChannelDispatcher channelDispatcher)
        {
            if (channelDispatcher == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            if (_channelDispatcher != channelDispatcher)
            {
                Exception error = new InvalidOperationException(SR.SFxEndpointDispatcherDifferentChannelDispatcher0);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
            }

            _channelDispatcher = null;
        }
        internal void Detach(ChannelDispatcher channelDispatcher)
        {
            if (channelDispatcher == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            if (this.channelDispatcher != channelDispatcher)
            {
                Exception error = new InvalidOperationException(SR.GetString(SR.SFxEndpointDispatcherDifferentChannelDispatcher0));
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
            }

            this.ReleasePerformanceCounters();
            this.channelDispatcher = null;
        }
        internal void Attach(ChannelDispatcher channelDispatcher)
        {
            if (channelDispatcher == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            if (this.channelDispatcher != null)
            {
                Exception error = new InvalidOperationException(SR.GetString(SR.SFxEndpointDispatcherMultipleChannelDispatcher0));
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
            }

            this.channelDispatcher = channelDispatcher;
            this.listenUri         = channelDispatcher.Listener.Uri;
        }
        public void ApplyDispatchBehavior_Test()
        {
            // Arrange
            ServiceHostBase host = new TestableServiceHostBase();
            Mock<IChannelListener> listener = new Mock<IChannelListener>();

            ChannelDispatcher dispatcher = new ChannelDispatcher(listener.Object);
            host.ChannelDispatchers.Add(dispatcher);

            ServiceHttpErrorBehaviorAttribute attribute = new ServiceHttpErrorBehaviorAttribute(typeof(HttpErrorHandler));

            // Act
            attribute.ApplyDispatchBehavior(null, host);

            // Assert
            Assert.IsType<HttpErrorHandler>(dispatcher.ErrorHandlers.First());
        }
 internal static bool IsConcurrent(ChannelDispatcher runtime, bool hasSession)
 {
     if (!SupportsTransactedBatch(runtime))
     {
         if (!hasSession)
         {
             return true;
         }
         foreach (EndpointDispatcher dispatcher in runtime.Endpoints)
         {
             if (dispatcher.DispatchRuntime.ConcurrencyMode != ConcurrencyMode.Single)
             {
                 return true;
             }
         }
     }
     return false;
 }
Exemple #28
0
 internal static bool IsConcurrent(ChannelDispatcher runtime, bool hasSession)
 {
     if (!SupportsTransactedBatch(runtime))
     {
         if (!hasSession)
         {
             return(true);
         }
         foreach (EndpointDispatcher dispatcher in runtime.Endpoints)
         {
             if (dispatcher.DispatchRuntime.ConcurrencyMode != ConcurrencyMode.Single)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
		public void ApplyDispatchBehavior ()
		{
			var se = CreateEndpoint ();
			var od = se.Contract.Operations [0];
			// in .NET 3.5 it adds "OperationSelectorBehavior"
			int initCB = ContractDescription.GetContract (typeof (IMyService)).Behaviors.Count;
			// in .NET 3.5 it adds
			// - OperationInvokeBehavior, 
			// - OperationBehaviorAttribute, 
			// - DataContractSerializerOperationBehavior and 
			// - DataContractSerializerOperationGenerator
			int initOB = od.Behaviors.Count;
			// Assert.AreEqual (1, initCB, "#0-1");
			// Assert.AreEqual (4, initOB, "#0-2");

			var b = new WebHttpBehavior ();
			se.Behaviors.Add (b);
			var ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
			IChannelListener l = new WebHttpBinding ().BuildChannelListener<IReplyChannel> (new BindingParameterCollection ());
			var cd = new ChannelDispatcher (l);
			cd.Endpoints.Add (ed); // without it this test results in NRE (it blindly adds IErrorHandler).
			Assert.AreEqual (0, cd.ErrorHandlers.Count, "#1-1");
			Assert.IsNull (ed.DispatchRuntime.OperationSelector, "#1-2");
			Assert.AreEqual (1, se.Behaviors.Count, "#1-3-1");
			Assert.AreEqual (initCB, se.Contract.Behaviors.Count, "#1-3-2");
			Assert.AreEqual (initOB, od.Behaviors.Count, "#1-3-3");

			Assert.IsTrue (ed.AddressFilter is EndpointAddressMessageFilter, "#1-4");

			b.ApplyDispatchBehavior (se, ed);
			// FIXME: implement and enable it later
			//Assert.AreEqual (1, cd.ErrorHandlers.Count, "#2-1");
			Assert.AreEqual (typeof (WebHttpDispatchOperationSelector),
					 ed.DispatchRuntime.OperationSelector.GetType (), "#2-2");
			Assert.AreEqual (1, se.Behaviors.Count, "#3-1");
			Assert.AreEqual (initCB, se.Contract.Behaviors.Count, "#3-2");
			Assert.AreEqual (initOB, od.Behaviors.Count, "#3-3");
			// ... i.e. nothing is added.

			Assert.IsTrue (ed.AddressFilter is PrefixEndpointAddressMessageFilter, "#3-4");

			Assert.AreEqual (0, ed.DispatchRuntime.Operations.Count, "#4-0"); // hmm... really?
		}
Exemple #30
0
        internal ListenerHandler(IListenerBinder listenerBinder, ChannelDispatcher channelDispatcher, IDefaultCommunicationTimeouts timeouts)
        {
            _listenerBinder = listenerBinder;
            if (!((_listenerBinder != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.listenerBinder != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listenerBinder");
            }

            _channelDispatcher = channelDispatcher;
            if (!((_channelDispatcher != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.channelDispatcher != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            _timeouts = timeouts;

            _endpoints = channelDispatcher.EndpointDispatcherTable;
        }
Exemple #31
0
        internal ListenerHandler(IListenerBinder listenerBinder, ChannelDispatcher channelDispatcher, IDefaultCommunicationTimeouts timeouts)
        {
            _listenerBinder = listenerBinder;
            if (!((_listenerBinder != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.listenerBinder != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listenerBinder");
            }

            _channelDispatcher = channelDispatcher;
            if (!((_channelDispatcher != null)))
            {
                Fx.Assert("ListenerHandler.ctor: (this.channelDispatcher != null)");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
            }

            _timeouts = timeouts;

            _endpoints = channelDispatcher.EndpointDispatcherTable;
        }
        private void TransferChannelFromPendingList(ref MessageRpc rpc)
        {
            if (rpc.Channel.IsPending)
            {
                rpc.Channel.IsPending = false;

                ChannelDispatcher        channelDispatcher = rpc.Channel.ChannelDispatcher;
                IInstanceContextProvider provider          = _instance.InstanceContextProvider;

                if (!InstanceContextProviderBase.IsProviderSessionful(provider) &&
                    !InstanceContextProviderBase.IsProviderSingleton(provider))
                {
                    IChannel proxy = rpc.Channel.Proxy as IChannel;
                    if (!rpc.InstanceContext.IncomingChannels.Contains(proxy))
                    {
                        channelDispatcher.Channels.Add(proxy);
                    }
                }

                channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel);
            }
        }
Exemple #33
0
        internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder,
                                ListenerHandler listener, SessionIdleManager idleManager)
        {
            ChannelDispatcher channelDispatcher = listener.ChannelDispatcher;

            _messageVersion     = messageVersion;
            _isManualAddressing = channelDispatcher.ManualAddressing;
            _binder             = binder;
            _listener           = listener;

            _receiveSynchronously = channelDispatcher.ReceiveSynchronously;
            _sendAsynchronously   = channelDispatcher.SendAsynchronously;
            _duplexBinder         = binder as DuplexChannelBinder;
            _hasSession           = binder.HasSession;
            _isConcurrent         = ConcurrencyBehavior.IsConcurrent(channelDispatcher, _hasSession);

            if (channelDispatcher.MaxPendingReceives > 1)
            {
                throw NotImplemented.ByDesign;
            }

            if (channelDispatcher.BufferedReceiveEnabled)
            {
                _binder = new BufferedReceiveBinder(_binder);
            }

            _receiver    = new ErrorHandlingReceiver(_binder, channelDispatcher);
            _idleManager = idleManager;
            Fx.Assert((_idleManager != null) == (_binder.HasSession && _listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout != TimeSpan.MaxValue), "idle manager is present only when there is a session with a finite receive timeout");


            _requestInfo = new RequestInfo(this);

            if (_listener.State == CommunicationState.Opened)
            {
                _listener.ChannelDispatcher.Channels.IncrementActivityCount();
                _incrementedActivityCountInConstructor = true;
            }
        }
		private ChannelDispatcher BuildChannelDispatcher(Uri listenUri, ServiceHostBase host)
		{
			BindingParameterCollection parameters = new BindingParameterCollection();
			VirtualPathExtension item = host.Extensions.Find<VirtualPathExtension>();
			if (item != null)
			{
				parameters.Add(item);
			}

			IChannelListener<IReplyChannel> listener = null;
			WebHttpBinding binding = new WebHttpBinding();
			if (binding.CanBuildChannelListener<IReplyChannel>(parameters))
			{
				listener = binding.BuildChannelListener<IReplyChannel>(listenUri, parameters);
			}

			ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener)
			{
				MessageVersion = MessageVersion.None
			};

			return channelDispatcher;
		}
Exemple #35
0
        protected override bool ProcessRequest(MessageProcessingContext mrc)
        {
            Exception       ex = mrc.ProcessingException;
            DispatchRuntime dispatchRuntime = mrc.OperationContext.EndpointDispatcher.DispatchRuntime;

            //invoke all user handlers
            ChannelDispatcher channelDispatcher = dispatchRuntime.ChannelDispatcher;

            foreach (IErrorHandler handler in channelDispatcher.ErrorHandlers)
            {
                if (handler.HandleError(ex))
                {
                    break;
                }
            }

            // FIXME: remove them. FaultConverter also covers errors like EndpointNotFoundException, which this handler never covers. And checking converter twice is extraneous, so this part is just extraneous.
            // FIXME: actually everything is done in OperationInvokerHandler now...
            FaultConverter fc  = FaultConverter.GetDefaultFaultConverter(dispatchRuntime.ChannelDispatcher.MessageVersion);
            Message        res = null;

            if (!fc.TryCreateFaultMessage(ex, out res))
            {
                throw ex;
            }
            mrc.ReplyMessage = res;

            if (duplex != null)
            {
                mrc.Reply(duplex, true);
            }
            else
            {
                mrc.Reply(true);
            }
            return(false);
        }
        void AddMetadataEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher, bool debugMode)
        {
            Uri baseAddress = endpoint.Address.Uri;
            if (baseAddress == null)
            {
                return;
            }

            ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host;

            UriBuilder builder = new UriBuilder(baseAddress);
            builder.Path += builder.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase)
                ? (WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode))
                : ("/" + WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode));
            EndpointAddress metadataAddress = new EndpointAddress(builder.Uri);

            foreach (ServiceEndpoint serviceEndpoint in host.Description.Endpoints)
            {
                if (EndpointAddress.UriEquals(serviceEndpoint.Address.Uri, metadataAddress.Uri, true, false))//  ignoreCase //  includeHostNameInComparison 
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.JsonNoEndpointAtMetadataAddress, this.GetType().ToString(), serviceEndpoint.Address, serviceEndpoint.Name, host.Description.Name)));
                }
            }

            HttpTransportBindingElement transportBindingElement;
            HttpTransportBindingElement existingTransportBindingElement = endpoint.Binding.CreateBindingElements().Find<HttpTransportBindingElement>();

            if (existingTransportBindingElement != null)
            {
                transportBindingElement = (HttpTransportBindingElement)existingTransportBindingElement.Clone();
            }
            else
            {
                if (baseAddress.Scheme == "https")
                {
                    transportBindingElement = new HttpsTransportBindingElement();
                }
                else
                {
                    transportBindingElement = new HttpTransportBindingElement();
                }
            }

            transportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            transportBindingElement.TransferMode = TransferMode.Buffered;
            transportBindingElement.MaxBufferSize = MaxMetadataEndpointBufferSize;
            transportBindingElement.MaxReceivedMessageSize = MaxMetadataEndpointBufferSize;
            Binding metadataBinding = new CustomBinding(
                new WebScriptMetadataMessageEncodingBindingElement(),
                transportBindingElement);
            BindingParameterCollection parameters = host.GetBindingParameters(endpoint);

            // build endpoint dispatcher
            ContractDescription metadataContract = ContractDescription.GetContract(typeof(ServiceMetadataExtension.IHttpGetMetadata));
            OperationDescription metadataOperation = metadataContract.Operations[0];
            EndpointDispatcher metadataEndpointDispatcher = new EndpointDispatcher(metadataAddress, metadataContract.Name, metadataContract.Namespace);
            DispatchOperation dispatchOperation = new DispatchOperation(metadataEndpointDispatcher.DispatchRuntime, metadataOperation.Name, metadataOperation.Messages[0].Action, metadataOperation.Messages[1].Action);
            dispatchOperation.Formatter = new WebScriptMetadataFormatter();
            dispatchOperation.Invoker = new SyncMethodInvoker(metadataOperation.SyncMethod);
            metadataEndpointDispatcher.DispatchRuntime.Operations.Add(dispatchOperation);
            metadataEndpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, new WebScriptClientGenerator(endpoint, debugMode, !String.IsNullOrEmpty(this.JavascriptCallbackParameterName)));
            metadataEndpointDispatcher.DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(metadataEndpointDispatcher.DispatchRuntime);

            // build channel dispatcher
            IChannelListener<IReplyChannel> listener = null;
            if (metadataBinding.CanBuildChannelListener<IReplyChannel>(parameters))
            {
                listener = metadataBinding.BuildChannelListener<IReplyChannel>(metadataAddress.Uri, parameters);
            }
            ChannelDispatcher metadataChannelDispatcher = new ChannelDispatcher(listener);
            metadataChannelDispatcher.MessageVersion = MessageVersion.None;
            metadataChannelDispatcher.Endpoints.Add(metadataEndpointDispatcher);

            host.ChannelDispatchers.Add(metadataChannelDispatcher);
        }
Exemple #37
0
 internal EndpointDispatcherCollection(ChannelDispatcher owner)
     : base(owner.ThisLock)
 {
     _owner = owner;
 }
 internal ErrorHandlingAcceptor(IListenerBinder binder, ChannelDispatcher dispatcher)
 {
     this.binder     = binder;
     this.dispatcher = dispatcher;
 }
        private void ApplyDispatchBehavior(ChannelDispatcher dispatcher)
        {
            // Don't add an error handler if it already exists
            foreach (IErrorHandler errorHandler in dispatcher.ErrorHandlers)
            {
                if (errorHandler is ExceptionMarshallingErrorHandler)
                {
                    return;
                }
            }

            dispatcher.ErrorHandlers.Add(new ExceptionMarshallingErrorHandler());
        }
 private bool HandleError(Exception e)
 {
     return(ChannelDispatcher.HandleError(e));
 }
Exemple #41
0
		public abstract void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout);
 internal ErrorHandlingReceiver(IChannelBinder binder, ChannelDispatcher dispatcher)
 {
     _binder     = binder;
     _dispatcher = dispatcher;
 }
 private void ApplyDispatchBehavior(ChannelDispatcher dispatcher)
 {
     //Nothing here
 }
 public EndpointDispatcherCollection(ChannelDispatcher owner)
 {
     this.owner = owner;
 }
        void CreateWorkflowManagementEndpoint(WorkflowServiceHost workflowServiceHost)
        {
            Binding controlEndpointBinding; 
            if (workflowServiceHost.InternalBaseAddresses.Contains(Uri.UriSchemeNetPipe))
            {
                controlEndpointBinding = NamedPipeControlEndpointBinding;
            }
            else if (workflowServiceHost.InternalBaseAddresses.Contains(Uri.UriSchemeHttp))
            {
                controlEndpointBinding = HttpControlEndpointBinding;
            }
            else
            {
                return;
            }

            Uri controlEndpointAddress = ServiceHost.GetVia(controlEndpointBinding.Scheme, new Uri(ControlEndpointAddress, UriKind.Relative), workflowServiceHost.InternalBaseAddresses);            
            XmlQualifiedName contractName = new XmlQualifiedName(XD2.WorkflowInstanceManagementService.ContractName, XD2.WorkflowServices.Namespace);
            //Create the Endpoint Dispatcher
            EndpointAddress address = new EndpointAddress(controlEndpointAddress.AbsoluteUri);
            EndpointDispatcher endpointDispatcher = new EndpointDispatcher(address,
                XD2.WorkflowInstanceManagementService.ContractName,
                XD2.WorkflowServices.Namespace, true)
            {
                ContractFilter = new ActionMessageFilter(
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Abandon, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Cancel, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Run, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Suspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Terminate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedCancel, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedRun, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedSuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedTerminate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedUnsuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedUpdate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Unsuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Update, null, false)),
            };

            //Create Listener
            ServiceEndpoint endpoint = new ServiceEndpoint(WorkflowControlEndpoint.WorkflowControlServiceContract, controlEndpointBinding, address);
            BindingParameterCollection parameters = workflowServiceHost.GetBindingParameters(endpoint);

            IChannelListener listener;
            if (controlEndpointBinding.CanBuildChannelListener<IDuplexSessionChannel>(controlEndpointAddress, parameters))
            {
                listener = controlEndpointBinding.BuildChannelListener<IDuplexSessionChannel>(controlEndpointAddress, parameters);
            }
            else if (controlEndpointBinding.CanBuildChannelListener<IReplySessionChannel>(controlEndpointAddress, parameters))
            {
                listener = controlEndpointBinding.BuildChannelListener<IReplySessionChannel>(controlEndpointAddress, parameters);
            }
            else
            {
                listener = controlEndpointBinding.BuildChannelListener<IReplyChannel>(controlEndpointAddress, parameters);
            }

            //Add the operations
            bool formatRequest;
            bool formatReply;
            foreach (OperationDescription operation in WorkflowControlEndpoint.WorkflowControlServiceContract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = new DataContractSerializerOperationBehavior(operation);

                DispatchOperation operationDispatcher = new DispatchOperation(endpointDispatcher.DispatchRuntime, operation.Name,
                    NamingHelper.GetMessageAction(operation, false), NamingHelper.GetMessageAction(operation, true))
                {
                    Formatter = (IDispatchMessageFormatter)dataContractSerializerOperationBehavior.GetFormatter(operation, out formatRequest, out formatReply, false),
                    Invoker = new ControlOperationInvoker(
                        operation,
                        new WorkflowControlEndpoint(controlEndpointBinding, address),
                        null,
                        workflowServiceHost),
                };
                endpointDispatcher.DispatchRuntime.Operations.Add(operationDispatcher);

                OperationBehaviorAttribute operationAttribute = operation.Behaviors.Find<OperationBehaviorAttribute>();
                ((IOperationBehavior)operationAttribute).ApplyDispatchBehavior(operation, operationDispatcher);
            }

            DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
            dispatchRuntime.ConcurrencyMode = ConcurrencyMode.Multiple;
            dispatchRuntime.InstanceContextProvider = new DurableInstanceContextProvider(workflowServiceHost);
            dispatchRuntime.InstanceProvider = new DurableInstanceProvider(workflowServiceHost);
            dispatchRuntime.ServiceAuthorizationManager = new WindowsAuthorizationManager(this.WindowsGroup);

            //Create the Channel Dispatcher
            ServiceDebugBehavior serviceDebugBehavior = workflowServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
            ServiceBehaviorAttribute serviceBehaviorAttribute = workflowServiceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();

            bool includeDebugInfo = false;
            if (serviceDebugBehavior != null)
            {
                includeDebugInfo |= serviceDebugBehavior.IncludeExceptionDetailInFaults;
            }
            if (serviceBehaviorAttribute != null)
            {
                includeDebugInfo |= serviceBehaviorAttribute.IncludeExceptionDetailInFaults;
            }

            ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, controlEndpointBinding.Name, controlEndpointBinding)
            {
                MessageVersion = controlEndpointBinding.MessageVersion,
                Endpoints = { endpointDispatcher },
                ServiceThrottle = workflowServiceHost.ServiceThrottle
            };
            workflowServiceHost.ChannelDispatchers.Add(channelDispatcher);
        }
Exemple #46
0
 public ListenerLoopManager(ChannelDispatcher owner)
 {
     this.owner = owner;
 }
Exemple #47
0
		public bool TryDequeueRequest (ChannelDispatcher channel, TimeSpan timeout, out HttpContextInfo context)
		{
			DateTime start = DateTime.Now;

			context = null;
			var ce = Entries.FirstOrDefault (e => e.ChannelDispatcher == channel);
			if (ce == null)
				return false;
			lock (ce.RetrieverLock) {
				var q = ce.ContextQueue;
				if (q.Count == 0) {
					bool ret = ce.WaitHandle.WaitOne (timeout);
					return ret && TryDequeueRequest (channel, timeout - (DateTime.Now - start), out context); // recurse, am lazy :/
				}
				context = q.Dequeue ();
				return true;
			}
		}
Exemple #48
0
		// FIXME: use timeout
		public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
		{
			UnregisterListenerCommon (channel, timeout);

			// stop the server if there is no more registered listener.
			if (Entries.Count > 0)
				return;

#if USE_SEPARATE_LOOP
			loop.Abort ();
#else
			this.listener.Stop ();
#endif
		}
Exemple #49
0
 private static bool SupportsTransactedBatch(ChannelDispatcher channelDispatcher)
 {
     return(channelDispatcher.IsTransactedReceive && (channelDispatcher.MaxTransactedBatchSize > 0));
 }
Exemple #50
0
 internal ChannelDispatcherBehaviorCollection(ChannelDispatcher outer)
     : base(outer.ThisLock)
 {
     _outer = outer;
 }
Exemple #51
0
		public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
		{
			RegisterListenerCommon (channel, timeout);
		}
        public void InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
        {
            if (serviceHost.ImplementedContracts != null && serviceHost.ImplementedContracts.Count > 0)
            {
                EnsureThereAreApplicationEndpoints(description);
            }
            ValidateDescription(description, serviceHost);

            AspNetEnvironment.Current.AddHostingBehavior(serviceHost, description);

            ServiceBehaviorAttribute instanceSettings = description.Behaviors.Find<ServiceBehaviorAttribute>();
            InitializeServicePerformanceCounters(serviceHost);

            Dictionary<ListenUriInfo, StuffPerListenUriInfo> stuffPerListenUriInfo
                = new Dictionary<ListenUriInfo, StuffPerListenUriInfo>();
            Dictionary<EndpointAddress, Collection<EndpointInfo>> endpointInfosPerEndpointAddress
                = new Dictionary<EndpointAddress, Collection<EndpointInfo>>();

            // Ensure ListenUri and group endpoints per ListenUri
            for (int i = 0; i < description.Endpoints.Count; i++)
            {
                //Ensure ReceiveContextSettings before building channel
                bool requiresReceiveContext = false; //at least one operation had ReceiveContextEnabledAttribute
                ServiceEndpoint endpoint = description.Endpoints[i];

                foreach (OperationDescription operation in endpoint.Contract.Operations)
                {
                    if (operation.Behaviors.Find<ReceiveContextEnabledAttribute>() != null)
                    {
                        requiresReceiveContext = true;
                        break;
                    }
                }

                if (requiresReceiveContext)
                {
                    IReceiveContextSettings receiveContextSettings = endpoint.Binding.GetProperty<IReceiveContextSettings>(new BindingParameterCollection());

                    if (receiveContextSettings == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(
                            SR.GetString(SR.SFxReceiveContextSettingsPropertyMissing,
                            endpoint.Contract.Name,
                            typeof(ReceiveContextEnabledAttribute).Name,
                            endpoint.Address.Uri.AbsoluteUri,
                            typeof(IReceiveContextSettings).Name)));
                    }
                    //Enable ReceiveContext on the binding.
                    receiveContextSettings.Enabled = true;
                }

                ListenUriInfo listenUriInfo = GetListenUriInfoForEndpoint(serviceHost, endpoint);
                if (!stuffPerListenUriInfo.ContainsKey(listenUriInfo))
                {
                    stuffPerListenUriInfo.Add(listenUriInfo, new StuffPerListenUriInfo());
                }
                stuffPerListenUriInfo[listenUriInfo].Endpoints.Add(endpoint);
            }

            foreach (KeyValuePair<ListenUriInfo, StuffPerListenUriInfo> stuff in stuffPerListenUriInfo)
            {
                Uri listenUri = stuff.Key.ListenUri;
                ListenUriMode listenUriMode = stuff.Key.ListenUriMode;
                BindingParameterCollection parameters = stuff.Value.Parameters;
                Binding binding = stuff.Value.Endpoints[0].Binding;
                EndpointIdentity identity = stuff.Value.Endpoints[0].Address.Identity;
                // same EndpointAddressTable instance must be shared between channelDispatcher and parameters
                ThreadSafeMessageFilterTable<EndpointAddress> endpointAddressTable = new ThreadSafeMessageFilterTable<EndpointAddress>();
                parameters.Add(endpointAddressTable);

                bool supportContextSession = false;
                // add service-level binding parameters
                foreach (IServiceBehavior behavior in description.Behaviors)
                {
                    if (behavior is IContextSessionProvider)
                    {
                        supportContextSession = true;
                    }
                    behavior.AddBindingParameters(description, serviceHost, stuff.Value.Endpoints, parameters);
                }
                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint = stuff.Value.Endpoints[i];
                    string viaString = listenUri.AbsoluteUri;

                    // ensure all endpoints with this ListenUriInfo have same binding
                    if (endpoint.Binding != binding)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ABindingInstanceHasAlreadyBeenAssociatedTo1, viaString)));
                    }

                    // ensure all endpoints with this ListenUriInfo have same identity
                    if (!object.Equals(endpoint.Address.Identity, identity))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.GetString(SR.SFxWhenMultipleEndpointsShareAListenUriTheyMustHaveSameIdentity, viaString)));
                    }

                    // add binding parameters (endpoint scope and below)
                    AddMsmqIntegrationContractInformation(endpoint);
                    SecurityContractInformationEndpointBehavior.ServerInstance.AddBindingParameters(endpoint, parameters);
                    AddBindingParameters(endpoint, parameters);
                }

                // build IChannelListener and ChannelDispatcher
                IChannelListener listener;
                Type channelType = this.BuildChannelListener(stuff.Value,
                                                             serviceHost,
                                                             listenUri,
                                                             listenUriMode,
                                                             supportContextSession,
                                                             out listener);

                XmlQualifiedName bindingQname = new XmlQualifiedName(binding.Name, binding.Namespace);
                ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, bindingQname.ToString(), binding);
                channelDispatcher.SetEndpointAddressTable(endpointAddressTable);
                stuff.Value.ChannelDispatcher = channelDispatcher;

                bool canReceiveInTransaction = false;   // at least one operation is TransactionScopeRequired
                int transactedBatchSize = int.MaxValue;

                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint = stuff.Value.Endpoints[i];
                    string viaString = listenUri.AbsoluteUri;

                    EndpointFilterProvider provider = new EndpointFilterProvider();
                    EndpointDispatcher dispatcher = DispatcherBuilder.BuildDispatcher(serviceHost, description, endpoint, endpoint.Contract, provider);

                    for (int j = 0; j < endpoint.Contract.Operations.Count; j++)
                    {
                        OperationDescription operation = endpoint.Contract.Operations[j];
                        OperationBehaviorAttribute operationBehavior = operation.Behaviors.Find<OperationBehaviorAttribute>();
                        if (null != operationBehavior && operationBehavior.TransactionScopeRequired)
                        {
                            canReceiveInTransaction = true;
                            break;
                        }
                    }

                    if (!endpointInfosPerEndpointAddress.ContainsKey(endpoint.Address))
                    {
                        endpointInfosPerEndpointAddress.Add(endpoint.Address, new Collection<EndpointInfo>());
                    }
                    endpointInfosPerEndpointAddress[endpoint.Address].Add(new EndpointInfo(endpoint, dispatcher, provider));

                    channelDispatcher.Endpoints.Add(dispatcher);

                    TransactedBatchingBehavior batchBehavior = endpoint.Behaviors.Find<TransactedBatchingBehavior>();
                    if (batchBehavior == null)
                    {
                        transactedBatchSize = 0;
                    }
                    else
                    {
                        if (!canReceiveInTransaction)
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MsmqBatchRequiresTransactionScope)));
                        transactedBatchSize = System.Math.Min(transactedBatchSize, batchBehavior.MaxBatchSize);
                    }
                    if (PerformanceCounters.PerformanceCountersEnabled || PerformanceCounters.MinimalPerformanceCountersEnabled)
                    {
                        PerformanceCounters.AddPerformanceCountersForEndpoint(serviceHost, endpoint.Contract, dispatcher);
                    }
                } // end foreach "endpoint"

                if (canReceiveInTransaction)
                {
                    BindingElementCollection bindingElements = binding.CreateBindingElements();
                    foreach (BindingElement bindingElement in bindingElements)
                    {
                        ITransactedBindingElement txElement = bindingElement as ITransactedBindingElement;
                        if (null != txElement && txElement.TransactedReceiveEnabled)
                        {
                            channelDispatcher.IsTransactedReceive = true;
                            channelDispatcher.MaxTransactedBatchSize = transactedBatchSize;
                            break;
                        }
                    }
                }

                //Set the mode of operation for ChannelDispatcher based on binding Settings.
                IReceiveContextSettings receiveContextSettings = binding.GetProperty<IReceiveContextSettings>(new BindingParameterCollection());

                if (receiveContextSettings != null)
                {
                    channelDispatcher.ReceiveContextEnabled = receiveContextSettings.Enabled;
                }
                serviceHost.ChannelDispatchers.Add(channelDispatcher);
            } // end foreach "ListenUri/ChannelDispatcher" group

            // run service behaviors
            for (int i = 0; i < description.Behaviors.Count; i++)
            {
                IServiceBehavior serviceBehavior = description.Behaviors[i];
                serviceBehavior.ApplyDispatchBehavior(description, serviceHost);
            }

            foreach (KeyValuePair<ListenUriInfo, StuffPerListenUriInfo> stuff in stuffPerListenUriInfo)
            {
                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint = stuff.Value.Endpoints[i];
                    // rediscover which dispatcher goes with this endpoint
                    Collection<EndpointInfo> infos = endpointInfosPerEndpointAddress[endpoint.Address];
                    EndpointInfo info = null;
                    foreach (EndpointInfo ei in infos)
                    {
                        if (ei.Endpoint == endpoint)
                        {
                            info = ei;
                            break;
                        }
                    }
                    EndpointDispatcher dispatcher = info.EndpointDispatcher;
                    // run contract behaviors
                    for (int k = 0; k < endpoint.Contract.Behaviors.Count; k++)
                    {
                        IContractBehavior behavior = endpoint.Contract.Behaviors[k];
                        behavior.ApplyDispatchBehavior(endpoint.Contract, endpoint, dispatcher.DispatchRuntime);
                    }
                    // run endpoint behaviors
                    BindingInformationEndpointBehavior.Instance.ApplyDispatchBehavior(endpoint, dispatcher);
                    TransactionContractInformationEndpointBehavior.Instance.ApplyDispatchBehavior(endpoint, dispatcher);
                    for (int j = 0; j < endpoint.Behaviors.Count; j++)
                    {
                        IEndpointBehavior eb = endpoint.Behaviors[j];
                        eb.ApplyDispatchBehavior(endpoint, dispatcher);
                    }
                    // run operation behaviors
                    DispatcherBuilder.BindOperations(endpoint.Contract, null, dispatcher.DispatchRuntime);
                }
            }

            this.EnsureRequiredRuntimeProperties(endpointInfosPerEndpointAddress);

            // Warn about obvious demux conflicts
            foreach (Collection<EndpointInfo> endpointInfos in endpointInfosPerEndpointAddress.Values)
            {
                // all elements of endpointInfos share the same Address (and thus EndpointListener.AddressFilter)
                if (endpointInfos.Count > 1)
                {
                    for (int i = 0; i < endpointInfos.Count; i++)
                    {
                        for (int j = i + 1; j < endpointInfos.Count; j++)
                        {
                            // if not same ListenUri, won't conflict
                            // if not same ChannelType, may not conflict (some transports demux based on this)
                            // if they share a ChannelDispatcher, this means same ListenUri and same ChannelType
                            if (endpointInfos[i].EndpointDispatcher.ChannelDispatcher ==
                                endpointInfos[j].EndpointDispatcher.ChannelDispatcher)
                            {
                                EndpointFilterProvider iProvider = endpointInfos[i].FilterProvider;
                                EndpointFilterProvider jProvider = endpointInfos[j].FilterProvider;
                                // if not default EndpointFilterProvider, we won't try to throw, you're on your own
                                string commonAction;
                                if (iProvider != null && jProvider != null
                                    && HaveCommonInitiatingActions(iProvider, jProvider, out commonAction))
                                {
                                    // you will definitely get a MultipleFiltersMatchedException at runtime,
                                    // so let's go ahead and throw now
                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                        new InvalidOperationException(
                                            SR.GetString(SR.SFxDuplicateInitiatingActionAtSameVia,
                                                         endpointInfos[i].Endpoint.ListenUri, commonAction)));
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #53
0
		public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
		{
			UnregisterListenerCommon (channel, timeout);
		}
Exemple #54
0
		// FIXME: use timeout
		public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
		{
			RegisterListenerCommon (channel, timeout);

			if (Entries.Count != 1)
				return;

			if (element != null) {
				var l = listener;
				l.AuthenticationSchemeSelectorDelegate = delegate (HttpListenerRequest req) {
					return element.AuthenticationScheme;
				};
				l.Realm = element.Realm;
				l.UnsafeConnectionNtlmAuthentication = element.UnsafeConnectionNtlmAuthentication;
			}

			// Start here. It is shared between channel listeners
			// that share the same listen Uri. So there is no other appropriate place.
#if USE_SEPARATE_LOOP // this cannot be enabled because it causes infinite loop when ChannelDispatcher is not involved.
			loop = new Thread (new ThreadStart (delegate {
				listener.Start ();
				try {
					while (true)
						ProcessNewContext (listener.GetContext ());
				} catch (ThreadAbortException) {
					Thread.ResetAbort ();
				}
				listener.Stop ();
			}));
			loop.Start ();
#else
			listener.Start ();
			listener.BeginGetContext (GetContextCompleted, null);
#endif
		}
Exemple #55
0
		public abstract void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout);