/**
  * The execution of this behavior comes rather late.
  * Anyone that inspects the service description in the meantime,
  * such as for metadata generation, won't see the protection level that we want to use.
  *
  * One way of doing it is at when create HostFactory
  *
  * ServiceEndpoint endpoint = host.Description.Endpoints.Find(typeof(IService));
  * OperationDescription operation = endpoint.Contract.Operations.Find("Action");
  * MessageDescription message = operation.Messages.Find("http://tempuri.org/IService/ActionResponse");
  * MessageHeaderDescription header = message.Headers[new XmlQualifiedName("aheader", "http://tempuri.org/")];
  * header.ProtectionLevel = ProtectionLevel.Sign;
  *
  * **/
 public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
 {
     ChannelProtectionRequirements requirements = bindingParameters.Find<ChannelProtectionRequirements>();
     XmlQualifiedName qName = new XmlQualifiedName(header, ns);
     MessagePartSpecification part = new MessagePartSpecification(qName);
     requirements.OutgoingSignatureParts.AddParts(part, action);
 }
 public void ApplyDispatchBehavior(
   ContractDescription contractDescription,
   ServiceEndpoint endpoint,
   DispatchRuntime dispatchRuntime)
 {
     dispatchRuntime.InstanceProvider = this;
 }
 public ComPlusThreadInitializer(ContractDescription contract, DispatchOperation operation, ServiceInfo info)
 {
     this.info = info;
     this.iid = contract.ContractType.GUID;
     if (info.CheckRoles)
     {
         string[] serviceRoleMembers = null;
         string[] contractRoleMembers = null;
         string[] operationRoleMembers = null;
         serviceRoleMembers = info.ComponentRoleMembers;
         foreach (ContractInfo info2 in this.info.Contracts)
         {
             if (!(info2.IID == this.iid))
             {
                 continue;
             }
             contractRoleMembers = info2.InterfaceRoleMembers;
             foreach (System.ServiceModel.ComIntegration.OperationInfo info3 in info2.Operations)
             {
                 if (info3.Name == operation.Name)
                 {
                     operationRoleMembers = info3.MethodRoleMembers;
                     break;
                 }
             }
             if (operationRoleMembers == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ComOperationNotFound", new object[] { contract.Name, operation.Name })));
             }
             break;
         }
         this.comAuth = new ComPlusAuthorization(serviceRoleMembers, contractRoleMembers, operationRoleMembers);
     }
 }
Beispiel #4
0
        private static void ConfigureRouterViaCode(ServiceHost serviceHost)
        {
            //This code sets up the Routing Sample via code.  Rename or delete the App.config file
            //and comment out this method call to run a config-based Routing Service

            //set up some communication defaults
            string deadAddress = "net.tcp://localhost:9090/servicemodelsamples/fakeDestination";
            string realAddress = "net.tcp://localhost:8080/servicemodelsamples/service";
            string routerAddress = "http://localhost/routingservice/router";

            //note that the calculator client will be communicating to the Routing Service via basic
            //HTTP, while the Routing Service is using Net.TCP to communicate to the calculator service.
            //This demonstrates the Routing Service's capability of bridging between different message
            //transports, formats, bindings, etc.  This automatic message conversion is governed by
            //whether or not SoapProcessing (enabled by default) is enabled on the Routing Configuration. 
            Binding routerBinding = new BasicHttpBinding();
            Binding clientBinding = new NetTcpBinding();
            
            //add the endpoint the router will use to recieve messages
            serviceHost.AddServiceEndpoint(typeof(IRequestReplyRouter), routerBinding, routerAddress);
            
            //create the client endpoint the router will route messages to
            //note that the contract description on the client endpoints is actually unused, so
            //this could be any string.  The contract specified here goes unused
            //because the Routing Service replaces this contract with one of the Router
            //contracts at runtime, depending on the contract that a message was received with.
            ContractDescription contract = new ContractDescription("IRequestReplyRouter");
            ServiceEndpoint fakeDestination = new ServiceEndpoint(contract, clientBinding, new EndpointAddress(deadAddress));
            ServiceEndpoint realDestination = new ServiceEndpoint(contract, clientBinding, new EndpointAddress(realAddress));
            
            //create the endpoint list that contains the service endpoints we want to route to
            List<ServiceEndpoint> backupList = new List<ServiceEndpoint>();

            //add the endpoints in the order that the Routing Service should contact them
            //first add the endpoint that we know will be down
            //clearly, normally you wouldn't know that this endpoint was down by default
            backupList.Add(fakeDestination);

            //then add the endpoint that will work
            //the Routing Service will attempt to send to this endpoint only if it 
            //encounters a TimeOutException or CommunicationException when sending
            //to the previous endpoint in the list.
            backupList.Add(realDestination);
            
            //create the default RoutingConfiguration option            
            RoutingConfiguration rc = new RoutingConfiguration();
            
            //add a MatchAll filter to the Routing Configuration's filter table
            //map it to the list of endpoints defined above
            //when a message matches this filter, it will be sent to the endpoints in the list in order
            //if an endpoint is down or doesn't respond (which the first client won't
            //since no service exists at that endpoint), the Routing Service will automatically move the message
            //to the next endpoint in the list and try again.
            rc.FilterTable.Add(new MatchAllMessageFilter(), backupList);
            
            //create the Routing Behavior with the Routing Configuration and add it to the 
            //serviceHost's Description.
            serviceHost.Description.Behaviors.Add(new RoutingBehavior(rc));
                        
        }
        private static void ApplyOperationBehaviors(ContractDescription contractDescription)
        {
            foreach (OperationDescription description in contractDescription.Operations)
            {
                switch (description.Name)
                {
                    case "Abandon":
                    case "Cancel":
                    case "Run":
                    case "Suspend":
                    case "Terminate":
                    case "Unsuspend":
                        EnsureDispatch(description);
                        break;

                    case "TransactedCancel":
                    case "TransactedRun":
                    case "TransactedSuspend":
                    case "TransactedTerminate":
                    case "TransactedUnsuspend":
                        EnsureDispatch(description);
                        EnsureTransactedInvoke(description);
                        break;
                }
            }
        }
		public ServiceContractGenerationContext (
			ServiceContractGenerator serviceContractGenerator,
			ContractDescription contract,
			CodeTypeDeclaration contractType)
			: this (serviceContractGenerator, contract, contractType, null)
		{
		}
 public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                 ClientRuntime clientRuntime)
 {
     if (!TypeHelper.IsTypeOf<IClientMessageInspector>(_inspectorType)) return;
     var inspector = TypeHelper.CreateInstance<IClientMessageInspector>(_inspectorType);
     clientRuntime.MessageInspectors.Add(inspector);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="contractDescription"></param>
 /// <param name="endpoint"></param>
 /// <param name="dispatchRuntime">The runtime object that can be used to modify the default service behavior.</param>
 public void ApplyDispatchBehavior(
     ContractDescription contractDescription,
     ServiceEndpoint endpoint,
     DispatchRuntime dispatchRuntime)
 {
     dispatchRuntime.InstanceProvider = this;   // set the provider to manage service objects instantiation
 }
 public static void ComputeContractRequirements(ContractDescription contractDescription, out ChannelRequirements requirements)
 {
     requirements = new ChannelRequirements();
     requirements.usesInput = false;
     requirements.usesReply = false;
     requirements.usesOutput = false;
     requirements.usesRequest = false;
     requirements.sessionMode = contractDescription.SessionMode;
     for (int i = 0; i < contractDescription.Operations.Count; i++)
     {
         OperationDescription description = contractDescription.Operations[i];
         bool isOneWay = description.IsOneWay;
         if (!description.IsServerInitiated())
         {
             if (isOneWay)
             {
                 requirements.usesInput = true;
             }
             else
             {
                 requirements.usesReply = true;
             }
         }
         else if (isOneWay)
         {
             requirements.usesOutput = true;
         }
         else
         {
             requirements.usesRequest = true;
         }
     }
 }
		void IContractBehavior.AddBindingParameters (
			ContractDescription description,
			ServiceEndpoint endpoint,
			BindingParameterCollection parameters)
		{
			throw new NotImplementedException ();
		}
            internal MethodInfoOperationSelector(ContractDescription description, MessageDirection directionThatRequiresClientOpSelection)
            {
                operationMap = new Dictionary<object, string>();

                for (int i = 0; i < description.Operations.Count; i++)
                {
                    OperationDescription operation = description.Operations[i];
                    if (operation.Messages[0].Direction == directionThatRequiresClientOpSelection)
                    {
                        if (operation.SyncMethod != null)
                        {
                            if (!operationMap.ContainsKey(operation.SyncMethod.MethodHandle))
                                operationMap.Add(operation.SyncMethod.MethodHandle, operation.Name);
                        }
    
                        if (operation.BeginMethod != null)
                        {
                            if (!operationMap.ContainsKey(operation.BeginMethod.MethodHandle))
                            {
                                operationMap.Add(operation.BeginMethod.MethodHandle, operation.Name);
                                operationMap.Add(operation.EndMethod.MethodHandle, operation.Name);                    
                            }
                        }

                        if (operation.TaskMethod != null)
                        {
                            if (!operationMap.ContainsKey(operation.TaskMethod.MethodHandle))
                            {
                                operationMap.Add(operation.TaskMethod.MethodHandle, operation.Name);
                            }
                        }
                    }
                }
            }
        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            var behavior =
                dispatchRuntime.ChannelDispatcher.Host.Description.FindBehavior
                        <WebAuthenticationConfigurationBehavior,
                         WebAuthenticationConfigurationAttribute>(b => b.BaseBehavior);

            if (behavior == null)
                behavior = contractDescription.FindBehavior
                        <WebAuthenticationConfigurationBehavior,
                         WebAuthenticationConfigurationAttribute>(b => b.BaseBehavior);

            if (behavior == null)
                throw new ServiceAuthenticationConfigurationMissingException();

            var authorizationBehavior =
                dispatchRuntime.ChannelDispatcher.Host.Description.FindBehavior
                        <WebAuthorizationConfigurationBehavior,
                        WebAuthorizationConfigurationAttribute>(b => b.BaseBehavior);

            Type authorizationPolicy = null;
            if (authorizationBehavior != null)
                authorizationPolicy = authorizationBehavior.AuthorizationPolicyType;

            foreach (var endpointDispatcher in dispatchRuntime.ChannelDispatcher.Endpoints)
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
                    new ServiceAuthenticationInspector(
                        behavior.ThrowIfNull().AuthenticationHandler,
                        behavior.UsernamePasswordValidatorType,
                        behavior.RequireSecureTransport,
                        behavior.Source,
                        authorizationPolicy));
        }
 /// <summary>
 /// 注册 服务实例创建提供者,将基于PIAB的实例生成器注入WCF扩展
 /// </summary>
 /// <param name="contractDescription"></param>
 /// <param name="endpoint"></param>
 /// <param name="dispatchRuntime"></param>
 public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                   DispatchRuntime dispatchRuntime)
 {
     Type serviceContractType = contractDescription.ContractType;
     dispatchRuntime.InstanceProvider = new PolicyInjectionInstanceProvider(serviceContractType,
                                                                            this.PolicyInjectorName);
 }
 public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
 {
   if (dispatchRuntime == null)
     throw new ArgumentNullException("dispatchRuntime");
   dispatchRuntime.InstanceProvider = this.instanceProvider;
   dispatchRuntime.InstanceContextInitializers.Add((IInstanceContextInitializer) new UnityInstanceContextInitializer());
 }
 void IContractBehavior.ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, DispatchRuntime dispatch)
 {
     if (dispatch.ClientRuntime != null)
     {
         dispatch.ClientRuntime.OperationSelector = new MethodInfoOperationSelector(description, MessageDirection.Output);
     }
 }
 internal static ComProxy Create(IntPtr outer, ContractDescription contract, IProvideChannelBuilderSettings channelBuilderSettings)
 {
     DispatchProxy proxy = null;
     ComProxy proxy3;
     IntPtr zero = IntPtr.Zero;
     ComProxy proxy2 = null;
     try
     {
         proxy = new DispatchProxy(contract, channelBuilderSettings);
         zero = OuterProxyWrapper.CreateDispatchProxy(outer, proxy);
         proxy2 = new ComProxy(zero, proxy);
         proxy3 = proxy2;
     }
     finally
     {
         if (proxy2 == null)
         {
             if (proxy != null)
             {
                 ((IDisposable) proxy).Dispose();
             }
             if (zero != IntPtr.Zero)
             {
                 Marshal.Release(zero);
             }
         }
     }
     return proxy3;
 }
 public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
 {
     if (endpoint.Binding.CreateBindingElements().Find<MessageEncodingBindingElement>() == null)
     {
         bindingParameters.Add(new BinaryMessageEncodingBindingElement());
     }
 }
 public void ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatch)
 {
     foreach (OperationDescription opDesc in description.Operations)
     {
         ApplyDataContractSurrogate(opDesc);
     }
 }
        static void FillContract(IWmiInstance contract, ContractDescription contractDescription)
        {
            Fx.Assert(null != contractDescription, "contractDescription cannot be null");
            contract.SetProperty(AdministrationStrings.Type, contractDescription.ContractType.Name);
            if (null != contractDescription.CallbackContractType)
            {
                contract.SetProperty(AdministrationStrings.CallbackContract, ContractReference(contractDescription.CallbackContractType.Name));
            }

            contract.SetProperty(AdministrationStrings.Name, contractDescription.Name);
            contract.SetProperty(AdministrationStrings.Namespace, contractDescription.Namespace);
            contract.SetProperty(AdministrationStrings.SessionMode, contractDescription.SessionMode.ToString());

            IWmiInstance[] operations = new IWmiInstance[contractDescription.Operations.Count];
            for (int j = 0; j < operations.Length; ++j)
            {
                OperationDescription operationDescription = contractDescription.Operations[j];
                Fx.Assert(operationDescription.Messages.Count > 0, "");
                IWmiInstance operation = contract.NewInstance(AdministrationStrings.Operation);
                FillOperation(operation, operationDescription);
                operations[j] = operation;

            }
            contract.SetProperty(AdministrationStrings.Operations, operations);
            FillBehaviorsInfo(contract, contractDescription.Behaviors);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="contractDescription"></param>
 /// <param name="endpoint"></param>
 /// <param name="clientRuntime"></param>
 public void ApplyClientBehavior(
     ContractDescription contractDescription,
     ServiceEndpoint endpoint,
     ClientRuntime clientRuntime)
 {
     // empty
 }
		void IContractBehavior.ApplyDispatchBehavior (
			ContractDescription description,
			ServiceEndpoint endpoint,
			DispatchRuntime dispatch)
		{
			throw new NotImplementedException ();
		}
		void IContractBehavior.ApplyClientBehavior (
			ContractDescription description,
			ServiceEndpoint endpoint,
			ClientRuntime proxy)
		{
			throw new NotImplementedException ();
		}
        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)
        {
            // We iterate over the operation descriptions in the contract and
            // try to locate an DispatchBodyElementAttribute behaviors on each
            // operation. If found, we add the operation, keyed by QName of the body element
            // that selects which calls shall be dispatched to this operation to a
            // dictionary.
            Dictionary<XmlQualifiedName,string> dispatchDictionary = new Dictionary<XmlQualifiedName,string>();
            foreach( OperationDescription operationDescription in contractDescription.Operations )
            {
                DispatchBodyElementAttribute dispatchBodyElement =
                    operationDescription.Behaviors.Find<DispatchBodyElementAttribute>();
                if ( dispatchBodyElement != null )
                {
                    dispatchDictionary.Add(dispatchBodyElement.QName, operationDescription.Name);
                }
            }

            // Lastly, we create and assign and instance of our operation selector that
            // gets the dispatch dictionary we've just created.
            dispatchRuntime.OperationSelector =
                new DispatchByBodyElementOperationSelector(
                   dispatchDictionary,
                   dispatchRuntime.UnhandledDispatchOperation.Name);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="contractDescription"></param>
 /// <param name="endpoint"></param>
 /// <param name="bindingParameters"></param>
 public void AddBindingParameters(
     ContractDescription contractDescription,
     ServiceEndpoint endpoint,
     BindingParameterCollection bindingParameters)
 {
     // empty
 }
        /// <summary>
        /// Implement to confirm that the contract and endpoint can support the contract behavior.
        /// </summary>
        /// <param name="contractDescription">The contract to validate.</param>
        /// <param name="endpoint">The endpoint to validate.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="contractDescription"/> is <c>null</c>.</exception>
        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
            Argument.IsNotNull("contractDescription", contractDescription);

            var messageDescriptions = contractDescription.Operations.SelectMany(operationDescription => operationDescription.Messages);

            foreach (var messageDescription in messageDescriptions)
            {
                ValidateMessagePartDescription(messageDescription.Body.ReturnValue);

                var messagePartDescriptions = messageDescription.Body.Parts;

                foreach (var messagePartDescription in messagePartDescriptions)
                {
                    ValidateMessagePartDescription(messagePartDescription);
                }

                var messageHeaderDescriptions = messageDescription.Headers;

                foreach (var messageHeaderDescription in messageHeaderDescriptions)
                {
                    ValidateBinarySerializableType(messageHeaderDescription.Type);
                }
            }
        }
 public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                   DispatchRuntime dispatchRuntime)
 {
     if (!TypeHelper.IsTypeOf<IDispatchMessageInspector>(_inspectorType)) return;
     var inspector = TypeHelper.CreateInstance<IDispatchMessageInspector>(_inspectorType);
     dispatchRuntime.MessageInspectors.Add(inspector);
 }
        internal static ComProxy Create(IntPtr outer, ContractDescription contract, IProvideChannelBuilderSettings channelBuilderSettings)
        {
            DispatchProxy proxy = null;
            IntPtr inner = IntPtr.Zero;
            ComProxy comProxy = null;
            try
            {
                proxy = new DispatchProxy(contract, channelBuilderSettings);
                inner = OuterProxyWrapper.CreateDispatchProxy(outer, proxy);
                comProxy = new ComProxy(inner, proxy);
                return comProxy;

            }
            finally
            {
                if (comProxy == null)
                {
                    if (proxy != null)
                    {
                        ((IDisposable)proxy).Dispose();
                    }
                    if (inner != IntPtr.Zero)
                    {
                        Marshal.Release(inner);
                    }
                }

            }


        }
 internal void CreateMyDataContractSerializerOperationBehaviors(ContractDescription contractDescription)
 {
     foreach (var operation in contractDescription.Operations)
     {
         CreateMyDataContractSerializerOperationBehavior(operation);
     }
 }
		public OperationDescription (string name,
			ContractDescription declaringContract)
		{
			this.name = name;
			contract = declaringContract;
			is_initiating = true;
		}
        /// <summary>
        /// Add the Ping method to the existing contract
        /// </summary>
        private void AddPingToContractDescription(ContractDescription contractDescription)
        {
            OperationDescription pingOperationDescription = new OperationDescription(PingOperationName, contractDescription);

            MessageDescription inputMessageDescription = new MessageDescription(
                GetAction(contractDescription, PingOperationName),
                MessageDirection.Input);

            MessageDescription outputMessageDescription = new MessageDescription(
                GetAction(contractDescription, PingResponse),
                MessageDirection.Output);

            MessagePartDescription returnValue = new MessagePartDescription("PingResult", contractDescription.Namespace);

            returnValue.Type = typeof(DateTime);
            outputMessageDescription.Body.ReturnValue = returnValue;

            inputMessageDescription.Body.WrapperName = PingOperationName;
            inputMessageDescription.Body.WrapperNamespace = contractDescription.Namespace;
            outputMessageDescription.Body.WrapperName = PingResponse;
            outputMessageDescription.Body.WrapperNamespace = contractDescription.Namespace;

            pingOperationDescription.Messages.Add(inputMessageDescription);
            pingOperationDescription.Messages.Add(outputMessageDescription);

            pingOperationDescription.Behaviors.Add(new DataContractSerializerOperationBehavior(pingOperationDescription));
            pingOperationDescription.Behaviors.Add(new PingOperationBehavior());

            contractDescription.Operations.Add(pingOperationDescription);
        }
Beispiel #31
0
 public ClientRuntimeChannel(System.ServiceModel.Dispatcher.ClientRuntime runtime, ContractDescription contract, TimeSpan openTimeout, TimeSpan closeTimeout, IChannel contextChannel, IChannelFactory factory, MessageVersion messageVersion, System.ServiceModel.EndpointAddress remoteAddress, Uri via)
 {
     if (runtime == null)
     {
         throw new ArgumentNullException("runtime");
     }
     if (messageVersion == null)
     {
         throw new ArgumentNullException("messageVersion");
     }
     this.runtime        = runtime;
     this.remote_address = remoteAddress;
     if (runtime.Via == null)
     {
         runtime.Via = via ?? (remote_address != null ? remote_address.Uri : null);
     }
     this.contract         = contract;
     this.message_version  = messageVersion;
     default_open_timeout  = openTimeout;
     default_close_timeout = closeTimeout;
     _processDelegate      = new ProcessDelegate(Process);
     requestDelegate       = new RequestDelegate(Request);
     sendDelegate          = new SendDelegate(Send);
     AllowInitializationUI = true;
     if (contextChannel != null)
     {
         channel = contextChannel;
     }
     else
     {
         var method = factory.GetType().GetMethod("CreateChannel", new Type[] {
             typeof(System.ServiceModel.EndpointAddress),
             typeof(Uri)
         });
         try
         {
             channel = (IChannel)method.Invoke(factory, new object[] {
                 remote_address,
                 Via
             });
             this.factory = factory;
         }
         catch (System.Reflection.TargetInvocationException ex)
         {
             if (ex.InnerException != null)
             {
                 throw ex.InnerException;
             }
             else
             {
                 throw;
             }
         }
     }
 }
 internal WebServiceEndpoint(ContractDescription contract, EndpointAddress address)
     : base(contract, new WebHttpBinding(), address)
 {
     Behaviors.Add(new WebHttpBehavior());
 }
Beispiel #33
0
 public ServiceEndpoint(ContractDescription contract)
 {
     _contract = contract ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contract));
 }
Beispiel #34
0
 public ServiceEndpoint(ContractDescription contract, Binding binding, EndpointAddress address)
 {
     _contract = contract ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contract));
     Binding   = binding;
     Address   = address;
 }