Ejemplo n.º 1
0
 public DataContractSerializerOperationFormatter(OperationDescription description, DataContractFormatAttribute dataContractFormatAttribute, DataContractSerializerOperationBehavior serializerFactory) : base(description, dataContractFormatAttribute.Style == OperationFormatStyle.Rpc, false)
 {
     if (description == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
     }
     this.serializerFactory = serializerFactory ?? new DataContractSerializerOperationBehavior(description);
     foreach (System.Type type in description.KnownTypes)
     {
         if (this.knownTypes == null)
         {
             this.knownTypes = new List <System.Type>();
         }
         if (type == null)
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxKnownTypeNull", new object[] { description.Name })));
         }
         this.ValidateDataContractType(type);
         this.knownTypes.Add(type);
     }
     this.requestMessageInfo = this.CreateMessageInfo(dataContractFormatAttribute, base.RequestDescription, this.serializerFactory);
     if (base.ReplyDescription != null)
     {
         this.replyMessageInfo = this.CreateMessageInfo(dataContractFormatAttribute, base.ReplyDescription, this.serializerFactory);
     }
 }
Ejemplo n.º 2
0
        public static IwrService GetService()
        {
            try
            {
                wrService ws = new wrService();
                foreach (var item in ws.Endpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dc = item.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                    if (dc != null)
                    {
                        dc.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }

                return(ws.GetChannel());
                //return new wrService().GetChannel();
            }
            catch (System.Exception ex)
            {
                if (log == null)
                {
                    log = LogService.Getlog(typeof(wrService));
                }

                log.Error(ex);

                throw;
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string ipAdress = ConfigurationManager.AppSettings["ipAdress"];

            new System.Threading.Thread(() =>
            {
                ChatToClient server             = new ChatToClient();
                server.ReceiveMsgEvent         += server_ReceiveMsgEvent;
                server.ReceiveImageEvent       += server_ReceiveImageEvent;
                server.ReceiveFriendListEvent  += GetOrUpdateFriendList;
                InstanceContext context         = new InstanceContext(server);
                WSDualHttpBinding bingding      = new WSDualHttpBinding();
                bingding.MaxReceivedMessageSize = Int32.MaxValue;
                bingding.MaxBufferPoolSize      = Int32.MaxValue;
                bingding.OpenTimeout            = new TimeSpan(0, 20, 0);
                bingding.SendTimeout            = new TimeSpan(0, 20, 0);
                //必须加上,否则传输大文件有问题..
                bingding.ReaderQuotas.MaxDepth = int.MaxValue;
                bingding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                bingding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
                bingding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
                bingding.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;

                //安全性
                bingding.UseDefaultWebProxy = false;
                bingding.Security.Message.ClientCredentialType = MessageCredentialType.None;
                bingding.Security.Mode = WSDualHttpSecurityMode.None;

                factory = new DuplexChannelFactory <IChatToServer>(context, bingding, new EndpointAddress(ipAdress));
                foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }
                try
                {
                    client = factory.CreateChannel();
                    client.Login(UserName);
                    client.GetFriendList();
                    UpdateText(DateTime.Now.ToString() + "  已经与服务器连接..", Colors.Gray, true);
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.loadingFrame.Visibility = System.Windows.Visibility.Collapsed;
                        this.mainGrid.Visibility     = System.Windows.Visibility.Visible;
                    }));
                }
                catch (Exception ee)
                {
                    UpdateText(DateTime.Now.ToString() + "  " + ee.Message + "\r\n请重启客户端重新来连接", Colors.Red, true);
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.loadingFrame.Visibility = System.Windows.Visibility.Collapsed;
                        this.mainGrid.Visibility     = System.Windows.Visibility.Visible;
                    }));
                }
            }).Start();
        }
Ejemplo n.º 4
0
        void ConfigureOperationDescriptionBehaviors(OperationDescription operation, IDataContractSurrogate contractSurrogate)
        {
            // DataContractSerializerOperationBehavior
            DataContractSerializerOperationBehavior contractSerializer = new DataContractSerializerOperationBehavior(operation, TypeLoader.DefaultDataContractFormatAttribute);

            if (null != contractSurrogate)
            {
                contractSerializer.DataContractSurrogate = contractSurrogate;
            }

            operation.Behaviors.Add(contractSerializer);

            // OperationInvokerBehavior
            operation.Behaviors.Add(new OperationInvokerBehavior());

            if (info.TransactionOption == TransactionOption.Supported || info.TransactionOption == TransactionOption.Required)
            {
                operation.Behaviors.Add(new TransactionFlowAttribute(TransactionFlowOption.Allowed));
            }

            // OperationBehaviorAttribute
            OperationBehaviorAttribute operationBehaviorAttribute = new OperationBehaviorAttribute();

            operationBehaviorAttribute.TransactionAutoComplete  = true;
            operationBehaviorAttribute.TransactionScopeRequired = false;
            operation.Behaviors.Add(operationBehaviorAttribute);
        }
Ejemplo n.º 5
0
        protected ChannelFactory <T> ExtendChannelFactory <T>(ChannelFactory <T> channelFactory)
        {
#if !SILVERLIGHT
            foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = (DataContractSerializerOperationBehavior)op.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dataContractBehavior == null)
                {
                    dataContractBehavior = new DataContractSerializerOperationBehavior(op);
                    op.Behaviors.Add(dataContractBehavior);
                }
                dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
            }
#endif
            //ZipClientMessageInspector compressBehavior = (ZipClientMessageInspector)channelFactory.Endpoint.Behaviors.Find<ZipClientMessageInspector>();
            //if (compressBehavior == null)
            //{
            //    compressBehavior = new ZipClientMessageInspector();
            //    channelFactory.Endpoint.Behaviors.Add(compressBehavior);
            //}

            MaxFaultSizeBehavior maxfaultSizeBehavior = new MaxFaultSizeBehavior(int.MaxValue);
            channelFactory.Endpoint.Behaviors.Add(maxfaultSizeBehavior);

            return(channelFactory);
        }
Ejemplo n.º 6
0
        //<snippet1>
        private void DataContractBehavior()
        {
            WSHttpBinding b           = new WSHttpBinding(SecurityMode.Message);
            Uri           baseAddress = new Uri("http://localhost:1066/calculator");
            ServiceHost   sh          = new ServiceHost(typeof(Calculator), baseAddress);

            sh.AddServiceEndpoint(typeof(ICalculator), b, "");

            // Find the ContractDescription of the operation to find.
            ContractDescription  cd = sh.Description.Endpoints[0].Contract;
            OperationDescription myOperationDescription = cd.Operations.Find("Add");

            // Find the serializer behavior.
            DataContractSerializerOperationBehavior serializerBehavior =
                myOperationDescription.Behaviors.
                Find <DataContractSerializerOperationBehavior>();

            // If the serializer is not found, create one and add it.
            if (serializerBehavior == null)
            {
                serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
                myOperationDescription.Behaviors.Add(serializerBehavior);
            }

            // Change the settings of the behavior.
            serializerBehavior.MaxItemsInObjectGraph     = 10000;
            serializerBehavior.IgnoreExtensionDataObject = true;

            sh.Open();
            Console.WriteLine("Listening");
            Console.ReadLine();
        }
        /// <summary>
        /// 构造文件传输的服务地址
        /// </summary>
        /// <returns></returns>
        public static IFileTransportService CreateChannelFileTransportService()
        {
            if (ConfigurationManager.ConnectionStrings["EndpointAddress"] != null)
            {
                readerOperateEndpointAddress = SeatManageComm.AESAlgorithm.AESDecrypt(ConfigurationManager.ConnectionStrings["EndpointAddress"].ConnectionString);
            }
            else
            {
                // throw new Exception("未设置远程服务连接字符串");
            }

            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            binding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            string endPointAddress = readerOperateEndpointAddress + "TransportService/";
            ChannelFactory <IFileTransportService> proxy = new ChannelFactory <IFileTransportService>(binding, new EndpointAddress(endPointAddress));

            foreach (OperationDescription op in proxy.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }
            IFileTransportService obj = proxy.CreateChannel();

            return(obj);
        }
Ejemplo n.º 8
0
        private static void SetSerializerForJsonFormatter(HttpOperationDescription operation, Type type, string name, MediaTypeFormatterCollection formatters)
        {
            Fx.Assert(operation != null, "The 'operation' parameter should not be null.");
            Fx.Assert(type != null, "The 'type' parameter should not be null.");
            Fx.Assert(name != null, "The 'name' parameter should not be null.");
            Fx.Assert(formatters != null, "The 'formatters' parameter should not be null.");

            JsonMediaTypeFormatter jsonFormatter = formatters.JsonFormatter;

            if (jsonFormatter != null)
            {
                DataContractJsonSerializer jsonSerializer = null;
                DataContractSerializerOperationBehavior dataContractSerializerBehavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dataContractSerializerBehavior != null)
                {
                    jsonSerializer = new DataContractJsonSerializer(
                        type,
                        operation.KnownTypes,
                        dataContractSerializerBehavior.MaxItemsInObjectGraph,
                        dataContractSerializerBehavior.IgnoreExtensionDataObject,
                        dataContractSerializerBehavior.DataContractSurrogate,
                        false);
                }
                else
                {
                    jsonSerializer = new DataContractJsonSerializer(type, "root", operation.KnownTypes);
                }

                jsonFormatter.SetSerializer(type, jsonSerializer);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Uses <see cref="WcfDataContractResolverConfiguration.GetDataContracts{TService}"/>
        /// to find <see cref="DataContractResolver">resolvers</see> to automatically attach to each
        /// <see cref="OperationDescription"/> in <see cref="ContractDescription.Operations"/> of <see cref="ServiceEndpoint.Contract"/> of the provided <paramref name="endpoint"/>.
        /// </summary>
        protected virtual void AttachDataContractResolver(ServiceEndpoint endpoint)
        {
            ContractDescription contractDescription = endpoint.Contract;

            foreach (OperationDescription operationDescription in contractDescription.Operations)
            {
                Type dataContractType = WcfDataContractResolverConfiguration.Current.GetDataContracts <TService>(operationDescription.Name);
                if (dataContractType == null)
                {
                    continue;
                }
                DataContractSerializerOperationBehavior serializerBehavior = operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (serializerBehavior == null)
                {
                    operationDescription.Behaviors.Add(serializerBehavior = new DataContractSerializerOperationBehavior(operationDescription));
                }
                                #if NET40
                serializerBehavior.DataContractResolver = (DataContractResolver)Activator.CreateInstance(AppDomain.CurrentDomain, dataContractType.Assembly.FullName, dataContractType.FullName).Unwrap();
                                #endif
                                #if NETSTANDARD2_0
                serializerBehavior.DataContractResolver = (DataContractResolver)DotNetStandard2Helper.CreateInstanceFrom(dataContractType.Assembly.FullName, dataContractType.FullName);
                                #endif
                                #if NETCOREAPP3_0
                serializerBehavior.DataContractResolver = (DataContractResolver)Activator.CreateInstance(dataContractType.Assembly.FullName, dataContractType.FullName).Unwrap();
                                #endif
            }
        }
Ejemplo n.º 10
0
 private void Run()
 {
     //<snippet8>
     using (ServiceHost serviceHost = new ServiceHost(typeof(InventoryCheck)))
         foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints)
         {
             foreach (OperationDescription op in ep.Contract.Operations)
             {
                 DataContractSerializerOperationBehavior dataContractBehavior =
                     op.Behaviors.Find <DataContractSerializerOperationBehavior>()
                     as DataContractSerializerOperationBehavior;
                 if (dataContractBehavior != null)
                 {
                     dataContractBehavior.DataContractSurrogate = new InventorySurrogated();
                 }
                 else
                 {
                     dataContractBehavior = new DataContractSerializerOperationBehavior(op);
                     dataContractBehavior.DataContractSurrogate = new InventorySurrogated();
                     op.Behaviors.Add(dataContractBehavior);
                 }
             }
         }
     //</snippet8>
 }
Ejemplo n.º 11
0
        private static TService HttpCreate <TService>(string uri, int TimeOut)
        {
            WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();

            binding.SendTimeout            = TimeSpan.FromSeconds(TimeOut);
            binding.ReceiveTimeout         = TimeSpan.FromSeconds(TimeOut);
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;

            #region  设置一些配置信息
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            #endregion

            #region  务令牌处理

            string          token          = string.Empty;
            AddressHeader[] addressHeaders = new AddressHeader[] { };

            if (string.IsNullOrEmpty(token) && OperationContext.Current != null)
            {
                int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("token", "");
                if (index >= 0)
                {
                    token = OperationContext.Current.IncomingMessageHeaders.GetHeader <string>(index);
                }
            }
            if (string.IsNullOrEmpty(token) && WebOperationContext.Current != null)
            {
                if (WebOperationContext.Current.IncomingRequest.Headers["token"] != null)
                {
                    token = WebOperationContext.Current.IncomingRequest.Headers["token"].ToString();
                }
            }
            if (!string.IsNullOrEmpty(token))
            {
                //若存在令牌,则继续添加令牌,不存在,则不管令牌
                AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("token", "", token);
                addressHeaders = new AddressHeader[] { addressHeader1 };
            }

            #endregion

            EndpointAddress endpoint = new EndpointAddress(new Uri(uri), addressHeaders);

            ChannelFactory <TService> channelfactory = new ChannelFactory <TService>(binding, endpoint);
            //返回工厂创建MaxItemsInObjectGraph
            foreach (OperationDescription op in channelfactory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }
            TService tservice = channelfactory.CreateChannel();
            return(tservice);
        }
        private static string pocketBespeakBllServiceEndpointAddress;// = ConfigurationManager.ConnectionStrings["EndpointAddress"].ConnectionString;
        public static IPocketBespeakBllService CreateChannelPocketBespeakBllService(string connStr)
        {
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            binding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.CloseTimeout           = new TimeSpan(0, 10, 0);
            string endPointAddress = connStr + "PocketBespeakBllService/";
            ChannelFactory <IPocketBespeakBllService> proxy = new ChannelFactory <IPocketBespeakBllService>(binding, new EndpointAddress(endPointAddress));

            foreach (OperationDescription op in proxy.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }
            IPocketBespeakBllService obj = proxy.CreateChannel();

            return(obj);
        }
        public DataContractSerializerOperationFormatter(OperationDescription description, DataContractFormatAttribute dataContractFormatAttribute,
                                                        DataContractSerializerOperationBehavior serializerFactory)
            : base(description, dataContractFormatAttribute.Style == OperationFormatStyle.Rpc, false /*isEncoded*/)
        {
            if (description == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(description));
            }

            _serializerFactory = serializerFactory ?? new DataContractSerializerOperationBehavior(description);
            foreach (Type type in description.KnownTypes)
            {
                if (_knownTypes == null)
                {
                    _knownTypes = new List <Type>();
                }

                if (type == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxKnownTypeNull, description.Name)));
                }

                ValidateDataContractType(type);
                _knownTypes.Add(type);
            }
            requestMessageInfo = CreateMessageInfo(dataContractFormatAttribute, RequestDescription, _serializerFactory);
            if (ReplyDescription != null)
            {
                replyMessageInfo = CreateMessageInfo(dataContractFormatAttribute, ReplyDescription, _serializerFactory);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Phương thức khởi tạo
        /// </summary>
        static UtilitiesProcess()
        {
            EndpointAddress  endpointAddressTruyVan  = Common.Utilities.getEndpointAddress(ApplicationConstant.SystemService.TruyVanService.layGiaTri());
            BasicHttpBinding basicHttpBindingTruyVan = Common.Utilities.getBasicHttpBinding(ApplicationConstant.SystemService.TruyVanService.layGiaTri());

            ClientTruyVan = new TruyVanServiceClient(basicHttpBindingTruyVan, endpointAddressTruyVan);

            foreach (var operationDescription in ClientTruyVan.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dcsob =
                    operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dcsob != null)
                {
                    dcsob.MaxItemsInObjectGraph = 2147483646;
                }
            }

            //Client = new UtilitiesServiceClient();
            EndpointAddress  endpointAddress  = Common.Utilities.getEndpointAddress(ApplicationConstant.SystemService.UtilitiesService.layGiaTri());
            BasicHttpBinding basicHttpBinding = Common.Utilities.getBasicHttpBinding(ApplicationConstant.SystemService.UtilitiesService.layGiaTri());

            Client = new UtilitiesServiceClient(basicHttpBinding, endpointAddress);

            foreach (var operationDescription in Client.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dcsob =
                    operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dcsob != null)
                {
                    dcsob.MaxItemsInObjectGraph = 2147483646;
                }
            }
        }
Ejemplo n.º 15
0
        protected static T CreateClient <T>(Binding binding, EndpointAddress address)
        {
            if (binding == null)
            {
                binding = new NetMsmqBinding(NetMsmqSecurityMode.None);
            }

            ChannelFactory <T> factory = new ChannelFactory <T>(binding, address);
            T service = factory.CreateChannel();
            ContractDescription cd = factory.Endpoint.Contract;

            // TODO: We should only attach a TaskDataContractResolver for operations that actually require it.
            foreach (OperationDescription operationDescription in cd.Operations)
            {
                DataContractSerializerOperationBehavior serializerBehavior = operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (serializerBehavior == null)
                {
                    serializerBehavior = new DataContractSerializerOperationBehavior(operationDescription);
                    operationDescription.Behaviors.Add(serializerBehavior);
                }
                serializerBehavior.DataContractResolver = new SchedulerTaskDataContractResolver();
            }

            return(service);
        }
Ejemplo n.º 16
0
        private static ServiceHost Start()
        {
            var sh = new ServiceHost(typeof(MyService2));

            sh.Closing += SVClose;
            sh.Open();

            sh          = new ServiceHost(typeof(MyService));
            sh.Closing += SVClose;
            sh.Open();

            sh = new ServiceHost(typeof(CommonCRUDService));
            var cd = sh.Description.Endpoints[0].Contract;
            //查找的是需要更改数据契约
            var myOperationDescription = cd.Operations.Find("Add");

            var serializerBehavior = myOperationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();

            if (serializerBehavior == null)
            {
                serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
                myOperationDescription.Behaviors.Add(serializerBehavior);
            }
            serializerBehavior.DataContractResolver = new MyDataContractResolver(typeof(CommonCRUDService).Assembly);

            sh.Open();
            //var result = PolicyInjection.Create<MyService>();
            ////var result = PolicyInjection.Wrap<MyService>(serviceInstance);
            //result.DoWork();

            return(sh);
        }
Ejemplo n.º 17
0
        private static IType CreateBLLFromWCF(string WcfUrl)
        {
            BasicHttpBinding          m_Binding      = new BasicHttpBinding();
            XmlDictionaryReaderQuotas m_ReaderQuotas = new XmlDictionaryReaderQuotas();

            m_Binding.MaxReceivedMessageSize      = int.MaxValue;
            m_Binding.MaxBufferPoolSize           = int.MaxValue;
            m_Binding.MaxBufferSize               = int.MaxValue;
            m_Binding.SendTimeout                 = new TimeSpan(1, 1, 1);
            m_ReaderQuotas.MaxArrayLength         = int.MaxValue;
            m_ReaderQuotas.MaxStringContentLength = int.MaxValue;
            m_ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            m_ReaderQuotas.MaxDepth               = 32;
            m_ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;
            m_Binding.ReaderQuotas                = m_ReaderQuotas;

            EndpointAddress endaddress = new EndpointAddress(WcfUrl);

            ChannelFactory <IType> channelFactory = new ChannelFactory <IType>(m_Binding);

            foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            IType t;

            t = channelFactory.CreateChannel(endaddress);
            return(t);
        }
Ejemplo n.º 18
0
        private string Variation_Service_BaseDataContractMethod(string clientString)
        {
            // Create the proxy
            var httpBinding = ClientHelper.GetBufferedModeBinding();

            System.ServiceModel.ChannelFactory <ClientContract.ISanityAParentB_857419_ContractBase> channelFactory = new System.ServiceModel.ChannelFactory <ClientContract.ISanityAParentB_857419_ContractBase>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/basichttp.svc")));


            // var clientProxy = this.GetProxy<ClientContract.ISanityAParentB_857419_ContractBase>();
            foreach (var operation in channelFactory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior behavior =
                    operation.OperationBehaviors.FirstOrDefault(
                        x => x.GetType() == typeof(DataContractSerializerOperationBehavior)) as DataContractSerializerOperationBehavior;
                behavior.DataContractResolver = new ManagerDataContractResolver <ClientContract.MyBaseDataType>();
            }
            var clientProxy = channelFactory.CreateChannel();

            // Send the two way message
            _output.WriteLine("Testing [Variation_Service_BaseTwoWayMethod]");
            var dataObj = new ClientContract.MyBaseDataType();

            dataObj.data = clientString;

            var    result   = (ClientContract.MyBaseDataType)clientProxy.DataContractMethod(dataObj);
            string response = result.data;

            _output.WriteLine($"Testing [Variation_Service_BaseTwoWayMethod] returned <{response}>");
            return(response);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the HpcSchedulerAdapterClient class
        /// </summary>
        /// <param name="headnode">indicating the headnode</param>
        /// <param name="instanceContext">indicating the instance context</param>
        public HpcSchedulerAdapterClient(string headnode, string certThrumbprint, InstanceContext instanceContext)
            : base(
                instanceContext,
                BindingHelper.HardCodedInternalSchedulerDelegationBinding,
                SoaHelper.CreateInternalCertEndpointAddress(new Uri(SoaHelper.GetSchedulerDelegationAddress(headnode)), certThrumbprint))
        {
            BrokerTracing.TraceVerbose("[HpcSchedulerAdapterClient] In constructor");
            this.ClientCredentials.UseInternalAuthentication(certThrumbprint);
            if (BrokerIdentity.IsHAMode)
            {
                // Bug 10301 : Explicitly open channel when impersonating the resource group's account if running on failover cluster so identity flows correctly when
                //      calling HpcSession.
                //  NOTE: The patch we got from the WCF team (KB981001) only works when the caller is on a threadpool thread.
                //  NOTE: Channel must be opened before setting OperationTimeout
                using (BrokerIdentity identity = new BrokerIdentity())
                {
                    identity.Impersonate();
                    this.Open();
                }
            }

            this.InnerChannel.OperationTimeout = SchedulerAdapterTimeout;

            foreach (OperationDescription op in this.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }
        }
        /// <summary>
        /// 初始化被调用的服务点对象
        /// </summary>
        /// <param name="bindingName">指定特定的Binding Name , 在addressing/binding下</param>
        public ServiceAgent(string bindingName)
        {
            var contractDescription = ContractDescription.GetContract(typeof(T));

            //TODO: handle exception like not found or configuration error
            KeyValuePair <string, Binding> hostService;

            if (String.IsNullOrEmpty(bindingName))
            {
                hostService = ServiceConfiguration.GetDefaultBindingConfiguration(typeof(T));
            }
            else
            {
                hostService = ServiceConfiguration.GetBindingConfiguration(bindingName, typeof(T));
            }

            _ServiceAddress  = hostService.Key;
            _ServiceEndpoint = new ServiceEndpoint(contractDescription, hostService.Value, new EndpointAddress(hostService.Key));

            // Find the ContractDescription of the operation to find.
            foreach (OperationDescription operDesc in contractDescription.Operations)
            {
                // Find the serializer behavior.
                var serializerBehavior = operDesc.Behaviors.Find <DataContractSerializerOperationBehavior>();
                // If the serializer is not found, create one and add it.
                if (serializerBehavior == null)
                {
                    serializerBehavior = new DataContractSerializerOperationBehavior(operDesc);
                    operDesc.Behaviors.Add(serializerBehavior);
                }
                // Change the settings of the behavior.
                serializerBehavior.MaxItemsInObjectGraph     = Int32.MaxValue - 1;
                serializerBehavior.IgnoreExtensionDataObject = true;
            }
        }
Ejemplo n.º 21
0
        void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase host)
        {
            foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
            {
                foreach (OperationDescription operation in endpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();

                    if (behavior == null)
                    {
                        behavior = new DataContractSerializerOperationBehavior(operation)
                        {
                            DataContractSurrogate = this.surrogate
                        };

                        operation.Behaviors.Add(behavior);
                    }
                    else
                    {
                        behavior.DataContractSurrogate = this.surrogate;
                    }
                }
            }

            this.HideEnumerationClassesFromMetadata(host);
        }
        internal void CreateMyDataContractSerializerOperationBehavior(OperationDescription operation)
        {
            DataContractSerializerOperationBehavior dataContractSerializerOperationbehavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();

            dataContractSerializerOperationbehavior.DataContractResolver  = this._resolver;
            dataContractSerializerOperationbehavior.DataContractSurrogate = this._surrogate;
        }
Ejemplo n.º 23
0
        public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
        {
            DataContractSerializerOperationBehavior
                dataContractSerializerOperationBehavior = description.Behaviors.Find <DataContractSerializerOperationBehavior>();

            dataContractSerializerOperationBehavior.DataContractResolver = new ProxyDataContractResolver();
        }
Ejemplo n.º 24
0
        private void CreateMyDataContractSerializerOperationBehavior(OperationDescription operationDescription)
        {
            DataContractSerializerOperationBehavior dataContractSerializerOperationbehavior =
                operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>();

            dataContractSerializerOperationbehavior.DataContractResolver = this.resolver;
        }
    public static void DataContractSerializationSurrogateTest()
    {
        OperationDescription od = null;
        DataContractSerializerOperationBehavior behavior = new DataContractSerializerOperationBehavior(od);

        behavior.SerializationSurrogateProvider = new MySerializationSurrogateProvider();

        DataContractSerializer dcs = (DataContractSerializer)behavior.CreateSerializer(typeof(SurrogateTestType), nameof(SurrogateTestType), "ns", new List <Type>());

        var members = new NonSerializableType[2];

        members[0] = new NonSerializableType("name1", 1);
        members[1] = new NonSerializableType("name2", 2);

        using (MemoryStream ms = new MemoryStream())
        {
            SurrogateTestType obj = new SurrogateTestType {
                Members = members
            };

            dcs.WriteObject(ms, obj);
            ms.Position = 0;
            var deserialized = (SurrogateTestType)dcs.ReadObject(ms);

            Assert.True(((MySerializationSurrogateProvider)behavior.SerializationSurrogateProvider).mySurrogateProviderIsUsed);

            for (int i = 0; i < 2; i++)
            {
                Assert.StrictEqual(obj.Members[i].Name, deserialized.Members[i].Name);
                Assert.StrictEqual(obj.Members[i].Index, deserialized.Members[i].Index);
            }
        }
    }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates the instance internal.
        /// </summary>
        /// <typeparam name="TServiceContract">The type of the service contract.</typeparam>
        /// <param name="channelFactory">The channel factory.</param>
        /// <returns></returns>
        private TServiceContract CreateInstanceInternalClaims <TServiceContract>(ChannelFactory <TServiceContract> channelFactory)
        {
            foreach (var operation in channelFactory.Endpoint.Contract.Operations)
            {
                var dataContractSerializerOperationBehavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dataContractSerializerOperationBehavior == null)
                {
                    dataContractSerializerOperationBehavior = new DataContractSerializerOperationBehavior(operation);

                    if (!operation.Behaviors.Contains(dataContractSerializerOperationBehavior))
                    {
                        operation.Behaviors.Add(dataContractSerializerOperationBehavior);
                    }
                }
                dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
            }

            // Add channelFactory.Endpoint Behaviors
            if (channelFactory.Endpoint.Behaviors.Find <CallerContextBehavior>() == null)
            {
                var endpointBehavior = new CallerContextBehavior();
                channelFactory.Endpoint.Behaviors.Add(endpointBehavior);
            }

#if DEBUG
            if (channelFactory.Endpoint.Behaviors.Find <ProfilerEndpointBehavior>() == null)
            {
                var profilerBehaviour = new ProfilerEndpointBehavior();
                channelFactory.Endpoint.Behaviors.Add(profilerBehaviour);
            }
#endif

            // Add channelFactory.Endpoint.Contract.Operations Behaviors

            // None

            /*
             *
             * var operationBehaviours = new List<IOperationBehavior>();
             *
             * foreach (var operationBehavior in operationBehaviors)
             * {
             *  foreach (var operation in channelFactory.Endpoint.Contract.Operations)
             *  {
             *      if (!operation.Behaviors.Contains(operationBehavior))
             *      {
             *          operation.Behaviors.Add(operationBehavior);
             *      }
             *  }
             * }
             */

            if (channelFactory.Credentials != null)
            {
                channelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
            }

            return(channelFactory.CreateChannelWithIssuedToken(GetSecurityTokenDirectFromLocalSts()));
        }
Ejemplo n.º 27
0
        public DataContractMessagesFormatter(OperationDescription desc, DataContractFormatAttribute attr)
            : base(desc)
        {
#if !MOBILE
            this.serializerBehavior = desc.Behaviors.Find <DataContractSerializerOperationBehavior>();
#endif
            this.attr = attr;
        }
Ejemplo n.º 28
0
        public void ApplyClientBehavior(OperationDescription description, System.ServiceModel.Dispatcher.ClientOperation proxy)
        {
            DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior =
                description.Behaviors.Find <DataContractSerializerOperationBehavior>();

            dataContractSerializerOperationBehavior.DataContractResolver =
                new ProxyDataContractResolver();
        }
Ejemplo n.º 29
0
        public static Object GetMessageFormatter(OperationDescription operation, bool isProxy)
        {
            DataContractSerializerOperationBehavior serializer = new DataContractSerializerOperationBehavior(operation);
            //我们调用操作行为DataContractSerializerOperationBehavior的GetFormatter方法来创建基于指定操作的消息格式化器。不过该方法是一个内部方法,所以我们是通过反射的方式来调用的。isProxy参数表示创建的是客户端消息格式化器(True)还是分发消息格式化器(False)。
            MethodInfo info = typeof(DataContractSerializerOperationBehavior).GetMethod("GetFormatter", BindingFlags.Instance | BindingFlags.NonPublic);

            return(info.Invoke(serializer, new object[] { operation, false, false, isProxy }));
        }
Ejemplo n.º 30
0
        public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
        {
            DataContractSerializerOperationBehavior
                                                           dataContractSerializerOperationBehavior =
                description.Behaviors.Find <DataContractSerializerOperationBehavior>();

            dataContractSerializerOperationBehavior.DataContractResolver = new ProxyDataContractResolver();
        }